Step-by-step guide on interacting with a JavaScript menu: Click to open the menu and close it by moving

My menu JavaScript function now opens with a click and closes with a click. I want it to open with a click and close when the mouse leaves the button.

$("#theme_select").click(function() {
    if (theme_list_open == true) {
        $(".center ul li ul").hide();
        theme_list_open = false;
    } else {
        $(".center ul li ul").show();
        theme_list_open = true;
    }
    return false;
});​

I made changes with one person and fixed the top problem, but when I tried to move my mouse to an opened menu item, the menu was closed. See my full script (before the change):

<script type="text/javascript">

    var theme_list_open = false;

    $(document).ready(function () {

        function fixHeight () {

        var headerHeight = $("#switcher").height();

        $("#iframe").attr("height", (($(window).height() - 1) - headerHeight) + 'px');

        }

        $(window).resize(function () {

            fixHeight();

        }).resize();

        $("#theme_select").click( function () {

            if (theme_list_open == true) {

            $(".center ul li ul").hide();

            theme_list_open = false;

            } else {

            $(".center ul li ul").show();               

            theme_list_open = true;

            }

            return false;

        });

        $("#theme_list ul li a").click(function () {

        var theme_data = $(this).attr("rel").split(",");

        $("li.purchase a").attr("href", theme_data[1]);
        $("li.remove_frame a").attr("href", theme_data[0]);
        $("#iframe").attr("src", theme_data[0]);

        $("#theme_list a#theme_select").text($(this).text());

        $(".center ul li ul").hide();

        theme_list_open = false;

        return false;

        });

    });

    </script>

Answer №1

Is this how you do it?

For example.. (Simply adjust your element selector, if you are familiar with jQuery)

HTML :

<ul>
    <li>Item#1</li>
    <span>Sub item</span>
    <li>Item#2</li>
    <span>Sub item</span>
</ul>

jQuery :

$("ul li").click(function () {
    $(this).addClass("active").next("span").show();
});

$('ul').mouseleave(function() {
  $("ul li.active").removeClass().next("span").hide();
});

Demo : http://jsfiddle.net/ahCxK/

In your customized scenario... It will appear like this.

$("#selection_button").click(function() {
    if (list_open == false) {
        $(".container ul li ul").addClass("open").show();
        list_open = true;
    }
    return false;
});

$("#selection_button").mouseleave(function() {
  $(".container ul li ul.open").removeClass().hide();
    list_open = false;
});

or

$("#selection_button").click(function() {
    if (list_open == false) {
        $(".container ul li ul").show();
        list_open = true;
    }
    return false;
});

$("#selection_button").mouseleave(function() {
    if (list_open == true) {
      $(".container ul li ul").hide();
        list_open = false;
    }
});

Answer №2

