Troubleshooting a jQuery Drop-Down Problem

My dropdown menu is not working as expected. I want to show the sub-menu when clicking on an item, and remove the previous sub-menu when clicking or blurring on another menu by removing the drop-down class. However, my current jQuery code does not seem to be functioning properly.

jQuery

$('.menu_item > li ').click(function(){
    $('.menu_item .drop-down').removeClass();
    $(this).find('span').addClass('drop-down');
});

$('.menu_item .drop-down').blur(function(){
    $('.menu_item .drop-down').removeClass();
    return false;
});

HTML

<nav id="menu_wrap" class="container">
    <a href="index.php" class="logo"></a>
    <a href="#" id="select_menu" class="active" onclick="open_menu()">Menu</a>
    <ul class="menu_item">
        <li><input type="text" placeholder="Search in here" class="search"></li>
        <li><a href="#">Top Lists</a></li>
        <li><a href="#">Shops</a></li>
        <li><a href="#">Products</a>
            <span>
            <a href="#">Products</a>
            <a href="#">Products</a>
            <a href="#">Products</a>
            <a href="#">Products</a>
            </span>
        </li>
        <li><a href="Signup.php">Create Account</a></li>
        <li><a href="Login.php">Log in</a></li>
    </ul>
</nav>

Answer №1

There may be a more efficient method to accomplish this task, but the solution provided is suitable for the specific scenario you have outlined.

$(document).ready(function() {

    $(document).click(function(e) {
        var $target = $(e.target);
        $('.menu_item .drop-down').removeClass();
        if ($target.parents().is('.menu_item > li')) {
            $target.parent().find('span').addClass('drop-down');
            if ($target.parent().is('span')) {
                $target.parent().addClass('drop-down');
            }
        }
    });

});​

Here is the JSFiddle link for reference.

Answer №2

Check out this solution:

view demo

 $('.menu_item li').click(function() {
     $('.menu_item .drop-down').removeClass();
     $(this).find('span').addClass('drop-down');

 });

 $('.menu_item li').mouseleave(function() {
     if ($(this).find('span').length > 0) {
         $(this).find('span').removeClass('drop-down');
     }
 });

Answer №3

It seems like I have the solution for you:

$('.menu_item > li ').click(function(){
    $('ul.menu_item li span').removeClass('drop-down');
    $(this).find('span').addClass('drop-down');
});

$('.menu_item .drop-down').blur(function(){
    $('ul.menu_item li span').removeClass('drop-down');
    return false;
});

This code will remove all instances of the drop-down class from all span elements within the menu_item class.

If you only want to close the previous drop-down, you need to select it using the appropriate selectors starting from $(this).

UPDATE:

I understand your goal now! You want to target all elements in order to close the drop-down menu, except for those where you want to add the drop-down class (in this case: $('.menu_item > li')). To achieve this, introduce another jQuery click function and adjust the selectors accordingly:

$('div').not('.menu_item li').click(function(){
        $('.menu_item .drop-down').removeClass('drop-down');
});

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

send parameter when clicking a link rather than using a hashtag

One interesting feature on my website is a menu link with the attribute title=.roc. When this link is clicked, I want to extract this attribute and click on an element with the same attribute on the destination page. Let's consider a scenario where I ...

Angular unable to find a route for external links

I am attempting to create an external link with an <a href="google.com"></a>, but for some reason it redirects me to localhost:4200/google.com... I'm not sure why this is happening, but I need to eliminate the localhost:4200. Below is the ...

Text field auto-saving within an iFrame using localStorage is not functioning as expected

My goal is to create a rich text editor with an autosave feature using an iframe. Although each code part works individually, I am struggling to combine them effectively. View LIVEDEMO This graphic illustrates what I aim to accomplish: The editable iFram ...

Modifying background with JavaScript and AJAX技术

I currently have a table structured like the following; <table style="width: 100%; border: solid 1px #666600; min-width: 800px" cellpadding="0" cellspacing="0"> <tr> <td id="aaa">&nbsp;</td> ... Using jQuery's ajax functi ...

"Experience the magic of Datepicker jQuery with just a click

