Alex Rivera | Logout

jQuery - How do I bind events to hidden elements that will be shown later?

Asked 2011-04-13T21:00:09.750
57

I am trying to attach 'click' events to all elements of a particular class. The problem is some of the elements are on a tab that is hidden (display: none) at the time that the event is bound. (.bind()). It seems that when these elements are shown the events are no longer bound.

$('a.someClass').bind('click', function(){
  alert("test");
});

The hidden elements do not appear to have a click event bound. If I select the hidden elements:

$('a.someClass:hidden').bind('click', function(){
  alert("test");
});

It seems the click event is not bound when these elements are no longer hidden. Has anyone experienced this? Is there a way to bind and event to elements irregardless of their display property?

Thanks

Edit
Report

1 Answer

67

As of jQuery 1.7, the .live() method is deprecated.

You can now use the .on() method. By attaching a delegated event to an element that is viewable in the HTML when the jQuery is run.

So if a.someClass is hidden when jQuery is run, you should attach a delegated event to the body, so it will run when there is a viewable a.someClass element in the future, for example:

$('body').on('click','input.a.someClass',function(){
  alert("test");
});
answered 2012-06-15T12:14:08.720

Your Answer