Event binding is an advantage of jquery. In jquery we implement the event binding to handle the newly created elements on page. Jquery has provided different functions/events for different versions. Before discussing these types of functions/events we will discribe the situation. Most of time we add the new elements on the page and apply the jquery events on them. To apply the jquery events on new created elements we have to use the delegated events. Jquery has provided on event in jquery1.7 and below this version you can use event named live. We are going to take an example.
<script>
jQuery(document).ready(function(){
jQuery("p.mypara").click(function(){
jQuery(this).html('Just testing');
});
});
</script>
<div id="mydiv">
<p class="mypara">
This is sample click events
</p>
</div>
In above example we are adding an event click. it will be applied to existing element with class mypara. If you add new elements inside the div later. This event will not applied on these new elements so to overcome this issue you need to use the delegated events like on. Please have a look.
<script>
jQuery(document).ready(function(){
jQuery("div#mydiv").on('click','p.mypara',function(){
jQuery(this).html('Just testing');
});
});
</script>
<div id="mydiv">
<p class="mypara">
This is delegated click events
</p>
</div>
In above example we are using on event which is beneficial to implement the click event on newly added elements. You can add more p element with class .mypara and click event will be applied on these elements as well. Hope this concept will be beneficial for you.
0 Comment(s)