Tag Archives: Java Script

LinkedIn jQuery Assessment

Here we have given the collection of jQuery Questions and Answers asked in Linked in assessment. LinkedIn Assessment is a test of particular skill. After passing this skill you will get a Bade in your profile and that you can share with your network.

Q1. What’s the difference between these two snippets?

$('button').on('click', function(){ alert('you clicked the button!'); });
$('button').click(function(){ alert('you clicked the button!'); });
  • Only the second one will work; jQuery does not have a function called .on.
  • The second snippet will not function.
  • Nothing .click(function) is shorter way to write .on('click', function).
  • The first snippet will execute for every button on the page, the second will only apply to the first button.

Q2. What does the following line of code do?

jQuery('p')

  • Loads a paragraph tag from a remote server using AJAX
  • Aliases jQuery to a variable p
  • Selects all paragraphs on the page
  • Creates a new paragraph tag and inserts it into the body tag

Q3. Given the following HTML, how could we use one line to hide or show the button?

<button class="btn btn-primary" type="submit">Continue to checkout</button>
  • $('.btn-primary').toggle();
  • $('.btn-primary').showHide();
  • $('.btn-primary').not(':visible').show();
  • $('.btn-primary').css({ display: 'block'});

Q4. Working with AJAX, we may run into situations where a piece of code should not be run until after multiple AJAX calls have completed successfully. Say we need to call two external services for JSON data (a list of students, and a list of classes). And only after retrieving those data will we perform some manipulations on a page. What is the preferred way for dealing with this scenario?

https://example.com/json-api/students
https://example.com/json-api/classes

  • [ ]
$.get([ 'https://example.com/json-api/students', 'https://example.com/json-api/classes' ], function(studentRequest, classRequest) { 
  // the rest of the code goes here 
});
  • [ ]
$.when( $.get('https://example.com/json-api/students'), $.get('https://example.com/json-api/classes') ).done(function(studentRequest, classRequest) { 
  // the rest of the code goes here 
});
  • [ ]
$.bind( $.get('https://example.com/json-api/students'), $.get('https://example.com/json-api/classes') ).done(function(studentRequest, classRequest) { 
  // the rest of the code goes here 
});
  • [x]
$.ajax('https://example.com/json-api/students', { success: function(studentRequest) { $.ajax('https://example.com/json-api/classes', { success: function(classRequest) { 
  // the rest of the code goes here 
} }); } });

Q5. Given the snippet of HTML below, what is the difference between the two lines that follow it?

<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
</ul>
$('ul').find('li').get(2);
$('ul').find('li').eq(2);
  • .get() retrieves a DOM element, and can’t be chained, eq() retrieves a jQuery object, and can be chained.
  • .get() retrieves a jQuery object, and can’t be chained, eq() retrieves a DOM element, and can be chained.
  • .get() retrieves a jQuery object, and is zero-indexed, eq() retrieves a DOM element, and is 1-indexed.
  • .get() retrieves a DOM element, and is zero-indexed, eq() retrieves a jQuery object, and is 1-indexed.

Q6. Suppose we want to have a ball created from an HTML element (id=ball) move down and to the right from its original location when clicked, and move back into its original place when finished. Given a starting point of this, which of these snippets would accomplish that goal?

$('#ball').click(function() {
  // Our code goes here
});
  • [x]
$(this).animate({ top: '+=100', left: '+=100', }, { duration: 600, complete: function() { $(this).animate({ top: '-=100', left: '-=100', }, 600) } });
  • [ ]
$(this).animate({ top: '-=100', left: '-=100', }, 600, function() { $(this).animate({ top: '+=100', left: '+=100', }, 600) });
  • [ ]
$(this).animate({ top: '=100', left: '=100', }, { duration: 600, complete: function() { $(this).animate({ top: 0, left: 0, }, 600) } });
  • [ ]
$(this).animate({ top: '100', left: '100', }, 600, function() { $(this).animate({ top: 0, left: 0, }, 600) });

Q7. Given the following CSS and HTML codes below, how could you apply the success class to the feedback div?

.success {
  color: green;
  background: #ddffdd;
}
<div class="feedback">
  Thank you for answering this survey.
</div>
  • $('.feedback').hasClass('.success');
  • $.css('.feedback', '.success');
  • $('.feedback').addClass('success');
  • $('.feedback').css('.success');

Q8. Below is an example page snippet that includes a couple of messages in a list, and a code snippet that retrieves a few hundred messages from a API endpoints using AJAX. How might we add these items to the page snippet in a way that avoids performance problems with DOM insertions?

<div class="message-area">
  <ul class="message-area--list">
    <li>Existing message 1</li>
    <li>Existing message 2</li>
  </ul>
</div>
$.get('//example.com/api/v1/message')
.done(function(data) {
  var tonsOfItems = data.messages;
  // add all these messages to a large page
});
  • tonsOfItems.map(function(item) { $('.message-area--list').append('<li>'+item+'</li>'); });
  • var tonsOfListItems = tonsOfItems.map(function(item)) { return '<li>'+item+'</li>'; }); $('.message-area--list').append(tonsOfListItems.join(''));
  • Removing the event handlers with JavaScript will be slower than removing them $.each(tonsOfItems, function(idx, item) { $('<li>'+item+'</li>').appendTo($messageList); });
  • $.each(tonsOfItems, function(idx, item) { $('.message-area--list').append('<li>'+item+'</li>'); });

Q9. What is jQuery?

  • jQuery is a bridge between Java and Javascript that makes native apps easier to write.
  • jQuery is a plugin for JavaScript that makes database queries easier to write.
  • jQuery is a collection of JavaScript functions that makes finding and manipulating elements on a page, AJAX, and other things easier.
  • jQuery is a Chrome extension that allows users to create their own extensions with just a few lines of JavaScript.

Q10. We want to create a new jQuery plugin called linkUpdater that can be chained onto other jQuery selector like a normal plugin. It should update all the links in the referenced collection so they open in new windows or tabs. Below is the first cut. What is one problem with this plugin?

"user strict";
($.linkUpdater = function() {
  this.find('a').attr('target', '_blank');
})( jQuery );
  • this needs to be wrapped, like $(this), in order to be chained in a plugin.
  • jQuery plugins can’t be safely authored in strict mode.
  • In order to be used by other code, plugins need to be added to the global namespace, not wrapped in a function expression.
  • Our plugin should extend jQuery.fn, not jQuery itself.

Q11. Generally speaking, when used on a web page, how should jQuery be installed, and why?

  • Just before the closing body tag, because we want to avoid blocking other resources from loading, and we use the ready method to make sure our code fires after the DOM is ready
  • Using the highest version number possible because only jQuery 3 and up are compatible with Internet Explorer 7
  • In the head tag because we want jQuery available as soon as possible
  • From a CDN because we want to be able to use jQuery online or offline

Q12. Given the following HTML, how could we make this button disappear from the page using jQuery?

<button class="btn btn-primary" type="submit">Continue to checkout</button>
  • $('.btn-primary').hide();
  • $('.btn-primary:visible').not();
  • $('.btn-primary').visibility(false);
  • $('.btn-primary').show(false);

Q13. What is the difference between $('header').html() and $('header').text()?

  • $('header').html() returns the inner HTML of the header. $('header').text() returns only the text
  • $('header').html() returns only the HTML tags used, without the text. $('header').text() returns only the text
  • $('header').html() strips all HTML from the header. $('header').text() always returns an empty string.
  • $('header').html() returns all headers in an HTML document. $('header').text() the first line of a text file.

Q14. When writing jQuery plugins, we often provide default options that may be overridden by the end user. What jQuery function is most useful for this purpose?

  • $.extend
  • $.clone
  • $.fn.extend
  • $.merge

Q15. There are times when you might want to programmatically trigger an event, instead of simply reacting to user input directly. Given this markup, Which choice will NOT cause a click event to the select box when the button is clicked?

<article>
  <div>
    Here's a button you can click: <button class="btn">Click Me</button>
  </div>
  <form>
    <p>
      Further down the page, there's a select box.
    </p>
    <select>
      <option value="1">One</option>
      <option value="2">One</option>
      <option value="3">One</option>
      <option value="4">One</option>
    </select>
  </form>
