简体   繁体   中英

An action before another in a Jquery function

I want that when I click on "nav-toggle" it adds the toggle class "open" to "grappa". Then I would like to remove the toggle class "open" clicking anywhere on the web page.

I wrote this but it doesn't working.

$(function() {
        $('.nav-toggle').on('click', function(){
            $('.grappa').toggleClass('open');{
                $(document).click(function() {
                $('.grappa').toggleClass('close');
             });
            }
        });

    });

Write separate events

To Toggle

  $('.nav-toggle').on('click', function(){
        $('.grappa').toggleClass('open');
    });

Any where on web page click

$( document.body ).click(function() {
    $('.grappa').toggleClass('close');
});

Keep Alert/Console statements to your script is getting called.Referencing js in your web page should be correct

Updated

Look at this Fiddle http://jsfiddle.net/M4teA/

You could check if your grappa element has the open class before toggling the close class. Then the close class would only be toggled if open had already been toggled. Something like:

$(function() {
    $('.nav-toggle').on('click', function(){
        $('.grappa').toggleClass('open');
    });

    $(document).click(function() {
        if ($('.grappa').hasClass('open'))
        {
            $('.grappa').toggleClass('close');
        }
    });

});

Also, since I haven't seen any of your css or html I'm not exactly sure how you are using the open and close classes but it appears that it might make more sense to just add and remove the open class depending on if the element has that class. Something like:

$(document).click(function() {
     if ($('.grappa').hasClass('open'))
     {
          $('.grappa').removeClass('open');
     }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM