Select from a dropdown menu with a single click

Need help with my dropdown menu. I'm having trouble getting it to hide when clicking on another element (menu), and the hover effect on the main menu does not stay while the dropdown is open.

$('.menus >li').on('click', '> a' ,function() {
    $(this).siblings('.main-subs').show();      
}).on('click', function(){  
    $(this).siblings('.main-subs').hide();      
});

Check out the demo here

Answer №1

When the mouse hovers over a link in the menu, hide all other submenus with the class name main-subs.

$('.menus >li').on('click', '> a' ,function() {
  $('.main-subs').hide();   
  $(this).siblings('.main-subs').show();    
})

$('.menus >li').on('mouseover', '> a' ,function() {
  $('.main-subs').hide();   
})

Check out the live example on JSFiddle: http://jsfiddle.net/tintucraju/c5ebqaje/1/

Answer №2

Here's a simple CSS solution to display the menu without needing to click on it. Just include this snippet in your CSS:

.menus li:hover a ~ ul {
    display: block;
}

You can see this in action by visiting this link: http://example.com/css-menu-demo

Answer №3

$('ul.list').on('click', 'li > a', function() {
        $('.sub-menu').hide();
        $(this).siblings('.sub-menu').show();  
    }).on('click', function(){  
        $(this).siblings('.sub-menu').hide();      
    });

$(document).click(function(event) { 
    if(!$(event.target).closest('ul.list li a').length) {
        if($('ul.list li a').is(":visible")) {
            $('.sub-menu').hide();
        }
    }        
})

JSFiddle Link

Answer №4

Easy peasy:

.navigation .active { background: green; }

Javascript:

$('.navigation > li').on('click', '> a' ,function() {
        //resetting
         $('.navigation li a').removeClass('active');
         $('.sub-menu').hide();
         //toggling the green color
        $(this).addClass('active');
        //displaying the submenu
        $(this).siblings('.sub-menu').show();  
    });

See it in action here.

Answer №5

In my opinion, the easiest fix would be to introduce a new rule in your CSS file

.menus .main-subs.active { display: block;}

Then, update your function like this:

$('.menus >li').on('click',function() {
    $("a", this).siblings('.main-subs').toggleClass("active");
    $(this).siblings().children(".main-subs").removeClass("active");
});

