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>
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.
If you're using jQuery 1.7+, rather than using .click() in your code use .on() instead.
$("#main").on('click', '#example', function(){
alert("You clicked me!");
});
...or with older versions of jQuery use .live() instead:
$("#example").live('click', function(){
alert("You clicked me!");
});
This will ensure that new elements added to the DOM will get the event handler bound to them also.
try this,
$("#example").live('click',function(){
alert("You clicked me!");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With