'My jQuery code is not working efficiently to open and close mobile menu bar

Pls I need help with the nav bar(mobile view) I want to use jQuery to open and close the menu. This is my first every web dev project

https://github.com/alwayswantedtocode/my-first-web-dev-project



Solution 1:[1]

.toggle() isn't enough!

Use remove/add class instead.

$('.navigation').removeClass('').addClass('')

https://jsfiddle.net/drmtpocn/1/

Solution 2:[2]

I can see you're defining your $(Document).ready function on each function, there is no need for that considering you will have most of your JQuery functions run inside it, so you can only define it at the start of your project. You will then place the other functions inside of only that one document.ready function.

If you want a simple way of resolving this you can use the following code:

   $(document).ready(() => {

    $('.menu-Icon span').click(() => {
        $('.navigation').addClass('open');
        $(".navigation").removeClass('close');

    });
    
    $(".X-close").click(() => {
        $(".navigation").toggleClass('close');
    });
});

this will remove the "close" class every time you open it and it will add the open class, when you close the menu after, it will then re-add the close class.

There is a another option with a built-in JQuery function that might make it look a bit better than just appearing.

You would put the following into your JQuery

  $(document).ready(() => {

    $('.menu-Icon').click(() => {
        $('.navigation').slideDown();

     

    });
    
    $(".X-close").click(() => {
        $('.navigation').slideUp();
    });
})

;

and your CSS on line 304 would change, here is the edited snippet.

@media only screen and (max-width:991px) /* Line 290 */
{
    .header .navigation{ 
        position: fixed;
        right:-250 ;/*initially zero*/
        width:250px;
        height: 100%;
        overflow-y: auto; 
        background-color: #3e5e75;
        /* opacity: 0.75; */
        top: 0;
        z-index: 1000;
        padding: 15px 0;
        transition: all 0.5s ease ;
       display: none; /*Changed element line 304*/
       /* Changed from visibility to display */
        
    }

For more details on the jQuery slideUP/slideDown please follow the link below :)

SlideDown

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pepeD
Solution 2 Leander