Restrict the number of times jQuery runs when hovering over an element

I recently developed a hover menu with CSS and jQuery to display sub-menus. However, I noticed that if the user hovers multiple times on the menu item, it behaves strangely. You can check out the menu in action at this URL: . Here's the jQuery code I used (inside document ready):

if ($(window).width()>991) //menu script for desktop or laptop
  {
  $('#mob-main-menu > li.menu-item-has-children').hover(function(event){
    event.preventDefault();
    $(this).children('a').toggleClass('bold600');
    $(this).children('a').siblings('.sub-menu').slideToggle();
  });
  }
  else // menu script for touch devices
  {
  $('#mob-main-menu > li.menu-item-has-children').click(function(event){
    if ($(this).children('a').siblings('.sub-menu').css('display') == 'none')
      {
        event.preventDefault();
        console.log('hidden');
      }
    $(this).children('a').toggleClass('bold600');
    $(this).children('a').siblings('.sub-menu').slideToggle();
  });
  }

I attempted to use setTimeout() function to resolve this issue but was unsuccessful. Is there a way to limit the code to execute no more than twice regardless of the number of hovers, and then reset after a certain period? Any other suggestions to improve its performance would be greatly appreciated.

Answer №1

Try incorporating the .stop() function when creating animations. This will clear the animation queue, ensuring that it runs smoothly.

$(this).children('a').siblings('.sub-menu').stop().slideToggle();

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

Having an issue with my Wordpress theme where the footer doesn't remain at the bottom of the page

Having trouble with my custom Wordpress theme that I can't seem to fix. Despite extensive research, the footer on my website refuses to stay at the bottom of the page and instead floats in the middle of posts and static pages. I've tried all sol ...

Experience the enhanced features and optimized performance of Onsen 2.0 compared to the earlier version

Apologies if this question is too simplistic, but I am finding some conflicting information in the documentation about using Onsen with Monaca. I am currently utilizing Monaca cloud and I prefer to work solely with pure JS, without incorporating Angular ...

Scraping HTML data without <div> tags with Scrapy - how to do it?

After spending hours attempting to extract a specific data set for use with Scrapy in a web scraping project, here is the current python code: bedrooms_info = house_listing.css( '.search-results-listings-list__item-description__charact ...

Using Laravel 5 for asynchronous AJAX requests can lead to session issues

In my current project, I am working with Laravel 5 ("laravel/framework" version is " v5.1.16", Homestead Ubuntu) and utilizing the 'file' session driver. One issue that has arisen is that when multiple async AJAX requests (using jQuery) are made ...

Tips on Creating a Responsive Absolutely Positioned Div for Various Screen Sizes

I'm currently working on a website and I've come across an issue regarding the responsiveness of an absolutely positioned div across various screen sizes. Let me provide some context and share what I have attempted so far: Issue: Within the head ...

What's the best way to determine the background image on this website? I'm in the process of replicating a site on

I have been asked to clone the website in order to create a Wordpress site. The original site is currently on Kajabi platform. I managed to download all images from the Kajabi site by right-clicking and selecting download. However, there are certain image ...

Reset button for jQuery form to clear all inputted values

My form has a reset button that is supposed to clear all entered values, but it doesn't seem to be working properly. After checking the Firefox console tab for errors, I noticed an 'illegal character' error at the end of my jQuery script. C ...

Distance between cursor and the conclusion of the text (autofocus)

I discovered a method to automatically position the cursor at the end of a string using autofocus: <input name="adtitle" type="text" id="adtitle" value="Some value" autofocus="" onfocus="this.setSelectionRange(this.value.length,this.value.length);"> ...

What are the best ways to ensure that my side menu, bottom buttons, and content are all responsive

I have been struggling with creating a responsive side menu in my HTML code. Despite my efforts, the side menu contents, buttons, and layout do not adjust properly when resizing the browser window. When I drag the browser size from bottom to top, the butto ...

I've noticed that my Bootstrap navbar is currently white, but I have a desire to switch it to a

I'm having trouble changing the transparency of my Navbar. I want it to match the color of my banner image underneath, but no matter what I try with !important, it stays white. Can anyone help me remove the background color from my Navbar? My Navbar ...

What is the reason behind the addition of '.txt' by the Next.js `Link` Component when redirecting to `href='/'` on GitHub pages?

My website is hosted on github-pages, and I am using the Link Component from Next.js to navigate within it. However, when I click on a component with the href="/", it adds .txt to the end of the URL. My website follows the /app structure. I have ...

An issue has occurred: The column name 'B' is not valid. This error originated from the System.Data.SqlClient.SqlConnection

I'm currently working on developing a straightforward registration page using ASP.NET C# in Visual Studio 2013. After attempting to submit the registration details for database insertion purposes, an error occurred. The error message indicated an iss ...

What's Causing the Ternary Operator to Malfunction?

Currently, I am involved in the development of a Chat Room Website and have encountered an issue. It seems that the Ternary Operator is not providing the expected output. Below is the segment of code responsible for this task: html = html.replace(/(@[a-z ...

Learn how to retrieve a jqGrid ajax Nested Array of Json string in C# using Newtonsoft Json

I am attempting to parse a JSON string and extract the array values within it. {"_search":true,"nd":1492064211841,"rows":30,"page":1,"sidx":"","sord":"asc","filters":"{\"groupOp\":\"OR\",\"rules\":[{\"field\":\ ...

Utilizing PHP within a Jquery Variable

Attempting to customize the appearance of new comments on a Wordpress comment list using Ajax. Currently working on this code snippet. The entire code can be accessed here: http://pastebin.com/UHnPgf4J success: function(data, textStatus){ if(data=="succe ...

Generating a JSON response. NodeJS is sending a response with no content

I'm facing an issue with my code where I need to retrieve data from the database multiple times and send a response containing this data. However, for some reason, the response is coming back empty. var express = require('express'), router ...

Angular service to display an array of data

I have been experimenting with Angular, working on small exercises to improve my skills. I have managed to display objects in the controller but am struggling to use service and factory to display an array called "names" on a table. Can someone please revi ...

Animate downwards pointing arrow to rotate 180 degrees upon activation

Is there a way to create a dropdown arrow that rotates when opened? I've experimented with different approaches, such as using CSS methods like .bd-aside .btn[aria-expanded="true"]::before {transform: rotate(90deg);}, along with ::after and ...

What is the best way to trigger a jQuery UI dialog using an AJAX request?

My website includes a jQuery UI Dialog that opens a new window when I click the "create new user" button. Is there a way to open this window using an AJAX request? It would be useful if I could open the dialog-form from another page, such as dialog.html ...

Show the file download link once the file has been selected using jQuery's file upload feature

Is there a way to retrieve the local file path after choosing a file from the file upload? I want to add the file path to the href attribute of an anchor tag so that when I click on the link, it opens or displays the file. Can this be done using jQuery? ...