Creating a JavaScript function to automatically hide a dropdown menu after a specific duration

I'm currently working on a side menu that drops down when hovering over Section One within the <a> tag. I need some guidance on how to make the JavaScript code continuously check the state of the list after a set amount of time in order to automatically close the menu. Can anyone offer some assistance?

HTML

<div class = "sidebarwrap">
    <ul>
       <li>
        <a href="#" onmouseover="toggle(this); return true;" onmouseout="timer()">Section One</a>
            <ul>
               <li><a href="#" >link page</a></li>
               <li><a href="#" >link page</a></li>
               <li><a href="#" >link page</a></li>
               <li><a href="#" >link page</a></li>
            </ul>
       </li>
     </ul>
   </div>

CSS

.sidebarwrap{
    width:auto;
    height:auto;
}

.sidebarwrap ul{
    float:left;
    display:block;
    background:white;
    padding:10px;
    margin-right:30px;
    margin-left:10px;
    list-style-type:none;
    border:1px dotted #0099CC;
    border-radius:100px/10px;
}

.sidebarwrap ul ul{
    list-style-type:none;
    display:none;
    border:0px dotted #0099CC;
    border-radius:20px/60px;
}

.sidebarwrap li li{
    list-style-type:circle;
    border:0px dotted #0099CC;
    border-radius:20px/60px;
    padding:5px;
}

JavaScript

var cssNode = document.createElement('link');
cssNode.setAttribute('rel','stylesheet');
cssNode.setAttribute('type','text/css');
cssNode.setAttribute('href', 'javascript-overrides.css');
document.getElementsByTagName('head')[0].appendChild(cssNode);


function toggle(toggler) {

    if(document.getElementById){
        targetElement = toggler.nextSibling;

        if(targetElement.className == undefined){
            targetElement = toggler.nextSibling.nextSibling;
        }

        if (targetElement.style.display == "block") {
            targetElement.style.display = "none";
        } else {
            targetElement.style.display = "block";
            timer();
        }
    }
}

function timer(){
    var Time = setTimeout(function(){toggle(toggler)},1000);
}

Answer №1

To achieve this functionality in jQuery, you can utilize the .hover() method. Simply attach the event to the link when the page is loaded.

$(document).ready(function () {
    $("a").hover(function () {
       $(this).next().slideDown(); 
    },
    function () {
        $(this).next().delay(1000).slideUp();
    });
});

For a demonstration, refer to this working example: http://jsfiddle.net/WFN6q/

If you prefer using Vanilla JS, here is a sample implementation:

<ul>
    <li>
        <a href="#" onmouseover="showMenu(this)" onmouseout="hideMenu(this)">Section One </a>
        <ul>
            <li>text</li>
            <li>text</li>
            <li>text</li>
            <li>text</li>
        </ul>
    </li>
</ul>

Include the following JavaScript code:

function showMenu(myLink) {
    myLink.nextElementSibling.style.display = 'block';
}

function hideMenu(myLink) {
    var ulElem = myLink.nextElementSibling;
    if (ulElement.style.display === 'block') {
        setTimeout(function () { myLink.nextElementSibling.style.display = 'none' }, 1000);
    }
}

Answer №2

After analyzing your code, it came to my attention that you have set onmouseout to call timer(), creating an unnecessary timeout function without defining toggler. This leads to a continuous recursion every ~1000ms.

To address this issue, I recommend establishing a global Timers variable to manage your timer references. This will allow you to exit the function and manipulate or cancel the timer as needed. Additionally, implementing a Singleton model can help prevent multiple instances of timers from being created.

var Timers = {}; // initialize a Timers object to store timers.
function timer(target){
    Timers.sectionOne = setTimeout(function(){ toggle(target); }, 1000);
}

Furthermore, consider incorporating the approach suggested by @Bic for a more elegant solution.

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

Array Filtering Results in an Empty Array of Objects

I'm currently attempting to filter out all objects from the projects array that do not appear in the savedProjects array, but I'm ending up with an empty result. Could it be that I am approaching the filtering process incorrectly? Here's my ...

Using a modal within a map function: Tips and tricks

I've been working on a Gallery application using React.JS and Reactstrap. The application uses the map() function to display each piece of art in a Card. Each card has a button that triggers a modal to show more data from the map function. However, I& ...

When the document is fully loaded and processed, a script will be executed immediately following

I'm facing an issue with a modal plugin on my website. The plugin is triggered on $(document).ready, but I have another function (innerHTML) that inserts an <a> element 5-10 seconds after the page loads. This causes the modal not to work properl ...

