简体   繁体   中英

I can't get the jQuery animation to work with my js

I've never used jQuery before. I probably messed something up with it. The js is working fine to hide / show the menu. The animation isn't doing anything tho.

Here is my js:

//show / hide menu on mobile
mobileMenuButton.addEventListener("click", function() {
  $('mainMenu').slideToggle(200)
  if (mainMenu.style.display !== "none") {
    mainMenu.style.display = "none";
  }
  else {
    mainMenu.style.display = "flex";
  }

})

This is at the top of my js:

//jQuery???
const script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery-3.4.1.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);

any help would be appreciated

Try this:

//show / hide menu on mobile
mobileMenuButton.addEventListener("click", function() {
    $('.mainMenu').slideToggle(200, function() {
        if ($(this).is(':visible')) $(this).css('display','flex');
    });
});

If you define display: flex within your CSS stylesheet then you do not need to specify it in your javascript. To hide your menu you can use an inline style of display: none on load, as this will be overridden by the slideToggle() function. This will really simplify your code.

A working example is shown below, I've added some basic structure and styling to the demo to help.


DEMO

 // Add click event listener $("#mobileMenuButton").click(function() { // Slide toggle $('#mainMenu').slideToggle(200); })
 #navbar { width: 100%; background: blue; padding: 12px; } #mainMenu { display: flex; background: yellow; padding: 12px; flex-wrap: wrap; } li { width: 100%; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="navbar"> <button id="mobileMenuButton">Mobile Menu</button> </div> <div id="mainMenu" style="display:none;"> <li>Menu item</li> <li>Menu item</li> <li>Menu item</li> </div>

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