Toggle menu but also allows click inside without closing - javascript

Firstly apologies for the random title, I really can't think of another way to word it succinctly.
This is my issue.
I have a couple of nav icons, that when clicked toggle menu displays, just like you see everywhere: facebook, etc.
When you click outside of the div it hides the menu.
It works but I have two problems.
Clicking outside works to close the open div, but clicking on the icon that triggers the toggle doesn't close it, it just re-toggles it instantly.
I would like to be able to click inside of the menus without them closing, which they are currently doing onclick.
The html looks something like this, where the user-menu is the click-able icon that toggles the div contained within.
HTML
<nav>
<div class="user-menu">
<div id="user-dropdown">MENU CONTENTS HERE</div>
</div>
</nav>
jQuery
$('.user-menu').click(function () {
$('#user-dropdown').fadeToggle();
});
$(document).mouseup(function(e) {
var container = $("#user-dropdown");
if (!container.is(e.target) && container.has(e.target).length === 0) {
container.hide();
}
});
FIDDLE
https://jsfiddle.net/vo8a1r0p/
EDIT - ANSWER
Using a mixture of Bhuwan's answer and a stopPropagation() it's now working.
Working jQUERY
$(document).on("click", function(e) {
if ($(e.target).hasClass("user-menu")) {
$('#user-dropdown').fadeToggle();
} else {
if ($(e.target).hasClass("dropdown-menu")) {
$('#user-dropdown').show();
} else {
$('#user-dropdown').fadeOut();
}
}
});
$("#user-dropdown").click(function(e){
e.stopPropagation();
});
Working FIDDLE
https://jsfiddle.net/ne4yfbjp/