</article>
  • $('button').on('click.myApp', (function() { $('input[type=select]').trigger('click'); });
  • $('button').on('click', (function() { $('input[type=select]').click()); });
  • $('button').trigger(function() { $('input[type=select]').click(); });
  • $('button').click(function() { $('input[type=select]').click(); });

Q16. You have an absolutely positioned element inside a relatively positioned parent element, and you want to animate that element within its parent element. What jQuery function is most useful for finding the initial coordinates of the .animate-me?

<style>
  .parent {
    position: relative;
    top: 3em;
    width: 50%;
    min-height: 50vh;
    margin: 0 auto;
  }

  .animate-me {
    position: absolute;
    top: 40px;
    right: 30px;
  }
</style>

<div class="parent">
  <div class="animate-me">
    This box will move!
  </div>
</div>
  • $('.animate-me').offset();
  • $('.animate-me').each();
  • $('.animate-me').position();
  • $('.animate-me').offsetParent();

Q17. You want to work with AJAX using a Promise-like interface instead of nested callback functions. What jQuery API should you use?

  • jQuery.sub
  • jQuery.ajaxTransport
  • jQuery.Deferred
  • jQuery.proxy

Q18. What is tricky about jQuery’s nth- filters (:nth-child, :nth-of-type, etc.) relative to other filters?

  • Referring to lists of items, they are 1-indexed (like CSS), not 0-indexed (like JavaScript).
  • They don’t return the jQuery object, and cannot be chained.
  • They can return the wrong items if the DOM was recently manipulated.
  • They are not part of CSS, so they don’t get the performance benefits of passing through the document.querySelectorAll.

Q19. jQuery’s AJAX functions return objects that implement the Promise API. As a result, you can chain promises and avoid nested callbacks. What does that look like?

  • [x]
$.get('hhttp://httpbin.org/delay/2')
  .then(function(response) {
    // Data from first GET is here as 'response'
    return $.get('http://httpbin.org/delay/2');
  })
  .then(function(response) {
    // Data from second GET is here as 'response'
  });
  • [ ]
$.get('hhttp://httpbin.org/delay/2')
  .catch(function(response) {
    // Data from first GET is here as 'response'
    return $.get('http://httpbin.org/delay/2');
  })
  .done(function(response) {
    // Data from second GET is here as 'response'
  });
  • [ ]
$.get('hhttp://httpbin.org/delay/2', function(response1) {
  // Data from first GET is here as 'response1'

  $.get('http://httpbin.org/delay/2', function(response2) {
  // Data from second GET is here as 'response2'
  });
});
  • [ ]
$.get('hhttp://httpbin.org/delay/2')
  .then(function(response) {
    // Data from first GET is here as 'response'
    return response;
  })
  .get('http://httpbin.org/delay/2', function(response) {
    // Data from second GET is here as 'response'
  });

Q20. You want to have a ball that is created from an HTML element (id=ball) move down and to the right of its original location when clicked, and move back to its original place when finished. What snippet, added to the code below, would do this?

$('#ball').click(function() {
  // Our code goes here
});
  • [ ]
$(this).animate({
  top: '-=100',
  left: '-=100',
}, 600, function() {
  $(this).animate({
  top: '+=100',
  left: '+=100',
  }, 600)
});
  • [x]
$(this).animate({
  top: '+=100',
  left: '+=100',
}, {
  duration: 600,
  complete: function() {
  $(this).animate({
  top: '-=100',
  left: '-=100',
  }, 600)
  }
});
  • [ ]
$(this).animate({
  top: 100,
  left: 100,
}, 600, function() {
  $(this).animate({
  top: 0,
  left: 0,
  }, 600)
});
  • [ ]
$(this).animate({
  top: 100,
  left: 100,
}, {
  duration: 600,
  complete: function() {
  $(this).animate({
  top: 0,
  left: 0,
  }, 600)
  }
});

Q21. The way .wrap() works is sometimes misunderstood. Given the DOM and jQuery snippets below, what does the modified DOM snippet look like?

<div id="container">
  <div class="item">Here's an item</div>
</div>
$('#container').wrap('<div class="wrapper"></div>').css('border', '2px solid red');
  • [ ]
<div class="wrapper" style="border: 2px solid red;">
  <div id="container">
    <div class="item">Here's an item</div>
  </div>
</div>
  • [x]
<div class="wrapper">
  <div id="container" style="border: 2px solid red;">
    <div class="item">Here's an item</div>
  </div>
</div>
  • [ ]
<div id="container" style="border: 2px solid red;">
  <div class="wrapper">
    <div class="item">Here's an item</div>
  </div>
  </div>
  • [ ]
<div id="container">
  <div class="wrapper" style="border: 2px solid red;">
    <div class="item">Here's an item</div>
  </div>
</div>

Q22. How can you select the following blockquote AND the list in a single call to jQuery() without chaining?

<div class="quotes">
  <blockquote data-favorite="false">A quote</blockquote>
  <blockquote data-favorite="true">A favorite quote</blockquote>
  <blockquote data-favorite="false">A quote</blockquote>
  <blockquote data-favorite="false">A quote</blockquote>
</div>

<ul class="menu-first">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
</ul>
  • $('.quotes + .menu-first')
  • $('.quotes .menu-first')
  • $('.quotes, .menu-first')
  • $('.quotes' + '.menu-first')

Q23. Effects like show, hide, fadIn, and fadeOut can be called with no arguments, but can also take arguments for how long they should last. Which is NOT a duration argument supported by these functions?

  • “fast”
  • “extreme”
  • 2000
  • “slow”

Q24. Though jQuery offers visual effects, it is considered a best practice to use CSS to set up different states triggered by classes, where it makes sense. What’s the easiest way to enable and disable a class bounce on an element with the ID dialog?

  • $('#dialog').classToggle('bounce')
  • $('#dialog.bounce').removeClass().addClass()
  • $('#dialog').addOrRemoveClass('bounce')
  • $('#dialog').toggleClass('bounce')

Q25. What is the main difference between selectors and filters?

  • Selectors are used to refine the content that filters have been applied to.
  • Selectors are used to find and select content in a page. Filters are used to refine the results of selectors.
  • Filters are used to remove content from the page. Selectors are used to add content to the page
  • There is no real difference. They are both used to build up lists of page content.

Q26. You want to create a custom right-click menu. How might you start the code?

  • $('#canvas').on('click.right', function(){ console.log('Handled a right-click') });
  • $('#canvas').on('contextual', function(){ console.log('Handled a right-click') });
  • $('#canvas').on('contextmenu', function(){ console.log('Handled a right-click') });
  • $('#canvas').on('rightclick', function(){ console.log('Handled a right-click') });

Q27. What is the correct way to check how many paragraphs exist on a page using jQuery?

  • $('p').count()
  • $('p').length
  • $('*').find('p')
  • $('p').length()

Q28. As with many areas of JavaScript, keeping track of the meaning of this is important and sometimes tricky. What does this mean at each of the two points in this custom plugin snippet?

$.fn.customPlugin = function() {
  // Point 1

  return this.each(function() {
    // Point 2
  })
}
$(document).customPlugin();
  • At Point 1, this means a jQuery object. At Point 2, it means a DOM element.
  • In this case, they mean the same thing: a jQuery object.
  • In this case, they mean the same thing: a DOM element.
  • At Point 1, this means a DOM element. At Point 2, it means a jQuery object.

Q29. How can you make the first list item bold and the next item oblique, in a single statement chain?

<ul class="menu-first">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
</ul>
  • [ ]
$('.menu-first > li')
  .eq(0)
  .css('font-weight', 'bold')
  .eq(1)
  .css('font-style', 'oblique');
  • [ ]
$('.menu-first > li')
  .first()
  .css('font-weight', 'bold')
  .after()
  .css('font-style', 'oblique');
  • [ ]
$('.menu-first > li')
  .first()
  .css('font-weight', 'bold')
  .second()
  .css('font-style', 'oblique');
  • [x]
$('.menu-first > li')
  .eq(0)
  .css('font-weight', 'bold')
  .next()
  .css('font-style', 'oblique');

Q30. Which CSS selectors can you NOT use in jQuery?

  • You cannot use multiple class selectors such as .class1.class2.
  • You cannot use pseudo-classes such as :not or :last-of-type.
  • You cannot use IDs and classes together, such as #element.class.
  • None. All CSS selectors are compatible in jQuery.

Q31. Starting with some DOM elements in the nested structure below, you assign listeners for the same event to a child element and one of the parents using the JavaScript that follows. You want to ensure that when .leaf is clicked, only its event handler will be fired, instead of the click bubbling up and also firing the parent’s click handler. What do you need to add to its handler function?

<ul class="items" id="main-menu">
  <li>Item 1<ul>
    <li class="leaf">Sub Item 1</li>
    <li>Sub Item 2</li>
  </ul></li>
</ul>
$('.leaf').click( function(event) { console.log('Sub Item 1 got a click'); } );
$('#main-menu').click( function(event) { console.log('Main menu got a click'); } );
  • event.capture();
  • event.stopPropagation();
  • event.preventDefault();
  • event.stop();

Q32. Using event delegation, you can listen for events on a lot of different items without having to attach separate listeners to each one. But there are times when you may want to check the type of item receiving the event before doing anything, such as checking if an image was clicked versus a text field. Given the starter code below, which choice shows what jQuery provides to help with that process?

<div id="sidebar">
  <img src="fancy-button.png" alt="Pick Me">
  <input type="text" placeholder="Fill in something">
</div>
$('#sidebar').click(function(evt) {
  var $target = $(evt.target);

  // What goes here?
});
  • $($target.get(0) + ':image')
  • $('img').is($target)
  • $target.filter('img')
  • $target.is('img')

Q33. There are many ways to create elements that can be added to the page. Which answer is NOT one of those ways, assuming you have the following on the page?

<div id="elements"></div>
  • [ ]
$("#elements").append($('<p class="appended">As an HTML string</p>'));
  • [ ]
var p = document.createElement('p');
var text = document.createTextNode('As a DOM element');
p.appendChild(text);
$("#elements").append(p);
  • [x]
$("#elements").append(<p class="appended">As a JSX object</p>);
  • [ ]
$("#elements").append($('<p>', {
  "class": 'appended',
  'text': "As an attribute object"
}));

Q34. The .addClass() and .removeClass() methods can accept functions as arguments. What does this function do?

$('#menu').addClass(function() {
  return $('body').attr('class');
});
  • It adds the first class found on the body element to the #menu element.
  • It adds all classes found on the #menu element to the body tag.
  • It replaces any classes on the #menu element with all classes from the body tag.
  • It adds all classes found on the body element to the #menu element.

Q35. You’re working on a site that uses an old version of jQuery, and you want to update to a newer version. What’s the most efficient way to do so?

  • Install the newer version of jQuery, go through each script one by one, and fix what looks broken.
  • Read the change notes for the newer version of jQuery, fix all scripts, install the newer version, and fix anything that remains broken.
  • Install the newer version of jQuery as well as its Migrate plugin, fix all warnings, and uninstall the Migrate plugin.
  • Install the newer version of jQuery at the same time, and use jQuery.noConflict() on pages that need the older version.

Q36. Let’s say you have a page with just one link on it. How can you change the anchor tag so it links to example.com?

  • $('a').attribute('href', 'http://www.example.com')
  • $('a').attr('href', 'http://www.example.com')
  • $('a').data('href', 'http://www.example.com')
  • $('a').href('http://www.example.com')

Q37. What does $() mean in jQuery?

  • It is an alias to the main core method of jQuery itself—the same as writing jQuery().
  • It is a utility function that selects the first element from the document.
  • It is a shorter way to write document.getElementById().
  • It is a utility function that selects the last element from the document.

Q38. Along with DOM traversal and manipulation, jQuery offers several general-purpose helper functions that fill in some JavaScript gaps, especially before ES2015. Which is NOT a jQuery utility function?

  • jQuery.each, a general purpose iterator for looping over arrays or objects
  • jQuery.isNumeric, which can check whether its argument is, or looks like, a number
  • jQuery.extend, which can merge objects and make complete deep copies of objects
  • jQuery.isMobile, which can tell whether the user is using a mobile browser

Q39. Given this set of checkboxes, how can you select the ones that have the phrase “sun” as part of the value?

<input type="checkbox" name="artists[]" value="sun-ra">
<input type="checkbox" name="artists[]" value="otis-redding">
<input type="checkbox" name="artists[]" value="captain-beefheart">
<input type="checkbox" name="artists[]" value="king-sunny-ade">
<input type="checkbox" name="artists[]" value="weather-report">
  • $('checkbox').val(/sun/);
  • $('input[value*="sun"]');
  • $('input[value|="sun"]');
  • $('input:checkbox').attr('value', '*sun*');

Q40. How can you get an AJAX request to go through without triggering any of jQuery’s AJAX events?

  • Set the type option to “none”.
  • Set the processData option to false.
  • Set a success callback that returns false.
  • Set the option “global” to false.

Q41. How do you change the current value of a text field with the class .form-item to “555-1212”?

  • $.val('.form-item', '555-1212');
  • $('.form-item').val('555-1212');
  • $('.form-item').data('value', '555-1212');
  • $('.form-item').set('value', '555-1212');

Q42. How would you fire a callback when any AJAX request on a page has completed?

  • $('body').ajaxComplete(function() { console.count('An AJAX request completed'); });
  • $(document).on('ajax-complete', function() { console.count('An AJAX request completed'); });
  • $('body').on('ajaxComplete', function() { console.count('An AJAX request completed'); });
  • $(document).ajaxComplete(function() { console.count('An AJAX request completed'); });

Q43. Given this set of checkboxes, how can you select the one with the value “blimp”?

<input type="checkbox" name="songs[]" value="satisfaction">
<input type="checkbox" name="songs[]" value="respect">
<input type="checkbox" name="songs[]" value="blimp">
<input type="checkbox" name="songs[]" value="saturn">
<input type="checkbox" name="songs[]" value="penguins">
  • $('input[value="blimp"]');
  • $('input[value!="blimp"]');
  • $('checkbox').val('blimp');
  • $('input:checkbox').attr('value', 'blimp');

Q44. Given this snippet of HTML and jQuery code, what does the jQuery do?

<ul class="menu">
  <li><a href="#" class="active">Home</a></li>
  <li><a href="#">Page 2</a></li>
</ul>
<ul class="active submenu">
  <li><a href="#">Subpage 1</a></li>
  <li><a href="#">Subpage 2</a></li>
</ul>
var m = $('.menu'), sm = $('.submenu');
m.add(sm);
m.css('font-weight', 'bold');
  • It makes all the menu items bold.
  • It throws an exception on line 3.
  • It makes the first set of menu items, not the second, bold.
  • It makes the second set of menu items, not the first, bold.

Q45. You want to take a block of type and animate it to a larger size with jQuery. The following HTML and JavaScript behaves strangely. What is the issue?

<div id="type" style="font: 1em/1.5 helvetica, arial, sans-serif; background: #ffc; padding: 0">
  Animate me!
</div>
$('#type').animate({
  fontSize: '+=1em'
}, 3000);
  • jQuery does not support ems and will make the type 1 pixel larger instead of 1 em larger.
  • jQuery cannot override CSS in a style attribute, so the font size will not change.
  • The font size was set with a shorthand property, so jQuery will not animate the font size at all.
  • The font size was set with a shorthand property, so jQuery will start the animation from 0 instead of from 1 em.

Q46. When using the clone() function to duplicate an element, what is one of the main concerns your code needs to watch out for?

  • The clone() function may ignore data attributes on the original elements.
  • The clone() function may result in elements with duplicate ID attributes.
  • The clone() function may remove CSS classes from the cloned elements.
  • The clone() function may not respect the attribute order of the original elements.

Q47. When incorporating a plugin into a project, what are the important steps for basic installation and usage?

  • The jQuery script tag must come first, followed by the plugin, followed by your custom scripts, all preferably at or near the bottom of the page.
  • Your custom scripts must appear first in the document <head>, followed by jQuery, followed by the plugin.
  • The jQuery script tag and the plugin script tag must appear in the document <head>, and your custom scripts can follow anywhere on the page.
  • The jQuery script tag must appear in the document <head>, but the plugin and your custom scripts can appear anywhere else in any order.

Q48. These two script tags show different ways of using jQuery’s ready() method. What is true about both approaches?

<script>
  $(function() {
    // The rest of my code goes here
  });
</script>

<script>
  jQuery(document).ready(function($) {
    // The rest of my code goes here
  });
</script>
  • The code inside them can manipulate the DOM safely, knowing the browser has loaded it fully.
  • The code inside them can manipulate images on the page safely, knowing they have fully downloaded to the browser.
  • The code inside them will be run exactly once per user session.
  • The code inside them is not aware of the DOM.

Q49. Which property of the jQuery event object references the DOM object that dispatched an event?

  • self
  • target
  • object
  • source

Q50. Which describes how jQuery makes working with the DOM faster?

  • jQuery optimizes the DOM in a background thread, making updates faster.
  • jQuery avoids using the DOM at all.
  • jQuery uses a virtual DOM that batches updates, making inserts and deletes faster.
  • jQuery code to perform DOM manipulation is shorter and easier to write, but does not make DOM operations faster.

Q51. There are some issues with this snippet of jQuery. First, it is manipulating CSS directly, rather than manipulating classes and leaving the CSS in stylesheets. What else in this code is best to avoid?

$('.item').css('background-color', 'red');
// some other code here
var firstSubItem = $('.item').find('.sub-item').get(0);
// some other code here too
$('.item').parents('.navigation').css('font-weight', 'bold');
  • The .css() method accepts only an object, not two separate arguments. This will trigger an exception that should be caught.
  • The $('.item') selection is being made several times. This should be cached in a variable for (however slightly) better performance and easier maintainability.
  • The call to .parents() is in an inefficient place.
  • All the calls to $('.item') should be chained together as a single executable line for better performance.

Q52. Which choice is an example of statement chaining?

  • var $p = $('p'); console.log($p.length);
  • $('p').find('a').children('li');
  • $('p > a > li');
  • $('p'); $('a'); $('li');

Q53. How can you ensure that some code executes only when a class active appears on an element?

  • $('.element').attr('class', 'active')
  • $('.element').with('.active')
  • $('.element').hasClass('active')
  • $('.active').then()

Q54. jQuery has a main function for handling AJAX, and several shorthand function including load() that make calling that main function easier. Given this HTML snippet, how can you insert only the second snippet from the source.html file (div#one) into the #load-me div on-demand via AJAX?

<div id="load-me">
  This area will be replaced with AJAX loaded content.
</div>

<div id="one">
  <h1>First Piece</h1>

  <p>
    Lorem ipsum duis maximus quam condimentum dolor eleifend scelerisque.
  </p>
</div>

<div id="two">
  <h1>Second Piece</h1>

  <p>
    Lorem ipsum proin facilisis augue in risus interdum ornare.
  </p>
</div>
  • $('#load-me').get('source.html#one');
  • $('#load-me').get('source.html #one');
  • $('#load-me').load('source.html #one');
  • $('#load-me').load('source.html', '#one');

Q55. Given this HTML list and subsequent two lines of jQuery, what is the difference in the behavior of .closest() and .parents()?

<ul class="items" id="main-menu">
  <li>Item 1 <ul id="sub-menu">
  <li class="leaf">Sub Item 1</li>
  <li>Sub Item 2</li>
  </ul></li>
</ul>
$('.leaf').closest('.items');
$('.leaf').parents('.items');
  • .closest() returns .leaf and #main-menu; .parents() returns #main-menu and #sub-menu.
  • .closest() returns .leaf and #sub-menu; .parents() returns #main-menu and #sub-menu.
  • .closest() returns only #main-menu; .parents() returns #main-menu and #sub-menu.
  • .closest() returns only #sub-menu; .parents() returns #main-menu and #sub-menu.

Q56. What does this line of code do?

$('ul > li:first-child');
  • selects the first list item inside all unordered lists on the page
  • selects the first list item inside the first unordered list on the page
  • selects the first element inside any list items on the page
  • creates a predefined CSS selector that can be reused later

Q57. Below is a list of items that you want to be clickable and an event handler function. How can you assign the event handler to every item in the list in a way that is most performant, and also that ensures that the handler is called even if more items are added to the list programmatically?

<ul class="clickable-list">
  <li>First Item</li>
  <li>Second Item</li>
  <li>Third Item</li>
  <li>Fourth Item</li>
  <li>Fifth Item</li>
</ul>
function listResponder(evt) {
  console.log('You clicked a list item that says', evt.target.innerText);
}
  • $('.clickable-list).click(listResponder);
  • $('.clickable-list).on('click', 'li', listResponder);
  • $('.clickable-list).on('click, append', listResponder);
  • $('.clickable-list).each(function() { $(this).click(listResponder); });
Spread the love

jQuery CDN

What is CDN?

A content delivery network or content distribution network (CDN) is a distributed system where users can store data and can access cached content. Usually, we store images, Style sheets, Javascript files, etc.

The use of CDN is very efficient when we have to access some static files. It directly connects to our physical server and provides the resources required, because it connects to the proxy server available in the locality and the nearest.

Que: Why we should Use jQuery CDN?

The CDN sends the data from the cache if available. In most of the cases the user has already history and they already have cached the query. When a new website is opened and using the CDN jQuery, CDN refers to the cached file and hence the zero latency is observed.

  1. Removes server Server Delay
  2. Secure and freely available

Must Read: Javascript Interview Questions

Que: How to use jQuery CDN?

As we all know we use CDN a proxy network to store the static files like images, CSS and javascript files. There are two methods that we can choose from to add jQuery in our application. Any of these methods can facilitate jQuery functionality in our application.

1.Hosted jQuery Files:

We can download a jquery file and upload it to our server and we can fetch it in our application. But downloading from their can increase the loading time of our application and It may take more time to produce the first visible snap of page.

2.jQUery CDN

CDN Hosted jQUery is then the solution of the problem in method one. jQuery CDN is the better way to include jQuery functionality in our application. jQuery CDN removes the server latency and TAT i.e. turn around time. Since CDN is a highly equipped Infrastructure, definitely the speed will be considerable.

We can found the Official jQuery CDN here :

The latest stable version: https://code.jquery.com/

There are two ways of including jQuery CDN:

1. jQuery CDN from Google

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

2. jQuery CDN from Google

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>

I hope you will get to know what is CDN and how it works jQuery. Now you can understand the difference between the hosted jQuery and CDN jQuery.

Spread the love

React JS Interview Questions

React is a JavaScript library for building user interfaces. It is based on ES6 Script Extension. ES6 is ECMA Script 2015. React provides seamless manipulation and rendering of DOM objects.

We also consider it as a Popular JavaScript framework based on Redux Architecture. React is developed and maintained by Facebook Inc. React was first created by Jordan Walke, a software engineer working for Facebook. Facebook is using React since 2011 and Instagram since 2012.

So it is a necessary skill to have in your stack. You will be considered if you are an expert in React JS.  Here are some important React Js Interview Questions and Answers useful for Javascript Interview.

What is React?

React is an open-source front-end JavaScript library that is used for building user interfaces especially for single-page applications. It is used for handling the view layer for web and mobile apps. React was created by Jordan Walke, a software engineer working for Facebook. React was first deployed on Facebook’s News Feed in 2011 and on Instagram in 2012.  Read more about – What is React JS?

What are the major features of React?

The major features of React are:

  • It uses VirtualDOM instead of RealDOM considering that RealDOM manipulations are expensive.
  • Supports server-side rendering.
  • Follows Unidirectional data flow or data binding.
  • Uses reusable/composable UI components to develop the view.

What is JSX?

JSX is a XML-like syntax extension to ECMAScript (the acronym stands for JavaScript XML). Basically it just provides syntactic sugar for the React.createElement() function, giving us expressiveness of JavaScript along with HTML like template syntax.

In the example below the text inside the <h1> tag returns as JavaScript function to the render function.

class App extends React.Component {

  render() {

    return(

      <div>

        <h1>{'Welcome to React world!'}</h1>

      </div>

    )

  }

}

What are Pure Components?

React.PureComponent is exactly the same as React. Component except that it handles the shouldComponentUpdate() method for you. When props or state changes, PureComponent will do a shallow comparison on both props and state. A component, on the other hand, won’t compare current props and state to next out of the box. Thus, the component will re-render by default whenever shouldComponentUpdate is called.

What is the difference between state and props?

Both props and state are plain JavaScript objects. While both of them hold information that influences the output of render, they are different in their functionality with respect to the component. Props get passed to the component similar to function parameters whereas the state is managed within the component similar to variables declared within a function.

What is the use of refs?

The ref is used to return a reference to the element. They should be avoided in most cases, however, they can be useful when you need direct access to the DOM element or an instance of a component.

What is Virtual DOM?

The Virtual DOM (VDOM) is an in-memory representation of Real DOM. The representation of a UI is kept in memory and synced with the “real” DOM. It’s a step that happens between the render function being called and the displaying of elements on the screen. This entire process is called reconciliation.

What is the difference between Shadow DOM and Virtual DOM?

The Shadow DOM is a browser technology designed primarily for scoping variables and CSS in web components. The Virtual DOM is a concept implemented by libraries in JavaScript on top of browser APIs.

What is React Fiber?

Fiber is the new reconciliation engine or reimplementation of the core algorithm in React v16. The goal of React Fiber is to increase its suitability for areas like animation, layout, gestures, ability to pause, abort, or reuse work and assign priority to different types of updates; and new concurrency primitives.

What is the main goal of React Fiber?

The goal of React Fiber is to increase its suitability for areas like animation, layout, and gestures. Its headline feature is incremental rendering: the ability to split rendering work into chunks and spread it out over multiple frames.

What are the controlled components?

A component that controls the input elements within the forms on subsequent user input is called Controlled Component, i.e, every state mutation will have an associated handler function.

For example, to write all the names in uppercase letters, we use handleChange as below,

handleChange(event) {

  this.setState({value: event.target.value.toUpperCase()})

}

How to create props proxy for the HOC component?

You can add/edit props passed to the component using props proxy pattern like this:

function HOC(WrappedComponent) {

  return class Test extends Component {

    render() {

      const newProps = {

        title: 'New Header',

        footer: false,

        showFeatureX: false,

        showFeatureY: true

      }

      return <WrappedComponent {...this.props} {...newProps} />

    }

  }

}

What is the context?

Context provides a way to pass data through the component tree without having to pass props down manually at every level. For example, authenticated user, locale preference, UI theme need to be accessed in the application by many components.

const {Provider, Consumer} = React.createContext(defaultValue)

What is a child prop?

Children are a prop (this.prop.children) that allow you to pass components as data to other components, just like any other prop you use. Component tree put between component’s opening and closing tag will be passed to that component as children prop.

There are a number of methods available in the React API to work with this prop. These include React.Children.map, React.Children.forEach, React.Children.count, React.Children.only, React.Children.toArray. A simple usage of children prop looks as below,

 

const MyDiv = React.createClass({

  render: function() {

    return <div>{this.props.children}</div>

  }

})

ReactDOM.render(

  <MyDiv>

    <span>{'Hello'}</span>

    <span>{'World'}</span>

  </MyDiv>,

  node

)

What is reconciliation?

When a component’s props or state change, React decides whether an actual DOM update is necessary by comparing the newly returned element with the previously rendered one. When they are not equal, React will update the DOM. This process is called reconciliation.

How to set a state with a dynamic key name?

If you are using ES6 or the Babel transpiler to transform your JSX code then you can accomplish this with computed property names.

 

handleInputChange(event) {

  this.setState({ [event.target.id]: event.target.value })

}

 

Why does React use className over class attribute?

class is a keyword in JavaScript, and JSX is an extension of JavaScript. That’s the principal reason why React uses className instead of class. Pass a string as the className prop.

render() {

  return <span className={'menu navigation-menu'}>{'Menu'}</span>

}

Why are fragments better than container divs?

  1. Fragments are a bit faster and use less memory by not creating an extra DOM node. This only has a real benefit on very large and deep trees.
  2. Some CSS mechanisms like Flexbox and CSS Grid have special parent-child relationships, and adding divs in the middle makes it hard to keep the desired layout.
  3. The DOM Inspector is less cluttered.

 

What are stateless components?

If the behavior is independent of its state then it can be a stateless component. You can use either a function or a class for creating stateless components. But unless you need to use a lifecycle hook in your components, you should go for function components. There are a lot of benefits if you decide to use function components here; they are easy to write, understand, and test, a little faster, and you can avoid this keyword altogether.

What are the advantages of React?

  1. Increases the application’s performance with Virtual DOM.
  2. JSX makes code easy to read and write.
  3. It renders both on client and server-side (SSR).
  4. Easy to integrate with frameworks (Angular, Backbone) since it is only a view library.
  5. Easy to write unit and integration tests with tools such as Jest.

 

What are the limitations of React?

  1. React is just a view library, not a full framework.
  2. There is a learning curve for beginners who are new to web development.
  3. Integrating React into a traditional MVC framework requires some additional configuration.
  4. The code complexity increases with inline templating and JSX.
  5. Too many smaller components leading to over-engineering or boilerplate.

How are error boundaries handled in React v15?

React v15 provided very basic support for error boundaries using the unstable_handleError method. It has been renamed to componentDidCatch in React v16.

What is the purpose of the render method of react-dom?

This method is used to render a React element into the DOM in the supplied container and return a reference to the component. If the React element was previously rendered into a container, it will perform an update on it and only mutate the DOM as necessary to reflect the latest changes.

ReactDOM.render(element, container[, callback])

 

If the optional callback is provided, it will be executed after the component is rendered or updated.

How to use innerHTML to React?

The dangerouslySetInnerHTML attribute is React’s replacement for using innerHTML in the browser DOM. Just like innerHTML, it is risky to use this attribute considering cross-site scripting (XSS) attacks. You just need to pass an __html object as key and HTML text as value.

In this example MyComponent uses dangerouslySetInnerHTML attribute for setting HTML markup:

function createMarkup() {

  return { __html: 'First &middot; Second' }

}


function MyComponent() {

  return <div dangerouslySetInnerHTML={createMarkup()} />

}

How events are different in React?

Handling events in React elements has some syntactic differences:

  1. React event handlers are named using camelCase, rather than lowercase.
  2. With JSX you pass a function as the event handler, rather than a string.

What will happen if you use setState() in the constructor?

When you use setState(), then apart from assigning to the object state React also re-renders the component and all its children. You would get an error like this: Can only update a mounted or mounting component. So we What will happen if you use setState() in the constructor? What will happen if you use setState() in the constructor? need to use this.state to initialize variables inside the constructor.

How do you conditionally render components?

In some cases, you want to render different components depending on some state. JSX does not render false or undefined, so you can use conditional short-circuiting to render a given part of your component only if a certain condition is true.

const MyComponent = ({ name, address }) => (

  <div>

    <h2>{name}</h2>

    {address &&

      <p>{address}</p>

    }

  </div>

)

If you need an if-else condition then use a ternary operator.

const MyComponent = ({ name, address }) => (

  <div>

    <h2>{name}</h2>

    {address

      ? <p>{address}</p>

      : <p>{'Address is not available'}</p>

    }

  </div>

)

 

Spread the love

What is React JS?

React is a JavaScript library for building user interfaces. It is based on ES6 Script Extension. ES6 is ECMA Script 2015. React provides seamless manipulation and rendering of DOM objects.

We also consider it as a Popular JavaScript framework based on Redux Architecture. React is developed and maintained by Facebook Inc. React was first created by Jordan Walke, a software engineer working for Facebook. Facebook is using React since 2011 and Instagram since 2012.

It can be used to render UI for any type of device like Mobile, Desktop and tablets. React use JSX syntax to create dynamic HTML DOM objects. In JSX HTML is part of the Javascript code. JSX stands for JavaScript XML.JSX is an XML/HTML like extension to JavaScript.

According to Official reactjs.org:

React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It lets you compose complex UIs from small and isolated pieces of code called “components”.

Reactjs Example:

A Simple Example of JSX:

const MyElement = <h1>Hello World!</h1>;

Features of React JS:

There is a number of features that React is Having. Let have a look at them:

#1.Declarative
Declarative views make your code more predictable and easier to debug. It renders and manipulates just the particular and right component when some change in data occurs and not the whole HTML page.

#2.Component-Based
Break the whole Applications in a simple component. Each component is responsible for some particular rendering. This makes easy to maintain and make it modular. Simple component are used to make a complex and enrich UI. Since Component is written using ES6, we can separate state from DOM.

Example of Component :

class HelloWorld extends React.Component {
  render() {
		return (
			<div>
			Hello {this.props.name}
			</div>
		);
	}
}
ReactDOM.render(
	<HelloWorld name="World" />,
	document.getElementById('hello-world')
);


#3.State Less and State Full Components:
React JS allow us to compose stateless and stateful component. Where we can decide to separate our DOM from the state. A simple stateless component can be used in the application to render the data from different states.

#4. Flexible
When it comes to flexibility, React gives freedom to the composer to create components, modules, and logic to make an application to work efficiently.

#5.Extensible
Plugins and components make it Extensible to any level. Users can create any number of Components and plugins as per convenient. It never restricts. We can use external plugins also.

#6.React Native
React has developed native libraries that are compatible with Android, iOS and UDP applications. So we can develop and deploy native applications for these Operating Systems.

#7.One-way data Flow:
In a React Js application, the components are not allowed to modify any property but can pass a call back function to do so. We can pass a set of values to the component to render the HTML with desired properties.

#8. Fast and Seamless Experience
All the above features make React Seamless and Fast. React provide a fast rendering of component because it renders only the right component where data has been changed.

Why We Should Choose React JS?

  • It is simple as an ES6 script.
  • Easy to learn and a huge community over the internet.
  • It has native libraries, so a single technology can work for mobile, and web applications.
  • It has one-way data binding.
  • It contains self- contained components.
  • Exceptional performance.
  • High flexibility, maintainability, and testability.

You have got a clear picture of React JS. What is React JS and what are the main features that let developers move towards it.

Spread the love

Email Validation in Javascript

Email ID is a very important part of a user account. When an application invites the user to create accounts or allow users to subscribe to a newsletter, they ask for an email ID. Email ID is the initial medium of formal communication, so this is mandatory that the email is received should be in a valid format.

Here we are going to explain how to do Email Validation in JavaScript?

An Email is a string with a very simple structure. There are two parts :

  1. unique_id
  2. Domain Name

These two parts are separated by @. 

Suppose interviewsortout@gmail.com is an email where the first part interviewsortout is Unique User ID at the gamil.com domain.

The length of the unique_id part may be up to 64 characters long and domain name may be up to 253 characters.

The first part of an email may have the following characters :

  • May contain Alphabets either in upper case or in lower case.
  • Any Digits 
  • Special character except @  
  • a dot(.) can not be the first and last character of uique_id

The second part is the domain name. So we can have .com, .in, .info, .net, .au etc type of domain. 

Have a look at some valid email addresses:

  • info@interviewsortout.com
  • interviewsortout@gmail.com
  • sibbu2005@gmail.com
  • interview.sortout@gmail.com
  • userid@example.net
  • 23_user_23@example.in

 

Now Have a look on Invalid Email Address : 

  • @not present : [Example.user.com]
  • Top Level Domain can not be started with dot ( . ) : [user@.com.my ]
  • @user.example.net [ No character before @ ]
  •  invalid top level domain   [exampleuser123@gmail.b]
  • an email can not start with “.” [ .user@example.net ]
  • double dots are not allowed [interview..sortout@gmail.com]

 

To do email validation in javascript we will use Regular Expression to match that the given email address matches the criteria of a valid domain.

 

Regular Expression for email validation in JavaScript:

 

/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

 

A complete Solution of Email Validation in Javascript :

Spread the love

Angular Basic Interview Questions and Answers

Angular is a TypeScript-based open-source web application framework Developed and Designed by Google. Angular is the majority used for One Page application and Material Design Concepts for Nowadays. It allows us to manipulate the HTML document and bind data with DOM seamlessly.

Angular is an Integral Part of the web at the age of today. It is widely used by may tech-giants and MNCs. Even We can say It is a need of time to have a skill like angular in your stack. Without angular, your stack is not completed.

We are providing a number of Best Angular Questions along with answers for the Freshers level. They are also useful for Developers having experienced more than 2 years. The facts are based on angular 2 interview questions and also relevant to the latest versions of angular.

Angular interview questions are key to success in a technical Interview you are going for. It is a summary of concepts and a test of Angular Questions also.

What is Angular JS?

Angular JS is a TypeScript framework used for developing single-page applications. It is maintained by Google.

What are the advantages of using Angular JS?

  1. Modular Structure based on MVC.
  2. Real-time one-way and two-way data binding and DOM manipulation.
  3. Reusable components
  4. Inbuilt form validation rules

What are the main features of Angular JS?

  1. Seamless rendering
  2. MVC Structure
  3. SuperScript of JavaScript
  4. Suitable for One-page application
  5. Supports Cache
  6. Service Worker Support
  7. Tree Shaking

What is Template?

Templates are the view part of MVC and HTML documents containing directives, elements, and attributes. A template is used to display results on browsers.

What is a controller?

A controller is an Object, defined by object constructor as per Angular 2.

What are the directives in Angular JS?

Directives are the HTML attributes for angular. Attributes prefixed by “ng-” and used to extend the scope of dom.

What is the difference between jQuery and Angular JS?

jQuery is a javascript library and based on functional programming features.jQuery used to handle events, animation, dom, etc. Whereas Angular is rich in UI and seamless in dynamic templating having EASY DOM manipulation.

What are the modules in Angular JS?

A module in AngularJS is a packet having different necessary items in it like controller, filters, directives, services.

What is Data Binding?

Data binding is the key feature of Angular and many such frameworks. Data binding refers to the synchronization of information. The value stored in variables reflects at the places where are used within no time and without change of frame. There are two types of data binding-

  1. One way data binding
  2. Two-way data binding

What are one-way bindings?

One way data binding is the synchronization from Modal to View. When there is a change in Model it reflects in View and in forms. But unable to change the value in a model when changes happen in view after user input.

What are two-way bindings?

Two-way binding is the bi-direction syncing of data. This reflects the data either side when changes occur. Changes in model lead to reflection in View and Changes in view reflects in Modal.

What is the component?

Components are the basic building blocks in applications. They are completed with MVC sub-components. They handle data, render views and accept user inputs.

What is the provider?

As per https://docs.angularjs.org
A provider is an object with a $get() method. The injector calls the $get method to create a new instance of a service. The Provider can have additional methods that would allow for configuration of the provider.$provide is used to create new providers.

What is the link?

Angular JS has a directive link on which link function is based. We can define a directive’s API using these functions.

What is the factory method?

A factory is a function that returns an object. They are reusable singleton objects and can be used as injections. We can create using factory.

What do you mean by ng-app,ng-init,ng-model?

ng-app: this is the fundamental directive to create an Angular JS Application.
ng-init: initialize the application and data
ng-model: define the model to be used in an application.

Can we use the jQuery library in Angular JS?

Yes, we can use jQuery and many other libraries along with Angular JS.

What do you understand by deep linking?

Deep linking is the redirection to the specific page without going through any other pages. This is a normal term and implemented by Angular JS by default.

What is the service?

Services are substitutable objects that can be used to organize and share code across the application.

What is internationalization?

As per https://docs.angularjs.org :
Internationalization (i18n) is the process of developing products in such a way that they can be localized for languages and cultures easily. This is the translation of application interfaces according to any locale.

What is Injector in Angular JS?

The injector is a subsystem in Angular JS which provide reusable component, dependency management making them available on request.

How can we share data between controllers?

Can move data by returning a factory and by using the reference of the same object by other controllers.

What is the digest cycle?

Digest Cycle allows us to write custom and complex directives for data binding processes.

What is a singleton pattern and where we can find it in Angular JS?

Singleton is a static variable and holds private instances of itself. It allows only a single instance to be created.

What is the interceptor?

Interceptor is used to modify the response. It only calls after the HTTP response received. It accepts the response object as an input

What is routing?

We use ngRoute to implement routing. Routing helps us to modularize our application based on logical units.

What does ‘ng-serve’ do?

The ng serve command launches the server watches your files and rebuilds the app as you make changes to those files.

what does –open or -o command do in angular?

The –open (or just -o) command automatically opens your browser to http://localhost:4200/.

How can we create a component using Angular CLI?

Using CLI we can create a component in very less time:

| ng generate component heroes |

It will be better if You could also read Jquery Interview Questions.

I hope that the above content will help you minimize the troubles in your interview. Please do write to us for your feedback. Let us know our weakness and send us more Interview Questions so that we can publish here.

Spread the love

Jquery noConflict() Explained

What is noConflict() method in jQuery?
This is very important to differentiate scripts when we are using many JavaScript framework in our project.As we know jQuery uses dollar symbol ($) as shortcut. There are many other popular frameworks are there as Angular JS,Knockout JS,Kendo JS,Backbone JS,Ember ,Vue etc.
Suppose i one of these frameworks is using the $ symbol as shortcut then one of the scripts either jQuery or the framework implemented parallel may stop working. noConflict is a method to avoid such situation in script.

We can create our self defined symbol or string as shortcut for jQuery. noConflict() return a reference and we can store this reference in a variable.

Example of noConflict() and self defined shortcut:

var jq = $.noConflict();
jq(document).ready(function(){
    jq("button").click(function(){
        jq("p").text("Hi there,Conflict resolved");
    });
});
Spread the love

jQuery Functionality – Common jQuery Functions

jQuery is a rich library and a very lightweight framework to provide javascript enhanced and modified functionality to our web page. jQuery is a javascript library and written in core javascript concepts. jQuery functionality is basically an easier version of javascript and a simple way to manipulate the DOM in the same way as Java Script does.
This is so popular because it has the number of functions events, chaining properties and they make it convenient as well as easy to use.  The jQuery Functionality provides rapid and smooth actions to perform actions on HTML DOM events.
There are few events and functions which are used frequently in addition to jQuery functionality. We are going to list them here with a one-line explanation. These explanations are very useful when you are explaining jQuery Functionality.
jQuery is a very rich library and has a number of functions. These functions provide a next-gen experience to jQuery functionality.
Find the jQuery functionality of a few popular library methods.
Must Read: What is jQuery?

Find some beautiful functions and their explanations in one line:

show(): display a hidden dom, set a style property display as Block.
hide(): Hide the selector from dom tree, visible on the browser.
animate(): Apply animation effects with selectors.
empty(): Empty the dom and also removes the child elements.
remove(): remove selector dom from tree
removeClass():remove class or classes from selectors
addClass():add class or classes to the selectors
toggleClass():add and remove simultaneously
stop():stop the propagation of event.
fadeIn():hide dom with a fading down effect.
fadeOut():display dom with a fading out effect.
val():get the value of form elements.
text():get the text in dom.
html():get the HTML in dom.
child(): find the child elements in dom.
parent(): find the immediate parent elements of the dom.
parents(): find the parents of the parent of the selector in the dome tree.
siblings(): find the parallel elements in the dom tree.
slideDown(): display the dom with sliding to downwards effect.
slideUp():hide the dome with sliding to up effect.
attr(): get the attribute of DOM.
append(): add the given object to the selector one after one, in a stack style. The object is added as the last child always.
prepend(): add the given object to the selector, but the object is added as the first child always.
after(): add an object just after the selector.
before(): add and object just before the selector.
css(): add some inline css-properties to the selector.
first(): get the first element in the child.
last(): get the last element in the child.
eq(): find the object of equal index passed to it.
noConflict(): avoid conflicts with other javascript frameworks using $ as shortcut symbol.

Conclusion

I Hope these functions will help you in the jquery excercise and application development. They will be helpful to answer your jQuery interview questions. We have added a few of the important functions and these are not the all jQuery functionality. You have to prefer the reference of jQuery to know more about the functions and events. Please share your feedback to improve our articles.
Thanks.
Spread the love

jQuery Events Frequently asked in various Interviews

Jquery events are attached with some function and function called when event triggers. On a web page actions taken by visitors are events. They can be responded accordingly as click,change,blur,focus,keypress etc. Some common events as categorised as :
Mouse Events : click,dblclick,hover
Keyboard Events : keypress,keydown,keyup
Form Events : change,select,focus,blur
Window : load,scroll,resize

Most Common events and their explanation in one line:

click(): event is triggered when an element is clicked.
change(): event is triggered when the value of a form field is changed.
focus(): event is triggered when a form field is focused.
blur(): event is triggered when a form field is blured.
hover(): event is triggered when moue pointer hover the element.
focusin(): event is triggered when the chield of and element is focused.
focusout(): event is triggered when the chiled of an element is blured.
keydown(): event is triggered when a key from keyboard is pressed down.
keypress(): event is triggered when a key is pressed .keypress event is not fired for ALT, CTRL, SHIFT, ESC.
keyup(): event is triggered when a pressed key is released.
load(): event is triggered when a dom is loaded.
unload(): event is triggered when a dom is unloaded.
mouseenter(): event is triggered when mouse pointer enters the area.
mousedown(): event is triggered when left mouse button is clicked.
mouseout(): event is triggered when mouse pointer leaves the area.
on(): on event is used to add additional handler to dom element.
submit(): event is triggered when form is submitted.
scroll(): event is triggered when the window is scrolled.
select(): event is triggered when the a form element is selected, in combobox or dropdown list.
ready(): event is triggered when the dom is ready and loaded in tree.
resize(): event is triggered when window dimensions are resized.

Spread the love

Top 10 AJAX Interview Questions and Answers

What is AJAX?
Full form of AJAX is Asynchronous JavaScript And XML.
AJAX facilitate web pages to be updated asynchronously by exchanging data with a web server in the background. It can update the webpage without reloading the whole page.

What are the main components that are used by AJAX?
AJAX components are :
1-A browser built-in XMLHttpRequest object
2-JavaScript and HTML DOM

What is XMLHttpRequest Object?
The XMLHttpRequest object can be used to request data from a web server without refreshing the whole page. It can send data to the server in the background and can ask and receive data in the background.

What is the request type used by XMLHttpRequest Object?
open(): It specifies the kind of request GET or POST
send(): Sends the GET request to the server
send(string): Sends the POST request to the server

Give an Example of a jQuery AJAX call.
A POST method AJAX example in jQuery:

var empId = $("ul .emp").first().attr("id");
var request = $.ajax({
url: "myajaxcall.php",
type: "POST",
data: {id : empId},
dataType: "json"
});

request.done(function(response) {
console.log(response);
});

request.fail(function(jqXHR, ajax_status) {
alert( "Request failed: " + ajax_status );
});

What is the difference between xhr.status and xhr.readyState?
xhr .status: used to determine whether the request was successful or not.
xhr.readyState: the state of the request.’
xhr.readyState zero(0) means “has not yet been sent”
xhr.readyState zero(4) means “complete and response received”
The server provides the status, while the user agent provides the readyState.

Spread the love

Interview Questions on jQuery

What is jQuery?
jQuery is a Javascript library that uses the usage of Javascript very easily. We can handle events, manage CSS properties, DOM element, animation and many more utilities using jQuery library. It is an opensource. It is used by Microsoft, Google, IBM and almost the big players in software industries.

What are selectors?
jQuery selectors are the tool to identify the HTML elements and to manipulate properties. for example:

$(".name") : Class selector
$('#logo') : ID selector
$("button") : tag selector
$(this) : current dom selector

What are the selectors that we use in jQuery?
We use the following selectors in jQuery:
-Tag
-Class
-Id
-all (*)
We can derive more selectors using these main selectors.

What is an event?
An event is a user action. When a user interacts using UI it has to make many clicks, drag, drop, mouse over, change drop-down, keypress actions, these actions are recognized by jQuery.

What are the common events that user make?
Most common events make by users are :
-click
-mouseover
-keypress
-keydown
-change
-input
-drag
-drop
-blur
-dblclick (double click)
-mouseenter

Must Read :

What is toggle()?
toggle() is a function which provides switching functionality between two actions, functions, properties etc. Suppose we can show and hide an element using toggle function.

What is callback?
A callback is a function that is called after when execution finished. We have to specify which function we have to call after a particular execution.

What is alert()?
alert() is used as a callback to show some warning, notification or error.

$("button").click(function(){
        alert("Clicked on button");
});

What is chaining in jQuery?
Chaining is calling of multiple functions in a single statement. for example :

$(".button").css("color", "#ececec").slideUp(1000).slideDown(2000).hide();

How to get value or text of an HTML element?
Since we know jQuery can manipulate HTML DOM, we can use functions to get value, text or html block inside an HTML element. For example

$('.first_name').val();  
//geting value in input box having class as first_name
$('p').html();   //getting html inside a 'p' tag
$('textarea').text();  //getting text inside a textarea

How can we set values for HTML element?
very similar to getting the value, we can set values to elements. For example:

$('.first_name').val('Interview Sortout Blogs');  
//geting value in input box having class as first_name
$('p').html('My blog is based on interview');  
 //getting html inside a 'p' tag
$('textarea').text('This blog is awesome. You are doing a verygood job,Interview Sortout');  //getting text inside a textarea

How to add or remove class from a HTML element?
jQuery have functions to add or to remove classes from an HTML elements. Please see the following examples:

$('button').addClass('btn-danger');
$('button').removeClass('btn-danger');

How to check that an element has a class?
We can use function hasClass().If class found it returns true, other wise returns false.

if($('button').hasClass('btn-danger')){
 alert('Button class is btn-danger');
}

What append() and prepend() functions do?
append() function , adds an HTML block after(at the end) a selector. For example :

$('p').append('Interview Sortout');

prepend() method, adds a block before or at the beginning of the selector. Example:

$('p').prepend('Interview Sortout');

What does parent() method do?
parent() method select the direct parent or immediate ancestor that is next to selector.

What does parents() method do?
parents() select all ancestors , the elements including parent of parent.

What childre() do?
children() method select the immediate child of the selector.

What does find() method do?
find() method search for the selector passed and selects from all the children of selector.

What does siblings() method do?
sibling() method returns all the elements having parralle relationship with selector. We can call them siblings.

How to call AJAX in jQuery?
An AJAX call example in jQuery:

var $post = $.ajax({
  url: "example.php",
  type: "POST",
  data: {id : product_id, product_name:product_name},
  dataType: "json"
});

$post.done(function(msg) {
  $("#log").html( msg );
});

$post.fail(function() {
  alert( "Request failed: Request Has been failed" );
});

 

Spread the love

Basic Java Script Interview Questions and Answers

JavaScript is common and most powerful programming and scripting language being used today. JavaScript is a lightweight and client-side scripting language.
Although after may server-side supporting frameworks have been developed and JavaScript is used today as a powerful server-side tool. Most of the framework based on Javascript provides smooth user experience and seamless content rendering.
Due to huge populariy of JavaScript and frameworks there are huge oppourtunnities in JavAScript and Great potential of Hihgly paid Job. Google, Microsoft, Facebook, Amazon and almost all the big player in IT and software Industry are using JavaScript.
That why We need to focus on JavaScript Interview Questions to get a right job. We have designed the collection of Questions asked in JavaScript Inteview and are having Most Frequent Questions along with Answers.
Here you will find JavaScript Interview Questions and Answers usefull for any level of Expertise . Lets go for it:

What is Javascript?

Javascript is a client-side scripting language, used to enhance webpage functionality and User Experience.
JavaScript is a multi-paradigm, dynamic language with types and operators, standard built-in objects, and methods.
Its syntax is based on the Java and C languages — many structures from those languages apply to JavaScript as well.
What is the importance of Javascript in Web Development and Web design?
Javascript provide additional functionality to HTML elements. It handles the DOM and content dynamically. Javascript is used by all the giant players in software industries like Microsoft, Google, Facebook, Amazon, etc.
How can we define a variable in javascript?
We can define a variable in javascript using ‘var’ keyword. for example :
var userName = 'Vishal Agrawaal';

When JavaScript was created?
JavaScript was created in 1995 by Brendan Eich while he was an engineer at Netscape. JavaScript was first released with Netscape 2 early in 1996.

What was the earliest name of JavaScript?
It was originally going to be called LiveScript.

Is JavaScript Object-Oriented?
JavaScript supports object-oriented programming with object prototypes, instead of classes.

What are the methods to return output in javascript?
We use alert(),console.log() and document.write() to display output in javascript.

What are the main types of JavaScript?
JavaScript’s types are:

  • Number
  • String
  • Boolean
  • Function
  • Object
  • Symbol (new in ES2015)

What is an alert?
Alert is a dialog box to display some warning or error. It displays a message on dialogue and a close button or OK button by default.

How to get a value by the ID of the element?
We can find the value by using Javascript function
var employee_name = documenst.getElementById(‘element_id’).value;

What is DOM?
The HTML DOM model is a tree of Objects and Objects are created by HTML the elements when the page loaded. It allows us to access the content and allow us to manipulate the HTML elements’ properties and attributes dynamically using Javascript or other scripts.

What are the functions of JavaScript?
Functions are just Objects and can be used to do some particular task.

What is the event?
An event is an action that takes place followed by any DOM activity or manipulation. Javascript provides a vast range of events that helps to create interactive interfaces in HTML. For example : onchange, onclick, onblur, onfocus, onmouseover, onkeypress, onkeyup, onmouseout, onload, etc.

How to create a function in Javascript?
Syntax to create a function in javascript:

function myFunction(){
//function logic goes here
}

Can JavaScript replace PHP or JSP or ASP?
Never, Not comparable. Javascript is a client-side scripting language whereas PHP and others are the server-side scripting language. So there is no reason for replacement.

What are the standard Arithmetic Operations that are supported in JavaScript?
Arithmetic Operations Supported by JavaScrip:

    • Addition operator.
    • Subtraction operator.
    • Division operator.
    • Multiplication operator.
    • Remainder operator.
    • Exponentiation operator.

What are the equality operators in JavaScript?
The result of an equality operator is always of type Boolean :

  • (==) Equality operator.
  • (!=)Inequality operator.
  • (===)Identity operator.
  • (!==)Nonidentity operator.

Does JavaScript support shift operators?
Yes, Here are some operators to shift all bits of the operand.

  • << : Bitwise left shift operator.
  • >>: Bitwise right shift operator.
  • >>> : Bitwise unsigned right shift operator.

How can we create an array in JavaScript?
Here is the way to create array in JavaScript:

  • var my_array = [ ]
  • Var my_array = new Array()

Write a function using JavScript.

function printMyName(){

console.log(‘ My Name is Lakhan’);

}

How to define an array in Javascript?
Defining an array in javascript is similar to any other language:

var students=['Ram','Vishal','Rahul','Kallu','Ballu','Lallu'];

How to handle date in javascript?
Javascript provides a constructor Date(). We can use Objects created by Date() and can Handle dates. For example:

var date = new Date();
var today = date.getDay();
var hour = date.getHours();
var minute = date.getMinutes();
var second = date.getSeconds();

How to convert an array into a string in Javascript?
We have an array :

var cars = ["BMW", "Benz", "Toyota", "Ford"];
var carString= car.toString();

and the result will be BMW, Benz, Toyota, Ford.

What is the functionality of pop() in js?
pop() is a standard method in javascript and it removes the last element of an array when we apply.
for example, we can apply it to cars :

cars.pop();

Now cars array will be : [“BMW”, “Benz”, “Toyota”];

What is the functionality of push() in js?
pop() is a standard method in javascript and it adds an element at the end of an array when we apply.
for example, we can apply it to cars :

cars.push("FORD");

Now cars array will be : [“BMW”, “Benz”, “Toyota”, “Ford”];

What is the functionality of splice() in js?
splice() added element/s at the particular index of an array and can remove some elements from the index. It can be used to replace some elements in the array.

var cars = ["BMW", "Benz", "Toyota", "Ford"];
fruits.splice(1, 0, "Ferari");

Resulting array : [“BMW”, “Ferrari”,”Benz”, “Toyota”, “Ford”];
The first parameter is the index of the element where the new elements will be added and second is the number of elements will be removed from that index.

How to apply a for loop in an array in Javascript?
Example of for loop in javascript:

var text='';
for (var i = 0; i < cars.length; i++) { 
text += cars[i] + "
";
}
alert(text);

Spread the love