jQuery Live Function Example
Let's have a closer look at the jQuery .live() function.
Description
The .live() function is essentially the same as .bind() but it can capture events on new elements that didn't exist on the page when it was loaded. For example, if your web page has already loaded and you dynamically insert an image into the page. If we used bind to attach an event when the mouse hovers over the image it would not work. But if we use .live() it will work! Lets have a look at an example of the live jQuery function in action. Further Reading »
Demo
Example: Capturing events on new or changed elements.
When the mouse moves through the div it toggles the background image class to show twitter eyes open.
Click "Run Demo" to dynamically insert a div element with a black background. When the div is hovered it loads in a background image.
Download
The download package includes all the inline HTML, CSS, JavaScript, jQuery and images required for the .live() function demo so you can try it yourself and change as you please.
Code
<!-- Copyright 2011 jQuery4u.com -->
<!DOCTYPE html>
<html>
<title>jQuery Function Demo - jQuery4u.com</title>
<head>
<script src="http://www.jquery4u.com/function-demos/js/jquery-1.6.4.min.js"></script>
<script src="http://www.jquery4u.com/scripts/function-demos-script.js"></script>
<script type="text/javascript">
var JQFUNCS =
{
runFunc:
{
/* ------------------------------ live Demo ------------------------------ */
"live":
{
run: function(id)
{
$('#'+id).append('<div style="text-align:center;width:688px;height:268px;background-color:black;"></div>');
$('#'+id+' div').live('mouseenter', function(e)
{
$(this).css("background","url(/function-demos/images/cats-eyes.jpg) no-repeat top center");
}).live('mouseleave', function(e)
{
$(this).css({
"background":"none no-repeat top center",
"background-color":"black"
});
});
},
reset: function(id)
{
$('#'+id).empty().hide();
}
}
}
}
</script>
</head>
<body>
<h3>Example: Capturing events on new or changed elements.</h3>
<p>When the mouse moves through the div it toggles the background image class to show twitter eyes open.</p>
<p>Click "Run Demo" to dynamically insert a div element with a black background. When the div is hovered it loads in a background image.</p>
<p><a href="#" id="live-demobtn" class="demobtn btn actionr">Run Demo</a> <a href="#" id="live-codebtn" class="codebtn btn actionr">View Code</a> <a href="#" id="live-resetbtn" class="resetbtn btn actionr" style="display: none;">Reset</a></p>
<div class="demoarea" id="live"></div>
</body>
</html>
<!-- Copyright 2011 jQuery4u.com -->


