Home > Software design >  Jquery Toggle firing multiple times
Jquery Toggle firing multiple times

Time:08-17

Fairly new to jQuery. Following various text and tutorials I'm trying to understand how to get the toggle function to work as its been shown in said tutorials. Yet, I'm having issues where it's being fired multiple times.

$document.ready(function() {
  $(#myButtonId).click(function() {
  $(#myDivId).toggle(
     function() {
       $(this).addClass("myClass");
       $(this).next().show(); },
     function() {
       $(this).removeClass("myClass");
       $(this).next().hide(); } 
);
});
}); 

It is my current understanding, the above should on button click, toggle on/show the div and add the class "myClass" to the div "myDivId". Then, on button click again, should toggle off/hide the div and remove the class from the div.

However, somehow it's either only calling 1 of the two toggle functions, and it's calling it multiple times.

CodePudding user response:

So, assuming that you have a button and div like this in your HTML:

<button id="myButtonId">Button</button>
<div id="myDivId" >Div that toggles</div>

You could, in your javascript file, do this:

jQuery(document).ready(function($)
{
    $('#myButtonId').click(function()
    {
        $('#myDivId').slideToggle(400, function()
            {
                if($(this).is(':visible'))
                { $(this).addClass('myClass'); }
                else
                { $(this).removeClass('myClass'); }
            }
        );
    });
});

To explain this bit of code:

  • Once the document is ready
  • We watch for any click events on the #myButtonId button
  • A click on the #myButtonId button will Toggle the #myDivId div at a speed of 400 milliseconds (0.4 seconds). The second parameter of this slideToggle function is a "Callback", which basically defines what you want to do once the toggle animation is finished
  • In the callback, we look at whether the toggled element (#myDivId, in this case) is visible or not. If it's visible, we add the 'myClass' class, otherwise we remove that class

I'm not sure what you wanted to do with the $(this).next().hide(); and $(this).next().show(); lines though, it seemed irrelevant to the question, you can just put them back in the "if is visible" condition if you need them. :-)

  • Related