Search code examples
jqueryhtmlajaxslidetoggle

How to load/unload an html to a div by clicking on a button with slideDown/Up


I am working on a big menu-list that opens/closes with jquery's toggle() function. I would like for one of the items on the menu-list to, when clicked, slideDown and reveal load() content from another .html on the div beneath it and then, when clicked again, to slideUp and remove the load () content.

The code i have written so far seems to work, however, after clicking the second time, it seems to go "crazy" and confuse the sequence of slideDown and Up and repeat the movement in a loop.

Since it uses the load() method, the code won't work here, but I am putting the code I am using anyway so you can check the logic.

$(document).ready(function(){       
    $('.show-project-01').on('click', function(){         

        if ($('.project').html() == "") {   
            $('.project').slideDown()
            $('.project').load('project-01.html')
        } else {
            $('.project').slideUp()
            $('.project').empty()
        }

        return false
            
        }) 
})    
<a href="#" class="title-project show-project-01">Pure office <img src="assets/teste-01.jpg" alt="" class="image-01"></a>

<div class="project">
</div>

I am new to jquery, so I don't quite understand what I am doing wrong and any suggestion is more than welcome.

Thank you!


Solution

  • You could use data attributes to make sure the container div is open or closed

    var button = $('.show-project-01');
    var container = $('.project');  
    
    // add data-open attribute of close
    button.attr('data-open','close');
      // on button click
      button.on('click',function() {        
    
        // get data-open arrtibute 
        var open = $(this).data('open');
    
        // if data-open is open 
        if(open != 'open'){  
          // update data-open to open
          $(this).data('open','open');
          container.load('project-01.html', function() {
               container.slideDown();
          });     
     } else {
            container.slideUp();
            // do you need to remove the html?
            //container.empty()
            // update data-open to close
            $(this).data('open','close');
        }
    });
    

    working example - https://jsfiddle.net/Jim_Miraidev/Lp2r3yqn/