New to Jquery - Experiencing difficulties with menu animation

I've encountered a strange problem that I've been struggling to find a solution for, even after spending hours trying to Google it...

The animation on 'mouseenter' and 'mouseleave' is working perfectly fine. However, the issue arises when I click the menu button twice to change it to an "X" and then revert back to three dashes - the animation for 'mouseenter' and 'mouseleave' stops functioning...

Apologies for my imperfect English... x.x

Below is the code snippet:

$(document).ready(function() {

  /* Slide up/down menu bars */

  $('.toggle-nav').on("mouseenter", function moveUp() {
    /* Implement animation for mouse enter */
    $('.line1').css({
      top: '-7px',
      opacity: '0'
    });
    setTimeout(function() {
      $('.line2').css({
        top: '0px'
      });
    }, 70);
    setTimeout(function() {
      $('.line3').css({
        top: '7px'
      });
    }, 140);
    setTimeout(function() {
      $('.line4').css({
        top: '14px',
        opacity: '1'
      });
    }, 210);
  });

  $('.toggle-nav').on("mouseleave", function moveDown() {
    /* Implement animation for mouse leave */
    $('.line4').css({
      top: '21px',
      opacity: '0'
    });
    setTimeout(function() {
      $('.line3').css({
        top: '14px'
      });
    }, 70);
    setTimeout(function() {
      $('.line2').css({
        top: '7px'
      });
    }, 140);
    setTimeout(function() {
      $('.line1').css({
        top: '0px',
        opacity: '1'
      });
    }, 210);
  });

  /* Show/hide nav-menu on click */
  $('.icon-container').on('click', function() {
    $('.nav-menu').toggle();
  });

  /* Change to 'X' */
  $('.toggle-nav').on('click', function() {
    $('.toggle-nav').toggleClass('test');

    if ($('.toggle-nav').hasClass('test')) {
      $('.toggle-nav').off('mouseenter');
      $('.toggle-nav').off('mouseleave');
      $('.line').css({
        top: "+7px"
      });
      $('.line2').css({
        transform: "rotate(-45deg)"
      });
      $('.line1').css({
        transform: "rotate(-45deg)",
        top: "7px",
        opacity: '0'
      });
      $('.line3').css({
        transform: "rotate(45deg)"
      });
      $('.line4').css({
        transform: "rotate(45deg)",
        top: "7px",
        opacity: '0'
      });
    } else {
      $('.line').css({
        top: "0px"
      });
      $('.line1').css({
        transform: "rotate(0deg)",
        top: "0px",
        opacity: '1'
      });
      $('.line2').css({
        transform: "rotate(0deg)",
        top: "7px"
      });
      $('.line3').css({
        transform: "rotate(0deg)",
        top: "14px"
      });
      $('.line4').css({
        transform: "rotate(0deg)",
        top: "21px",
        opacity: '0'
      });
    };
  });
});
body {
  /*body reset*/
  margin: 0px;
  padding: 0px;
  width: 100%;
  height: 100%;
  font-family: 'Roboto', sans-serif;
}

header {
  position: absolute;
  top: 0px;
  height: 500px;
  width: 100%;
  background-image: url(img/bg.jpg);
  background-size: cover;
}

.toggle-nav {
  width: 93px;
  height: 68px;
  background: #990e35;
  margin: 0px;
  z-index: 1;
  position: absolute;
}

.icon-container {
  display: block;
  height: 20px;
  position: absolute;
  top: 10px;
  backface-visibility: hidden;
}

.line {
  position: absolute;
  background-color: white;
  width: 37px;
  height: 3px;
  left: 28px;
  transition: all 250ms ease-in-out;
}

.nav-menu {
  background: #990e35;
  z-index: 0;
  position: absolute;
  width: 100%;
  height: 100%;
  text-align: center;
  top: 20%;
  opacity: 0;
}

.nav-menu ul {
  width: 300px;
  display: inline-block;
  list-style: none;
  position: relative;
  top: calc(50% - 100px)
}

.nav-menu ul li {
  padding: 5px 0px;
  margin: 5px 0px;
}


/**** line base ****/

.line1 {
  top: 0px;
}

.line2 {
  top: 7px;
}

.line3 {
  top: 14px;
}

