[ACCEPTED]-jQuery - How do I bind events to hidden elements that will be shown later?-jquery
As of jQuery 1.7, the .live()
method is deprecated.
You 7 can now use the .on()
method. By attaching a 6 delegated event to an element that is viewable 5 in the HTML when the jQuery is run.
So if 4 a.someClass
is hidden when jQuery is run, you should 3 attach a delegated event to the body, so 2 it will run when there is a viewable a.someClass
element 1 in the future, for example:
$('body').on('click','input.a.someClass',function(){
alert("test");
});
edit 2 years later: As some people pointed out, the Live
function 5 is now deprecated (as you can also see at 4 the top of the linked docs page). The right 3 event handler name for the current version 2 would be On
. See Maxim's answer for a good 1 example.
Original answer:
Have you tried using Live()?
.live('click',function(){/* code */});
?
version note: live
has been deprecated in jQuery 1.7 and it was removed in jQuery 1.9. This answer is only correct for jQuery versions older than jQuery 1.7
Use delegate (note this is after you unhide 1 them):
$('body').delegate('.someClass', 'click', function (evt) {
// do something here
});
Use
$('parentelement').on('click','taget element',function(){
})
parentelement
should be visible at page load
0
According to the jquery documentation at 4 http://api.jquery.com/live/
Attach a handler to the event for all elements 3 which match the current selector, now and 2 in the future
Here is an example of how to 1 use it:
<!DOCTYPE html>
<html>
<head>
<style>
p { background:yellow; font-weight:bold; cursor:pointer;
padding:5px; }
p.over { background: #ccc; }
span { color:red; }
</style>
<script src="http://code.jquery.com/jquery-1.5.js"></script>
</head>
<body>
<p>Click me!</p>
<span></span>
<script>
$("p").live("click", function(){
$(this).after("<p>Another paragraph!</p>");
});
</script>
</body>
</html>
Times have changed, it would now be done 1 using ".on"
.on('click',function(){/* code */});
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.