I am trying to create a page where the example div is clickable, as it would be below.
However I'm trying to make it so if the user clicks the logo it will reload the original content using load.
After this load has occurred is it possible to 'click' a loaded <div id="example">
? I'm trying this at the moment and it fails to alert when clicking the loaded <div id="example">
that is in file.php
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Example</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#example").click(function(){
alert("You clicked me!");
});
$("#logo").click(function(){
$("#main").load("file.php");
});
});
</script>
</head>
<body>
<img id="logo" src="404.gif" />
<div id="main">
<div id="example">This is content.</div>
</div>
</body>
</html>
file.php contains
<div id="example">This is loaded content that can't be clicked?</div>
try this,
jQuery 1.7 introduced the
.on()
API for event binding and event delegation:The problem is that after you replace the innerHTML of
<div id="main">
,<div id="example">
no longer has the click action on it.There are a couple methods to solve this:
First and probably the best method is to use
.on()
:This attaches to
#main
and therefore, it doesn't matter what you do with the content inside. As the events bubble up, they will be noticed by theon
and then the selector will determine if the handler should run.Second there is live. The following will replace your current click on
#example
:The one flaw in this is that jQuery is constantly watching the dom for any changes, which depending on how many you'll have, this can start to slow things down (although maybe not noticeably on faster machines). Also,
.live()
has been deprecated in 1.7.The last option is to add a success function on the
#logo
click. I'd recommend creating a method so you don't have duplicate code:This means that every time after
#main
is loaded successfully, the click will be added to#example
. But this is kind of ugly as you need to call the function twice.Problem
The problem is that
.click()
only binds events to elements that exist in the DOM at that moment in time. Meaning that when you add a new element to the page, it will not have an event handler bound to it.Solution
If you're using jQuery 1.7+, rather than using
.click()
in your code use.on()
instead....or with older versions of jQuery use
.live()
instead:This will ensure that new elements added to the DOM will get the event handler bound to them also.
If you are using jquery 1.7+, use "on".
http://api.jquery.com/on/
Try putting the
click()
function for theexample
div in the callback for the load function.