JQuery Interview Questions and Answers Part 1

1. Difference between preventDefault() and stopPropagation() functions in jquery?
Ans. 
1.preventDefault() : this prevents the default action the browser makes on that event.
2.stopPropagation() : this stops the event from bubbling up the event chain.

Example:

<div id="parent">
 <div id="child">click me !!</div>
</div>

$("#parent").click(function() {
   // mouse click on parent
});

$("#child").click(function(e) {
   // mouse click on child div
   e.stopPropagation();
});

Here, with stopPropagation only the 'child div' click handler is called and the 'parent div' 
click handler never fires.

$("#child").click(function(e) {
   // mouse click on child div
   e.preventDefault();
});
Here, with preventDefault only the 'child div' action is stopped but the 'parent div'
click handler still fires.


2. Difference between $('#elementid').val() and $('#elementid').text() in jquery?
Ans. val() works on 'input' element whereas text() gets the innerText of matching element.

3. Print the number of child 'div' elements using jquery?

<div id="parent">
<p>start of parent block</p>
<div id="child1"></div>
<div id="child2"></div>
<div id="child3"></div>
<p>end of parent block</p>
</div>

Ans. var count = $('#parent div').children().length;

4. How do we handle the input box mouse right click 'paste' using jquery?
Ans. 
$('#elementid').bind('input propertychange',function(){
alert("value pasted");
});

or 

$('#elementid').on('paste',function(){
alert("value pasted");
});

5. How to stop event bubbling in a function using jquery?
Ans. just by using "return false";

$('#elementid').bind('click',function(event){
return false;
alert("event cancelled");
});






Subscribe

Receive Quality Tutorials Straight in your Inbox by submitting your Email below:

Delivered by FeedBurner

Protected by Copyscape Duplicate Content Checker