Ajay
Ajay

Reputation: 151

jQuery bind event handler to a hidden element (display:none)

So i'm trying to change class of sub-element of an element which parent is hidden.

Basically I'm trying to tie two pseudo-checkboxes, one is on the frontpage (let's say "remember me"), another one is in the hidden menu (with display:none).

Currently if I use selector to pick them all:

$('.rememberme').on('click', function() { $(this).toggleClass('fa-square fa-check-square') });

It doesn't work on the parent-hidden ".rememberme" element.

<html>
 <title>test</title>
 <body>
  <section class="hidden" style="display:none">
   <a href="#" class="rememberme"><i class="fa fa-square"></a>
  </section>
  <section style="display:block">
   <a href="#" class="rememberme"><i class="fa fa-square"></a>
   <button id="fu">turn first section one</button>
  </section>
 </body>
</html>

Thus resulting in inconsistency.

Currently I see only 2 ways - either run a "thread" (i.e. interval) and get the checked value from localstorage / global and synchronize the data (which looks clunky as hell), or bind to the button element which activates the section

$('#fu').on('click', function() { $('.hidden').show(); });

the whole rebinding function (I did such things before .live was invented).

Upvotes: 1

Views: 2495

Answers (1)

LeJared
LeJared

Reputation: 2052

Try this one:

$('.rememberme').on('click', function() {
    $('.rememberme').toggleClass('fa-square fa-check-square')
});

This $(this) selects only the link currently beeing clicked on. This $('.rememberme') selects all "rememberme" links every time.

You may want to improve this by storing the result of $('.rememberme') in a variable, so the links don't need to be gathered from the DOM every time.

Upvotes: 1

Related Questions