on() method:
On() method is used to attach events to selected elements and also used to specify a function when the event occurs. It is similar to bind method but on() method also attach event handler to elements generated using script while bind cannot (means it can bind events to both current and future generated elements).
Syntax:
$(selector).on(event,childSelector,data,function,map)
Example:
<!DOCTYPE html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<style>
.content{border:1px solid #333;padding:24px 7px;width:250px;margin-bottom:10px;}
.addlnk{text-indent:40px;}
</style>
</head>
<body>
<section id="main-container">
<p class="addlnk"><a href="javascript:void(0);" onclick="addDiv();">Add box</a></p>
<div class="content">
on() method example
</div>
</section>
<script type="text/javascript">
$(function()
{
$("#main-container").on("mouseover",'.content', function()
{
$(this).css("background-color", "#5AB0A6");
}).on("mouseout",'.content',function()
{
$(this).css("background-color", "white");
});
});
function addDiv()
{
var div = $("<div></div>").addClass("content").text("Content generated using script");
$("#main-container").append(div);
}
</script>
</body>
</html>
In the above example, when an add box is clicked by the user then a div will get added inside main-container div and also the mouseover and mouseout event will get attached to the div generated using script.
On() method was replacement for live() method which was deprecated in jQuery version 1.7 and removed in jQuery version 1.9.
0 Comment(s)