Mozilla browser experiencing issues with mouse move event functionality

Here, I have a background image on the body and with the following script, when the user moves the mouse, the image in the background also moves. body { background-image: url('../images/1.png'); background-size: 98%; background-posi ...

Tips for waiting for an event from a specific element in Playwright

Is there a way to await an event on a specific element using Playwright? Similar to page.waitForEvent, but focusing only on a particular element rather than the entire page. More information can be found in the documentation. ...

Encountering a NullPointerException while trying to load a resource from a directory that is not within

I'm working with JavaFX and trying to incorporate a CSS file into my scene. scene.getStyleSheets().add(Main.class.getResource("res/application.css").toExternalForm(); An NPE is being thrown. I suspect it's because the css file isn't locate ...

Protecting a Web Function

Suppose I have a C# MVC method to send emails using AJAX, like this: public class EmailController : Controller { SmtpClient mailserver = new SmtpClient("smtp.foo.com"); public string sendEmail(string from, string to, string subject = "", ...

Something seems off with the performance of Gulp-filter and it is not

I am struggling with the following piece of code: gulp.src('src/*.*') .pipe(filter(['**', '!**/*.{png,jpg,bmp,jpeg,jpeg2,webp,svg}', '!**/*.{css,less}'])) .pipe(gulp.dest('dev/')); This code is sup ...

The most effective way to align text in a right-to-left language is by utilizing the text-align property with a

If the project is in a right-to-left language (such as Persian or Arabic), which method is preferable for setting text-align: right and direction: rtl? Option 1: Implement globally, for example: body * { direction: rtl; text-align: right; } ...

What is the best way to nest _app.js within several providers?

Is there a way to wrap my top-level page _app.js in both Redux provider and Next-auth provider? Currently, I have already wrapped it in the Next-auth provider like this: import React from "react" import { Provider } from 'next-auth/client&ap ...

Remove dynamically created elements from an AngularJS div

Is there a way to remove an item from the criteria list when clicking the delete button? Currently, only the filter is being refreshed and not the tables. Any suggestions on how to resolve this issue? HTML <ul class="list-unstyled"> <l ...

Encountering an issue with my code in CodeIgniter

I encountered an error when trying to make an AJAX request in CodeIgniter, unlike the usual process in core PHP where we specify the file URL containing the query. The error I received was net::ERR_SSL_PROTOCOL_ERROR . Here is the JavaScript AJAX code sni ...

Certain hyperlinks are refusing to open within an embedded iframe

I'm currently facing an issue with finding a solution for a simple problem. I am in the process of developing a portfolio plugin and one of the requirements is to showcase projects within an iframe to demonstrate their responsive layout. However, I&ap ...

Unusual host value being returned by next/headers in Next.js version 13

In my current Next.js project, I am utilizing next/headers to dynamically set a baseUrl for calls to my API. const baseUrl = () => { const protocol = process?.env.NODE_ENV === "development" ? "http" : "https"; const ...

AngularJS Module Instantiation Error

My angularjs module is not loading correctly and I'm struggling to figure out why. Despite reading numerous tutorials, I can't seem to get it to work. [17:22:36.338] Error: [$injector:modulerr] Failed to instantiate module wc2013mongoMod due t ...

Guide to horizontally aligning a div with a dynamic width in the center

After extensive research, I discovered that setting a width allows you to center a div using margin: 0 auto along with left: 0;, right: 0, and position: absolute. However, all the examples I found had a specified width. In my specific case, I need to cent ...

Tips on how to ensure the navigation menu is the same size as its child elements in the navigation menu

I'm currently designing a navigation menu that includes a child navigation menu. My goal is to have the size of the main navigation menu match that of the child navigation menu. To achieve this, I've created three hyperlink tags followed by a di ...

Dynamic CSS Changes in AngularJS Animations

I am currently working on a multi-stage web form using AngularJS. You can see an example of this form in action by visiting the link below: http://codepen.io/kwakwak/full/kvEig When clicking the "Next" button, the form slides to the right smoothly. Howev ...

Having trouble accessing properties that are undefined while using react JS, specifically when trying to read a 'map' property

Currently, I am in the process of building a blog with ReactJS and NextJS within VS Code. Despite not encountering any errors during coding, when I attempt to run it, the browser displays: "TypeError: Cannot read properties of undefined (reading 'map& ...

Styling HTML elements using CSS within PHP echo statements

I am a beginner when it comes to PHP and I'm trying to figure out how to style this table. I tried creating a class, but changing the styles in a separate CSS file didn't work for me. Should I use style tags? How should I go about styling this? ...