JQuery Event Propagation
In previous article, we looked into events present in JQuery. In this article, we will cover JQuery event propagation followed by firing events like button click through code. JQuery supports event bubbling. It means, when an event is fired on a child element. It will get propagate to its parents for handling by them as shown below:
In below HTML, when you click the button, it will fire click event of button as well as div element.
<html>
<head>
<title>JQuery Sample HTML Page</title>
<script src="jquery-1.4.2.min.js" temp_src="jquery-1.4.2.min.js" type="text/javascript">
</script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$('#myButton').click(function(){alert('Button clicked');});
$('#myDiv').click(function(){alert('div clicked');});
});
</script>
</head>
<body>
<div id='myDiv'>
<input type="button" value="My Button" id="myButton"/>
</div>
</body>
</html>
We are not interested in firing click event of parent element [div]. We can rewrite above code to avoid event propagation as shown below:
$(document).ready(function() {
$('#myButton').click(function(){alert('Button clicked');});
$('#myDiv').click(function(event){if(event.target==this)alert('div clicked');});
});
We can check for event's target property before executing the code to avoid propagation. The other way to stop event propagation using event.stopPropagation() is shown below:
$(document).ready(function() {
$('#myButton').click(function(event){alert('Button clicked');event.stopPropagation();});
$('#myDiv').click(function(){alert('div clicked');});
});
Now, we will look into firing an event through code. In certain cases, we might need to fire button click event through code. This can be done using below code:
$('#myButton').click();// Executes code associated with myButton click event.
(or)
$('#myButton').trigger('click');
Tip: We can write $(document).ready(function() {}) in shortcut as shown below:
$().ready(function() {
.........
});
(or)
$(function() {
.........
});
I am ending the things here. In next article, we will discuss about Effects available in JQuery.