[To clarify @PeeHaa's point,] Utilize the jQuery .hover() method.

$("#theme_select").click(function() {
    if ($("#theme_select").is(":visible")) {
        $(".center ul li ul").hide();
    } else {
        $(".center ul li ul").show();
    }
    return false;
});​


$("#theme_select").hover(function() {
     //Do Nothing
    },function(){
        $(".center ul li ul").hide(); //Mouse leave
});​

The first function is triggered when the mouse hovers over theme_select, while the second function is executed upon the mouse leaving theme_select.

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

The html-duration-picker is not being displayed in the proper format

I've been working on integrating an external library that allows for inputting document length. Specifically, I'm using the html-duration-picker library, but it seems like the input functionality is not quite right for durations. Could it be th ...

An unusual error occurred stating that the `forEach` property does not exist on the given type

I am working on a chess game and encountering some Typescript errors that I'm struggling to comprehend. The issue arises in the following class method: clickEvent (e: MouseEvent): void { const coordinates: ClientRect = this.chessBoard.getBounding ...

Creating a Duplicate of the Higher Lower Challenge Game

To enhance my comprehension of React, I am constructing a replica of the website: Instead of utilizing Google searches, I opted for a dataset containing Premier League stadiums and their capacities. Up to this point, I have crafted the subsequent script: ...

What are some of the potential drawbacks of utilizing the same template ref values repeatedly in Vue 3?

Is it problematic to have duplicate template ref values, such as ref="foo", for the same type but different instances of a component across views in a Vue 3 application? Let's consider the following example pseudocode: // ROUTE A <te ...

Having trouble locating HTML elements by their id when typing into a box using cy.get in Cypress with JavaScript

I am a novice in working with cypress and HTML, and I am currently attempting to enter an address in the specified address field. <input type="text" title="Street Address 1" name="billing[street][]" id="billing:street1" value="" class="input-text " ...

Updating existing text to create personalized HTML dropdown menus

I have designed a unique set of dropdowns by using divs and checkboxes instead of the traditional elements My goal is to dynamically change the 'select-wrapper--title' text (e.g. the first option) based on the selected option in the dropdown I ...

Generating an array within the custom hook results in the value being re-rendered with each change in state

While working on a custom hook in react native, I ran into an issue with the combination of useEffect and useState that led to an infinite loop. To demonstrate the problem, I created a small snack: import React, { useEffect, useState, useMemo } from &apos ...

How can I retrieve the children of a component in React?

Currently, I am working on implementing Class Components for a project involving a main picture and a smaller pictures gallery stored in an array. The overall structure consists of an all pictures container that houses both the main picture and smaller pic ...

Issue with Jquery Fancybox shadow rendering on older versions of Internet Explorer (IE7/IE8

Take a look at this demo page: Notice that the popup has a shadow around it in most browsers, but not in IE7/IE8. I'm seeking advice on how to make the shadow appear in those browsers as well. Any suggestions? ...

An issue has arisen in the production environment on AWS EC2 due to a problem with Nodemailer

When using nodemailer with node.js to send emails, I have set up the following configuration: var transporter = nodemailer.createTransport({ service: 'gmail', host: 'smtp.gmail.com', auth: { ...

`How can I extract information from the internet?`

I am attempting to retrieve data from the following URL: . My focus is on obtaining the raw data series rather than the data presented in tables and charts. Although the website provides a button for downloading a .csv file, I am unsure of how to automat ...

Adjust the clarity of the elements within my HTML document

I have been working on creating a login page that will appear in front of the main webpage. Through my online research, I discovered a technique to blur the main webpage background until the user logs in. Below is the code snippet: HTML: <div id="logi ...

The ƒ character doesn't seem to be a match for the JavaScript regex

I am facing a requirement to only allow (extended) ASCII characters in my input. As a solution, I've implemented a JavaScript regex pattern like this: /^[\x20-\xff]+$/.test("helloê¿£×جáƒ") However, this doesn't work as expect ...

How to filter jQuery DataTables by column using comparison operators

Recently, I've been utilizing the amazing DataTables jQuery plugin along with the filter plug in. But now, I find myself pondering if there's a way to filter table columns by row using a comparison operator (such as '<', '>&a ...

Halt the script if the file has not been successfully loaded

Looking for a way to halt the script until $.get() has completed executing in this code snippet. $.get("assets/data/html/navigation.html", function(response) { $('body').append(response); }); $('body').append('<div class="m ...

Utilizing Vue.js for the selection of multiple elements

I am currently in the process of transitioning from jQuery to Vue, and I have encountered an issue when trying to select multiple elements within a single Vue instance. For instance, On my website, there are two posts each with a comment form. I want to ...

Having difficulty sending ajax to the controller function

Currently, I am facing an issue with updating my database using AJAX in Laravel. The goal is to change the value in the enable column from 1 to 0 when a toggle button is clicked. Below script is included in the view: $(".toggle-btn").change(function() { ...

Using fancybox to send an ajax post request to an iframe

Can you send a variable to the iframe when using fancybox? This is my current setup: function fancyBoxLoad(element) { var elementToEdit = $("#" + $(element).attr("class")); var content = encodeURIComponent($(elementToEdit).oute ...

When using Vuejs2, the list of autosize textareas connected to an expanding array of objects does not properly update their values

After binding https://github.com/jackmoore/autosize to textareas within a v-for loop, I've noticed an unexpected data persistence issue while expanding the array linked to that list: While inputs on the left side move downward as intended, new textar ...

Efficiently pinpointing the <div> element with precision using jQuery

I am building an interactive quiz for users of my app. The questions are table based, and can be answered "yes," "no," or "maybe." If the user answers "no" or "maybe," I would to slide open an informational panel that lives beneath the table. Here is the ...