.line4 {
  top: 21px;
  opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<header>

  <div class="toggle-nav">
    <div class="icon-container">
      <p class="line line1"></p>
      <p class="line line2"></p>
      <p class="line line3"></p>
      <p class="line line4"></p>
    </div>
  </div>
</header>


<nav class="nav-menu">
  <ul>
    <li>
      <a href="#"></a>Home</li>
    <li>
      <a href="#"></a>Artwork Gallery</li>
    <li>
      <a href="#"></a>Clients</li>
    <li>
      <a href="#"></a>About Me</li>
    <li>
      <a href="#"></a>Contact</li>
  </ul>
</nav>

Answer №1

By using the following code, you can eliminate the behaviors of mouseenter-leave when clicked:

$('.toggle-nav').off('mouseenter');
$('.toggle-nav').off('mouseleave');

To enhance your code, it's recommended to define the functions separately from the initial binding. This way, you can re-bind those functions for the enter/leave events later:

$(document).ready(function() {
  function moveUp() {
    $('.line1').css({
      top: '-7px',
      opacity: '0'
    });
    setTimeout(function() {
      $('.line2').css({
        top: '0px'
      });
    }, 70);
    setTimeout(function() {
      $('.line3').css({
        top: '7px'
      });
    }, 140);
    setTimeout(function() {
      $('.line4').css({
        top: '14px',
        opacity: '1'
      });
    }, 210);
  }
  function moveDown() {
    $('.line4').css({
      top: '21px',
      opacity: '0'
    });
    setTimeout(function() {
      $('.line3').css({
        top: '14px'
      });
    }, 70);
    setTimeout(function() {
      $('.line2').css({
        top: '7px'
      });
    }, 140);
    setTimeout(function() {
      $('.line1').css({
        top: '0px',
        opacity: '1'
      });
    }, 210);
  }
  $('.toggle-nav').on("mouseenter", moveUp)
  $('.toggle-nav').on("mouseleave", moveDown);

  /* Transform to X */
  $('.toggle-nav').on('click', function() {
    $('.toggle-nav').toggleClass('test');
    if ($('.toggle-nav').hasClass('test')) {
      $('.toggle-nav').off('mouseenter');
      $('.toggle-nav').off('mouseleave');
      $('.line').css({
        top: "+7px"
      });
      $('.line2').css({
        transform: "rotate(-45deg)"
      });
      $('.line1').css({
        transform: "rotate(-45deg)",
        top: "7px",
        opacity: '0'
      });
      $('.line3').css({
        transform: "rotate(45deg)"
      });
      $('.line4').css({
        transform: "rotate(45deg)",
        top: "7px",
        opacity: '0'
      });
    } else {
      $('.toggle-nav').on("mouseenter", moveUp)
      $('.toggle-nav').on("mouseleave", moveDown);
      $('.line').css({
        top: "0px"
      });
      $('.line1').css({
        transform: "rotate(0deg)",
        top: "0px",
        opacity: '1'
      });
      $('.line2').css({
        transform: "rotate(0deg)",
        top: "7px"
      });
      $('.line3').css({
        transform: "rotate(0deg)",
        top: "14px"
      });
      $('.line4').css({
        transform: "rotate(0deg)",
        top: "21px",
        opacity: '0'
      });
    };
  });
});
.toggle-nav {
  width: 93px;
  height: 68px;
  background: #990e35;
  margin: 0px;
  z-index: 1;
  position: absolute;
}
.icon-container {
  display: block;
  height: 20px;
  position: absolute;
  top: 10px;
  backface-visibility: hidden;
}
.line {
  position: absolute;
  background-color: white;
  width: 37px;
  height: 3px;
  left: 28px;
  transition: all 250ms ease-in-out;
}
.line2 {
  top: 7px;
}
.line3 {
  top: 14px;
}
.line4 {
  top: 21px;
  opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<header>
  <div class="toggle-nav">
    <div class="icon-container">
      <p class="line line1"></p>
      <p class="line line2"></p>
      <p class="line line3"></p>
      <p class="line line4"></p>
    </div>
  </div>
</header>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to send a string to a function within another function using jQuery?

I've been struggling to understand why I'm unable to pass a string into a function that contains another function. When trying to alert, I keep getting undefined. $.fn.downCount = function (start_time) { function countdown(start_time) { ...

Tips for Keeping Footer Aligned with Content:

When checking out this website, you may notice that the footer appears to be affixed to the left side. The CSS code responsible for this is as follows: #footer { width: 800px; clear:both; float:right; position:relative; left:-50%;} I would appreciate it ...

``The issue concerning the preloading layer on the website``

My experience with the website www.wirecreation.net is sometimes marred by an issue during the initial load. It seems that there is a margin of a few pixels on the gray div containing the logo and progress bar at times, but other times it appears with zero ...

Having trouble selecting a URL tag that was dynamically created using JQuery by its class?

While working on implementing a TagCloud for my website, I encountered an issue with using JQuery to alert me about the selected link. Even though the links are being generated correctly and assigned the 'tagLink' class, when I attempt to determi ...

What technique works best for changing the visibility of an image without causing other elements to shift position?

On my webpage, I have a table cell with an image that should only display when hovering over the cell. The problem is that when the image is shown, it shifts the other text to the left because its default state is "display:none". I'm searching for a s ...

Executing a JavaScript function from one page on a separate webpage

I am trying to link three pages together: dashboard.html, documents.jsp, and documents.js In the dashboard.html file, I have a hyperlink that should take the user to documents.jsp and also trigger a function in the documents.js file, which is included in ...

Swap out a div identifier and reload the page without a full page refresh

I am interested in learning how to dynamically remove a div id upon button click and then add it back with another button click to load the associated CSS. The goal is for the page to refresh asynchronously to reflect these changes. So far, I have successf ...

Events in the backbone view fail to trigger after a re-render

For some reason, I am struggling to get mouse events to work on my backbone view after it is re-rendered. It seems like the only solution is to use a rather convoluted jQuery statement: $("a").die().unbind().live("mousedown",this.switchtabs); I initially ...

The menu is loaded dynamically by Ajax from JavaScript once the page is refreshed

$('#subregionListPage').bind('pageinit', function(event){ var output = $('#subregions'); var region = getUrlVars()["reg"]; $.ajax({ url: 'http://localhost:8888/my/getsubregions.php', dat ...

Real-time JQuery search with instant results

While utilizing a custom script to display search results on the page, I encountered an issue when typing long sentences. Each request goes to the server, resulting in delayed responses that stack up and cause the div to change quickly. This is not the des ...

Accessing and parsing JSON data from directories within directories

My file directory structure is dynamic, with only the name of $(Root Directory) known at runtime. All folders and files are generated dynamically, with all files being in .json format. I am looking to count the number of files and read the content of eac ...

Having issues with React Nivo tooltip functionality not functioning properly on specific graphs

While using Nivo ResponsivePie to visualize some data, everything is functioning properly except for the tooltip. For some reason, the tooltip isn't appearing as it should. Interestingly, I have a heatmap and a bar graph with tooltips that are working ...

What is the best way to transform all elements on a webpage into a dynamic scrolling marquee?

Is there a way to make every div in a web application scroll like a marquee? Perhaps by using a specific CSS class or other method? The application is built with Angular 4 and Bootstrap. ...

Determine the precise location of a screen element with jQuery

Can anyone help me determine the precise position of an element on the current visible screen using jQuery? My element has a relative position, so the offset() function only gives me the offset within the parent. Unfortunately, I have hierarchical divs, ...

I am having trouble programmatically setting the 'checked' attribute for a newly added checkbox on an asp.net page

I dynamically added checkboxes using jQuery on my ASPX page and attempted to check some checkboxes by default based on conditions. However, I encountered the following error: Uncaught TypeError: undefined is not a function I tried the following methods ...

One single block preventing all asynchronous jQuery/ASP.NET AJAX calls

My JQuery application is set up to make four asynchronous calls to four different asp.net web services, each on its own timer. However, I noticed that when I introduced a Thread.Sleep(10000) command in one of the web services, it ended up causing delays i ...

Adding pixels to the top position with jQuery in Angular 2

I am trying to adjust the position of my markers when the zoom level is at 18 or higher by adding 10px upwards. However, my current approach doesn't seem to be working as expected. Can someone please assist me with this issue? You can view the code sn ...

Tips for expanding an input to fit the width of a div without altering the dimensions of a preceding span element

Let me explain, I have a form that includes a span and an input: <form onSubmit={e => handleSubmit(e)}> <Box className='form_box'> <span> <a href="/cd ...

What is the best way to eliminate the space between the website's border and the image?

Is there a way to eliminate the space between the left and right borders? I want the picture to fill 100% of the browser window. https://i.stack.imgur.com/gqgOs.png img.test { display: block; outline: 0px; padding: 0px; margin: 0px; } <img c ...

Tooltip Bootstrap timing

I am currently working on creating a navigation bar with icon-only buttons that display tooltips when touched or tapped. Here is the code I have implemented: $('a[rel="tooltip"]').tooltip({ animated: 'fade', placement: ' ...