You can try this
$(document).on("click", function(e) {
if ($(e.target).hasClass("user-menu")) {
$('#user-dropdown').fadeToggle();
} else {
if ($(e.target).closest("#user-dropdown").hasClass("dropdown-menu")) {
$('#user-dropdown').show();
} else {
$('#user-dropdown').fadeOut();
}
}
});
.dropdown-menu {
display: none;
background: gray;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
<div>
<button class="user-menu">Menu</button>
<div id="user-dropdown" class="dropdown-menu">
<div class="username">
Some User
</div>
<ul>
<li>Link1</li>
<li>Link1</li>
</ul>
</div>
</div>
</nav>

Related

jQuery toggle show/hide default content

I have a show/hide toggle that switches between content if menu a is clicked.
Before the click function is triggered content is shown in the default div.
For some reason if you click one of the a tag's twice it successfully toggles the content on/off; however you are left with a blank screen
This is a poor user experience.
How can I avoid this and ensure that the default content is shown if a user selects a menu item twice?
$(document).ready(function() {
var $show = $('.show');
$('.menu a').on('click', function(e) {
e.preventDefault();
$show.not(this).stop().hide(450);
$($(this).attr('href')).stop().toggle(450);
$('.default').addClass('hidden');
});
});
.hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="menu">
Screen
Music
Art
Food
</div>
<div id="show-screen" class="show">show screen</div>
<div id="show-music" class="show">show music</div>
<div id="show-art" class="show">show art</div>
<div id="show-food" class="show">show food</div>
<div class="default">default content</div>
Thanks
Although I'd suggest a completely different approach to handle this problem, to make your code work, I'd do something like this.
https://jsfiddle.net/6cnt95ap/1/
$(document).ready(function() {
var $show = $('.show');
$('.menu a').on('click', function(e) {
e.preventDefault();
$show.not(this).stop().hide(450);
$($(this).attr('href')).stop().toggle(450);
$('.default').addClass('hidden');
window.setTimeout(()=>{
var showDefault = true, divs = $('.show');
divs.each(function(){
if($(this).css("display") !=='none'){
showDefault = false;
return false;
}
});
if(showDefault){
$('.default').removeClass('hidden');
}
}, 500)
});
})

Use jQuery to click anywhere and remove 'active' class

I'm having some trouble figuring out how to close a div by clicking anywhere on the screen.
I'm currently toggling an 'active' class in order to display a drop down div, then attempting to remove that class by clicking on the body:
$(document).ready(function () {
$('.navbar a').click(function () {
$(this).next('.navbar-dropdown').toggleClass('active');
});
$(body).click(function() {
if($('.navbar-dropdown').hasClass('active')){
$('.navbar-dropdown').removeClass('active');
}
});
});
<ul class="navbar">
<li>
Link
<div class="navbar-dropdown">
Dropdown Content
</div>
</li>
</ul>
However they are conflicting with each other, so as soon as the class is toggled on, the 'body' click toggles it off at the same time. Have spent some time looking on here and came across this method a few times:
$(document.body).click( function() {
closeMenu();
});
$(".dialog").click( function(e) {
e.stopPropagation();
});
However any attempts to configure this to work correctly seemed to fall on deaf ears!
The click event from the navbar is bubbling up to the body, so both events fire. stopPropagation() is one way to prevent that, but you need to do it in the navbar link's event handler, so it stops that particular event; not in a separate event handler as you had it.
Another change you might consider making is to only assign the body click handler when you need it, instead of firing all the time -- create that handler inside the navbar's click handler, and deactivate it again when it's used:
$(document).ready(function() {
$('.navbar a').click(function(e) {
var myDropdown = $(this).next('.navbar-dropdown');
$('.navbar-dropdown.active').not(myDropdown).removeClass('active'); // close any other open dropdowns
myDropdown.toggleClass('active'); // open this one
$('body').click(function() {
// no need for an if statement here, just use a selector that matches the active elements:
$('.navbar-dropdown.active').removeClass('active');
$('body').off('click'); // cancel the body's click handler when it's used
});
e.stopPropagation(); // prevent the navbar event from bubbling up to the body
});
});
.active {
color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="navbar">
<li>
Link
<div class="navbar-dropdown">
Dropdown Content
</div>
</li>
<li>
Link 2
<div class="navbar-dropdown">
Dropdown Content 2
</div>
</li>
<li>
Link 3
<div class="navbar-dropdown">
Dropdown Content 3
</div>
</li>
</ul>
(If there's a chance you might need more than one separate click event handler on the body, you can namespace the event so you can control which one you're turning off:
$('body').on("click.myNamespace", function() {
// do other stuff
$('body').off("click.myNamespace")
})
I did the exact thing as you and it works for me. Are you sure you don't have any other event listeners attached? Or maybe a z-index on the menu bringing it underneath other elements?
$(document).click(function(e) {
$(".dialog").text('closed')
});
$(".dialog").click(function(e) {
e.target.innerText = 'open';
e.stopPropagation();
});
.dialog {
width: 200px;
height: 200px;
background: antiquewhite;
text-align: center;
}
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="dialog">open</div>
</body>
</html>

How do I make a .hover div stay open while the mouseover is still on the parent?

First things first, a fiddle: http://jsfiddle.net/d7wfv8w8/
I have a navbar with a logo, search form and a Categories link. When somebody moves over it with the mouse, it should open the wrapper-categories div, which is display: none; by default.
I got it working, except the div is closing when you then move the mouse over the div that opened. I thought I could get it to stay open if I used .navbar .toggle to tell it that the parent is .navbar and it should stay open as long as the mouse is anywhere over that parent div.
How can I achieve this?
Here is my HTML:
<div class="navbar">
<div class="wrapper-header">
<ul>
<li class="">Logo Here</li>
<li class="">Search Here</li>
<li class="">Categories</li>
</ul>
</div>
<div class="wrapper-categories">
Categories Here
</div>
</div>
And the jQuery:
$(".navbar .toggle").hover(function (event){
event.preventDefault();
$(".wrapper-categories").slideToggle("fast");
});
You can achieve this by binding the hover function to the element wrapping both wrapper-header and wrapper-catagories. This will cause the hoverOut to only be called when it leaves the wrapper for both elements. Keeping both of your required divs open.
Fiddle: http://jsfiddle.net/d7wfv8w8/5/
Late to the party but change your class' to ID's and give this a go. Works for me.
$(document).ready(function(){
$( "#toggle" ).hover(
function() {
$( "#wrapper-categories" ).slideDown({
left: "+=50",
height: "toggle"
}, 500, function() {
// Animation complete.
});
}
);
var inArr = {toggle:false, wrapper-categories:false};
$('#toggle, #wrapper-categories').mouseover(function(){
inArr [$(this).attr('id')] = true;
});
$('#toggle, #wrapper-categories').mouseout(function(){
inArr [$(this).attr('id')] = false;
setTimeout(function(){
if(!inArr.toggle && !inArr.wrapper-categories) {
$('#navArea').slideUp(500);
}
},100);
});
});

jquery hide div when click outside

I am trying to style div and ul to function like . However, I have a problem that:
1) I only want to toggle the ul that I click and hide the other ul. So I wonder if jquery support some function such as 'not click'?
2) I want to hide all the ul when the mouse is click outside. I did some research, and see other people use mouseup or click on body. But I am not quiet sure how it works.
$(document).ready(function() {
$('.hide').each(function() {
$(this).hide();
});
$('.select').click(function() {
var id = '#' + $(this).attr('id');
var sub = id + '_sub';
$(sub).slideToggle();
});
$('body').mouseup(function() {
if($(this).length == 0) {
$(this).hide();
}
});
});
div.select {
display: inline-block;
margin: 10px;
padding: 20px;
background: red;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="1" class="select">
<div class="main">
<span>1</span>
</div>
<div>
<ul id="1_sub" class="hide">
<li>1</li>
<li>2</li>
</ul>
</div>
</div>
<div id="2" class="select">
<div class="main">
<span>1</span>
</div>
<div>
<ul id="2_sub" class="hide">
<li>1</li>
<li>2</li>
</ul>
</div>
</div>
<div id="3" class="select">
<div class="main">
<span>1</span>
</div>
<div>
<ul id="3_sub" class="hide">
<li>1</li>
<li>2</li>
</ul>
</div>
</div>
</body>
here you go: DEMO
$(document).ready(function() {
$('.hide').hide(); //hide in the beginning
$('.select').click(function() {
$('.hide').slideUp(200); //hide all the divs
$(this).find('.hide').slideDown(200); //show the one that is clicked
});
$(document).click(function(e){
if(!$('.select').is(e.target) || !$('.select').has(e.target)){ // check if the click is inside a div or outside
$('.hide').slideUp(200); // if it is outside then hide all of them
}
});
});
you can define your notClick() function as below:
$.fn.notClicked= function(clickPosition){
if (!$(this).is(clickPosition.target) && $(this).has(clickPosition.target).length === 0){
return true;
}
else{
return false;
}
};
and then use it as:
$(document).click(function(e){
alert($('.select').notClick(e)); // will return true if it is not clicked, and false if clicked
});
You need to hide other ul whenever some one clicks on .select div.
Here is a working fiddle: http://jsfiddle.net/0mgbsa0b/1/
$(document).ready(function() {
$('.hide').each(function() {
$(this).hide();
});
$('.select').click(function() {
$('.hide').each(function() {
$(this).hide();
});
var id = '#' + $(this).attr('id');
var sub = id + '_sub';
$(sub).slideToggle();
});
$('body').mouseup(function() {
if($(this).length == 0) {
$(this).hide();
}
});
});
I'm interested in two concerns you raised, so i will be trying to share some ideas on them:
1)So I wonder if jquery support some function such as 'not click'?
personally, to quesiton1
i think there is no jQuery event method called .noclick()
PPL often use addClass & removeClass to log whether an element got clicked and after marking the element with class="active" , using jQuery selector to select ".active" or using jQuery ":not" selector to select elements that are not marked ".active" ( indirectly finding out those unclicked.)
3.You might also need to count in click propagation issues. meaning sometimes you click a children container and triggered click event towards all its parent inside.
fiddle link: `http://jsfiddle.net/hahatey/ctp5jngf/2/`
In the above case , if you clicked child box in red, will by default alert1, alert2 if
you didn't apply a e.stopPropagation() to the click event;
2) I want to hide all the ul when the mouse is click outside. I did some research, and see other people use mouseup or click on body. But I am not quiet sure how it works.
for question 2:
could be many many ways to do it, you can try blur() //lose focus event trigger.
like what you mentioned mouseout, mouseup, add click event listener to outer area all will work for it as long as u can use method in answer1. i see other ppl have posted many answers already as it can be done in many ways.