Does anyone know how to capture the click event when a day is selected using jQuery Datepicker? Is it possible, and if so, how can I achieve this? https://i.sstatic.net/ZG4r8.png Here is the HTML code snippet: Date From : <input type="text" ...

Prevent the ability to drag and drop within specific div elements

Having trouble disabling the sortable function when the ui ID is set to "comp". Can't figure out what's going wrong, hoping for some assistance here. $(".sort").sortable({ // start sortable connectWith: ".sort", receive: function ...

Token Fields malfunctioning

I attempted to use a sample from bootstrap, but I am not having any luck with it. Is there anyone who can assist me in resolving this issue and understanding it better? Code Snippet: <input type="text" class="form-control" id="tokenfield" value="red, ...

Centering Images Using CSS Floats

I've got this HTML code featuring images and titles: <div class="container"> <div class="box"><a href="#" class="catname"><img src="image1.jpg" class="thumb"><p>Title 1</p></a></div> <div class="box" ...

Is there a more efficient method for handling this JSON dataset?

After delving into Sitepoint's "Novice to Ninja" and starting to explore jQuery, I can't help but question if there is a more efficient way to write the code I've put together. The resounding answer appears to be "yes." All these cumbersome ...

Using JQuery to Load Text Content from Textarea into an IFrame

Seeking a solution to transfer HTML textarea content into an IFrame upon button click. Any suggestions on achieving this functionality? Thank you in advance. Illustratively, when a user types Hello World in the textarea and clicks the submit button, the t ...

insert a new DOM element into an array using jQuery

Looking at the code snippet below: a_ajouter = $('.question'); hidden_div.push(a_ajouter); console.log(hidden_div); Upon examining the output in the console, instead of a DOM object being added to the div as intended, it shows &apo ...

The functionality of Bootstrap's Modal feature seems to be malfunctioning

I'm attempting to test the sample modals for my project, but even the codes from jfiddles are not working for me. When I click the button, it only gives me a dimmed window. I have also tried searching on Google for a solution, but to no avail. Below ...

Generate dynamic Bootstrap Carousel slides with unique hashtag URLs

I've been attempting to connect to various slides within a bootstrap carousel from a different page but have had no success. Here is an example of what I'm trying to achieve: <a href="services#slide2">Link to Slide 2</a> For refere ...

Utilizing an overlay to conceal both the body content and the input fields

I have a website that includes a sliding overlay div which triggers when the user exits a specific area. To showcase this, I created a demonstration on jsfiddle. http://jsfiddle.net/qxcd8y1L/ <body class="overlay"> <input> </body> ...

Issue with JQuery .fadeToggle() function: Unexpected behavior causing automatic fade-out

$(document).on('click', '.tree label', function(e) { $(this).next('ul').fadeToggle(); e.stopPropagation(); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul cl ...

"Beginner's guide to utilizing JQuery and AJAX with PHP

I am struggling to grasp the concept of using AJAX and jQuery to post data without reloading the page. Specifically, I am facing issues with the form reloading the page and not updating variables. Here is the code I have been working on: Initially, I was ...

Converting a string to regular text in JavaScript (specifically in ReactJS)

When I fetch data from an API, sometimes there are special characters involved. For example, the object returned may look like this: { question : "In which year did the British television series &quot;The Bill&quot; end?" } If I save t ...

Using AJAX to inject JSON data from PHP into Edge Animate

For a school assignment, I am currently working on a project using edge animate. My objective is to import data from a database hosted on my school's webspace and incorporate it into the edge animate project. Despite researching online for a solution ...

Why does the container overflow when the child is floated in CSS?

Can you explain why a parent div element stops adjusting its height when its child is floated? Here is the HTML snippet: <!DOCTYPE html> <html> <head> <title>test</title> <link rel="stylesheet" type="text/css" href="in ...

What methods can I use to guarantee that a cloned HTML element retains a specific property during Unit Testing?

During my HTML cloning process, I am using the following code snippet: var clone = document.getElementById('tempID').cloneNode(true); After creating the clone, I need to modify its ID by assigning a new unique identifier with clone['id&apo ...