Home > front end >  I can't get the jQuery animation to work with my js
I can't get the jQuery animation to work with my js

Time:11-26

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

CodePudding user response:

Try this:

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

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related