$('.menus >li').on('click',function() {
$("a", this).siblings('.main-subs').toggleClass("active");
    $(this).siblings().children(".main-subs").removeClass("active");
});
.menus { display: table; width: 70%; height: 76px; }
.menus li { position: relative; display: table-cell; height: 48px; padding: 0; text-transform: uppercase; font-size: 17px; font-family: 'Myriad Pro'; text-align: center; }
.menus li:hover {background:green;}
.menus li.order a { color: #ffffff; }
.menus li.order .main-subs { display: none; }
.menus li a { width: 100%; height: 48px; padding-top: 28px; display: block; color: #b1bbbe; }
.menus li a:hover { color: #fff; }
.menus li:hover { background: green; }
.menus li.current { background: #0383E7; }
.menus li.current a { color: #fff; }
.menus .main-subs { display: none; position: absolute; width: 100%; left: -40px; top: 76px; z-index: 999; }


.menus .main-subs.active { display: block;}


.menus .main-subs li { display: block; height: 51px; padding: 0; border-bottom: 1px solid #0383e7; text-align: left; text-transform: uppercase; background: #0870d3; font: normal 12px 'Malgun Gothic'; }
.menus .main-subs li a { display: block; height: 31px; padding-left: 12px; padding-top: 20px; color: #fff; }
.menus .main-subs li:hover { background: #0866c5; }
.menus .main-subs li:last-child { border-bottom: 0; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menus">
<li>
<a href="#">Main Menu</a>
<ul class="main-subs">
<li><a href="#">Sub Menu 1</a></li>
<li><a href="#">Sub Menu 1</a></li>
</ul>
</li>
<li>
<a href="#">Main Menu2</a>
<ul class="main-subs">
<li class="withsub"><a href="#">Sub Menu 2</a>
</li>
<li class="withsub"><a href="#">Sub Menu 2</a>
</li>
<li><a href="#">Sub Menu 2</a></li>
</ul>
</li>
<li>
<a href="#">Main Menu3</a>
<ul class="main-subs">
<li><a href="#">Main Menu3</a></li>
<li><a href="#">Main Menu3</a></li>
<li><a href="#">Main Menu3</a></li>
</ul>
</li>

</ul>

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 input value remains unaffected by Bootstrap checkbox and radio button selections

On the Bootstrap JavaScript page, there are examples of using buttons to style checkboxes and radio fields. For instance, a checkbox might be written as: <div class="btn-group" data-toggle="buttons"> <label class="btn btn-primary"> <i ...

Easily convert grams to kilograms with just a click of a button using JavaScript

Enter Grams(g): <input type="text" name="grams" id="grams"><br> <br> <button type="button" onclick="kiloConversion()">Convert to Kilogram</button> <p id="conversionResult"></p> ...

The Bootstrap nav-justified feature fails to utilize the entire width available

Have you heard of the bootstrap-4 class called nav-pill? It's meant to make links have equal width and occupy all horizontal space. To achieve equal-width elements, simply use .nav-justified, as suggested. This will ensure that nav links take up al ...

Toggle the class and execute the order within a jQuery script

When the mouse moves in, the jQuery trigger enters the status. $(".test").bind("mouseenter mouseout", function(event) { $(this).toggleClass("entered"); alert("mouse position (" + event.pageX + "," + event.pageY + ")"); }); .entered { ...

Utilizing a server for seamless communication between a mobile device and a website

Exploring a simple setup idea here: Imagine having a mobile app with a page that contains 4 lines of content (utilizing phonegap for development). The plan is to have a web page where data for those 4 lines can be inputted. Once the information is submitt ...

AJAX form in a partial view displaying a summary of validations

I am facing an issue with my application that utilizes an AJAX form. Whenever the form is submitted and fails validation, I return the partial view in which the form resides. In this scenario, I would expect the Validation Summary to be displayed. However, ...

PHP POST data not displaying in output

Having an issue with displaying the chosen value from a database enum in a text field on my website. The enum table has options like Bachelor of Science, Master of Science, Bachelor of Education, and Master of Education. I want to show the selected option ...

The Google Match Content Ad is adapting to larger screen resolutions in order to optimize its display

We've encountered a few problems with Google matched content ads and Bootstrap 4. 1) In larger resolutions, the ad attempts to adjust to the container size: https://gyazo.com/1f7f485f4a0dd91e33e69aaf41af2412 I've experimented with setting a fix ...

Using jQuery to interact with a web service - overcoming cross-domain restrictions

Attempting to connect to a WCF service using a jQuery client. Referencing this specific example: http://www.codeproject.com/KB/aspnet/WCF_JQUERY_ASMX.aspx#4 Everything functions properly when the client webpage is on the same domain as the service. Howe ...

The function data() is coming back as null

This is the code snippet I am working with: $.getJSON("link here", function (result) { $.each(result, function (i, value) { $('.usersOfGroupList').append($("<li id='userElement' data-userId='' ></li>") ...

Load additional content seamlessly using Ajax in Django without needing to reload the entire navigation bar

I recently started working with Django as I develop my own website. I have created a base.html file which includes the main body, CSS, js, fonts, and navbar that will be present on all pages of my site. The navbar is located in another HTML file called nav ...

a Bootstrap 4 element lacking any line-styling

Is it possible to create a link that appears as plain text with no underline, using minimal css? The issue at hand is that the <a> tag defaults to a blue color and adds an underline on hover, making it look like a typical link. I would like it to re ...

Tips for automatically selecting the state from a dropdown list when utilizing address autofill

I created an HTML form and noticed that Chrome's autofill feature successfully fills in the street address, city, and zip code. However, when I use a select/option dropdown list for the state input, it does not get auto-filled. I have tried using sta ...

Is it possible to include an onclick event in a hyperlink tag to initiate an ajax call

I am looking to incorporate an ajax call within a hyperlink tag "a". The purpose of this ajax call is to send some information to the server without expecting any return value. I attempted the following approach: document.querySelector("#myId").onclic ...

What is the correct way to utilize JSON with AJAX?

I am looking to transfer data from a php backend to a browser using JSON. I have a basic understanding of the process and have included an example code snippet below. However, I have been advised that this may not be the most efficient approach. Due to my ...

Has the zip creation tool in the Google Doodle on April 24th been coded entirely in JavaScript?

Was the Gideon Sundback Google doodle created using JavaScript? I attempted to follow along in Firebug, but I couldn't quite grasp its implementation details. Any ideas on how it was possibly implemented? Any insights on the potential techniques use ...

Understanding the values of the jQuery "Each" function

Initially, I crafted the original AJAX function: dataType: 'json', data : { action: something , id: id}, success: function(data) { var my_title= data.title; // values: "post1,post2,post3" var my_name = data.name; // values: "stev ...

What is the best way to send a selected value to a different function in order to retrieve data from a JSON file based on that

I have been working on writing HTML and JavaScript code to extract data from a JSON file. Here is a snippet of my HTML code: <div class="section"> <div class="sectionTitle"> <h3>Configuration</h3> </div> &l ...

Is it frowned upon or considered incorrect to achieve a horizontally centered page by adjusting the CSS properties of the html tag?

Is it considered wrong or frowned upon to center a webpage horizontally by adjusting CSS properties of the HTML tag? Sample CSS code: <style type="text/css"> html { width: 1200px; margin: 0px auto; background-color: ...

What could be causing PHP to incorrectly display form data?

After learning html and css, I decided to venture into php scripting. My goal is to retrieve input from an HTML form using php code that looks like this: form.html : <html> <body> <form action="action.php" method="POST&q ...