RegEdit
RegEdit

Reputation: 2162

Using on('click') event with jQuery and changeclass only fires once

In the script below, the first click on the "toggleExtras" span works. But subsequent clicks do nothing. I'm trying to use the on('click') method along with a toggleClass to define events for both toggled and untoggled states.

    jQuery(document).ready(function()
    {
        jQuery('.toggleExtras').on('click', function(e)
        {
            //jQuery('.extras').slideToggle(); //This works but bounces twice.
            jQuery('.extras').show();
            jQuery('.toggleExtras').text('Hide Advanced Options');
            jQuery('.toggleExtras').toggleClass('toggleExtras toggleExtrasHide');
        });

        jQuery('.toggleExtrasHide').on('click', function(e)
        {
            jQuery('.extras').hide();
            jQuery('.toggleExtrasHide').text('Show Advanced Options');
            jQuery('.toggleExtrasHide').toggleClass('toggleExtrasHide toggleExtras');
        });
    });

HTML:

    <span class="toggleExtras">Show Advanced Options</span>

Upvotes: 3

Views: 171

Answers (1)

ahren
ahren

Reputation: 16959

It's because .toggleExtrasHide doesn't exist at the time of initialization...

I'd re-write your code like this:

jQuery('.toggleExtras').on('click', function(e){
  jQuery('.extras').toggle();
  jQuery(this).text(function(el, currentValue){
    return currentValue == "Show Advanced Options" ? "Hide Advanced Options" : "Show Advanced Options";
  });
});

Demo: http://jsfiddle.net/xbLc2/

Read more about .toggle() : http://api.jquery.com/toggle/
Read more about .text() : http://api.jquery.com/text/

Upvotes: 3

Related Questions