slide up jumps to top of page

I have some jQuery accordion sliders that slide down and slide up when clicked to reveal content.
Everything works as it should, but if you click on the same link to slide up the same content, it will jump to the top of the page.
I have
return false;
to prevent it jumping to the top of the page when another slider is clicked, so not too sure on what to use so that it doesn't jump to the top of the page to slide up the same content.
I've tied to add
event.preventDefault();
which works, but it breaks in IE9 and IE8.
Here's what I have:
$(document).ready(function() {
$('.slider').click(function() {
$('.internal').slideUp('normal');
if ($(this).next().is(':hidden') == true) {
$(this).addClass('on');
$(this).next().slideDown('normal');
return false;
}
});
$('.internal').hide();
});
HTML Sample:
<div class="slider">Slide Link 1</div>
<div class="internal">
Stuff1
</div>
<div class="slider">Slide Link 2</div>
<div class="internal">
Stuff2
</div>
You are going to want to prevent the default action of the click event. try this:
$(document).ready(function() {
$('.slider').click(function(e) {
e.preventDefault();
$('.internal').slideUp('normal');
if ($(this).next().is(':hidden') == true) {
$(this).addClass('on');
$(this).next().slideDown('normal');
return false;
}
});
$('.internal').hide();
});
the links probably have anchor tags like <a href="#" ...>, try to remove href="#" and if you still want that looks like a link with pointer cursor, use css:
a{
cursor: pointer;
}

Categories