How to close navbar when clicking outside of it - javascript

How can I edit my code so that the navbar closes when clicked outside of it but remain open if something inside of it is clicked?
$(document).ready(function() {
$('.nav-btn').on('click', function() {
$('.nav-btn').removeClass('active');
$(this).parent().find('.sub-menu').slideToggle();
$(this).toggleClass('active');
});
});

$(document).ready(function () {
$('.nav-btn').on('click', function (e) {
// Stop Document to be clicked when clicked in nav.
e.stopPropagation()
$('.nav-btn').removeClass('active');
var subMenu = $(this).parent().find('.sub-menu')
if (!$(".sub-menu").is(":visible")) {
$(this).parent().find('.sub-menu').slideToggle();
}
$(this).toggleClass('active');
});
// Toggle Sub Menu and remove active when Any vacant place is clicked
$(this).on('click', function (event) {
$('.nav-btn').removeClass('active');
$('.nav-btn').parent().find('.sub-menu').slideToggle();
});
// Prevent View close when Sub Items is clicked
$('.sub-menu').on('click', function (e) {
e.stopPropagation()
})
});
Hi, You just need to prevent the document click when clicked on the nav item and handle some additional things as done in the above code.
You can see Plunker example here also.

$(document).on('click', function (event) {
if ($(event.target).closest('.main-nav').length === 0) {
// Close button code
}
});

Another possible way is by wrapping all the content inside another div (except the header & navbar) and using the onclick tag:
<div onclick="hideNavbar()">
all your content goes here
</div>
function hideNavbar() {
$('.navbar-collapse').collapse('hide');
// getting the navbar div with jQuery
// and calling the function 'hide' of the Bootstrap class 'collapse'
}

Related

jQuery slidetoggle keeps toggling after window resize/ready combined

I want to add slidetoggle only when screen size is less than 768px. I also want this to work when user for some reason would resize the window manually.
I have come across a bug with jQuery where my dropdown menu will keep toggling after I resize the window. I've looked up this issue and tried adding return false; to click function and adding position: relative; overflow:hidden; to toggleable div(these should be a workaround according to some forums). No luck there. What causes this bug. I will include the whole function with the click function
//Call function on ready and window resize
$(document).ready(navigationMobile);
$(window).on('resize', navigationMobile);
function navigationMobile() {
const windowWidth = $(window).width();
if (windowWidth < 768) {
//Remove href from main link and add it as a "all" link in menu
$(".js-second-title").each(function () {
const currentHref = $(this).attr('href');
$(this).removeAttr('href');
if ($(this).siblings('ul').find('.js-all-link').length === 0) {
$(this).siblings('ul').prepend(`<li><a class="js-all-link" href="${currentHref}">All</a></li>`);
}
});
//When clicked on main link open menu
$(".js-second-title").click(function () {
$(this).siblings('.js-menu').slideToggle();
$(this).toggleClass('js-open');
});
} else {
//Add href back to main link
$('.js-second-title').each(function () {
if ($(this).attr('href') === undefined) {
const allHref = $(this).siblings('ul').find('.js-all-link').attr('href');
$(this).attr('href', `${allHref}`);
$(this).siblings('ul').find('.js-all-link').remove();
}
});
}
}
Cheers!
I don't exactly know what is causing this bug. But I came up with this workaround.
//Remove href from main link and add it as a "all" link in menu
$(".js-second-title").each(function () {
$(this).addClass('js-closed');
const currentHref = $(this).attr('href');
$(this).removeAttr('href');
if ($(this).siblings('ul').find('.js-all-link').length === 0) {
$(this).siblings('ul').prepend(`<li><a class="js-all-link" href="${currentHref}">All</a></li>`);
}
});
//When clicked on main link open menu
$(document).on("click", '.js-second-title.js-closed', function (e) {
$(this).removeClass('js-closed');
$(this).siblings('.js-menu').slideDown();
$(this).addClass('js-open');
});
$(document).on("click", '.js-second-title.js-open', function (e) {
$(this).siblings('.js-menu').slideUp();
$(this).removeClass('js-open');
$(this).addClass('js-closed');
});
So here I am basically extening SlideToggle function. Before I call slide functions on click I give each js-second-title classes an extra class .js-closed so the browser is aware that the menu is closed. After that I call slideDown function when I click on closed menu title and slideUp when I click on open menu title.
I do not think that this is the best or most sematic solution so I would like to keep this topic open.

Logic to hide opened sub menu on click elsewhere?

Suppose user goes to a ecommerce site and clicks on products, there is a submenu which drops down. What logic to write to ensure that when user clicks on any other blank space(or elements) that submenu is hidden back?
Check this js fiddle:-
http://jsfiddle.net/H3Vnw/3/
Here is the java script code:-
$(document).mouseup(function (e)
{
var container = $('.dropdown-menu');
if (container.has(e.target).length === 0)
{
container.hide();
}
});
$('.comment').click(function(){
$('.dropdown-menu').css({'display': 'block'});
});
If we click on the comment we can get drop menu if we click else where the drop menu will be hidden!
Hope this helps!
Wild guess: something that listens to anything but the submenu click, and closes it.
// assumption: submenu has open() and close() functions
submenu.open();
var listener = document.addEventListener('click', function(e){
// TODO: how to check if click is on submenu?
if (e.target != submenu) {
submenu.close();
document.removeEventListener('click', listener);
}
});

hide div on background click

I have a series of divs that reveal on link click. When revealed i'm trying to make them close on background click while maintaining their ability to have the different divs replace each other when different links are clicked.
JS fiddle here: http://jsfiddle.net/t593pyg9/3/
$(document).ready(function () {
$('.toggle').hide();
$('a.togglelink').on('click', function (e) {
e.preventDefault();
var elem = $(this).next('.toggle')
$('.toggle').not(elem).hide();
elem.toggle();
});
});
Listen to clicks on the entire document, to prevent this from closing the "popup" after clicking it's link due to event propagation add a return false; to the show click listener.
$('.toggle').hide();
$('a.togglelink').on('click', function (e) {
e.preventDefault();
var elem = $(this).next('.toggle')
$('.toggle').not(elem).hide();
elem.toggle();
return false;
});
$(document).on('click',function(e){
$('.toggle').hide();
});
Fiddle
Update
If you want to prevent the popup from hiding on clicking on it add this:
$('.toggle').on('click', function (e) {
return false;
});
New Fiddle

dropdown menu , remove class if its open

I'm trying to create dropdown menu, I'm doing it in this way, by default on dropdown menu I'm doing
.dropdown {
display: none;
}
then im creating event on click and based on that context im toggling class
.active { display block; }
now I cant figure out how can I remove that .active class when I click on other button or in document, I don't want to keep dropdown active class if user click on other button demo
http://jsfiddle.net/pnLkpxkb/8/
$(function () {
// The user clicks anywhere in the document
$(document).click(function (e) {
// If a dropdown has a class active AND if the dropdown or the link is not the target of the click
if ($("ul.dropdown").hasClass("active") && !$("ul.dropdown, .btn > a").is(e.target)) {
// Remove class active
$("ul.dropdown.active").removeClass("active");
}
});
var dropdown = $(".btn > a");
// The user clicks on a toggle link (One or Two)
dropdown.on("click", function () {
// Remove the active class from the active element
$("ul.dropdown.active").removeClass("active");
// Add class to the relevant sub menu
$(this).siblings("ul.dropdown").addClass("active");
});
}());
Updated after comment
You don't need to put "" with this keyword. Your code line should be:
$(this).siblings("ul.dropdown").toggleClass("active");
Complete Code
$(function () {
var dropdown = $(".btn").find("a");
dropdown.on("click", function() {
$("ul.dropdown.active").removeClass("active"); //added new line
$(this).siblings("ul.dropdown").toggleClass("active");
});
}());
Updated Code with Remove Class
toggleClass don't work as you want. For your case i suggest to go this way:
$(function () {
var dropdown = $(".btn").find("a");
dropdown.on("click", function() {
$("ul.dropdown").removeClass("active");//add this to remove class from all ul .dropdowns
$(this).siblings("ul.dropdown").addClass("active");//Add class to your ul dropdown. Here you can use toggleClass too
});
}());
fiddle
$(function () {
$(document).on('click', function () {
$("ul.dropdown").removeClass('active');
});
$(".btn a").on("click", function (e) {
e.stopPropagation();
$("ul.dropdown").removeClass('active');
$(this).siblings("ul.dropdown").addClass("active");
});
});
JSFiddle Demo.

Prevent Bootstrap dropdown from closing on clicks [duplicate]

This question already has answers here:
How do I prevent my dropdown from closing when clicking inside it?
(3 answers)
Closed 4 years ago.
My menu uses Bootstrap 3 and I can't prevent dropdown from closing on click. How can I do it?
JSFiddle
// Add open class if active
$('.sidebar-nav').find('li.dropdown.active').addClass('open');
// Open submenu if active
$('.sidebar-nav').find('li.dropdown.open ul').css("display","block");
// Change active menu
$(".sidebar-nav > li").click(function(){
$(".sidebar-nav > li").removeClass("active");
$(this).addClass("active");
});
// Add open animation
$('.dropdown').on('show.bs.dropdown', function(e){
$(this).find('.dropdown-menu').first().stop(true, true).slideDown();
});
// Add close animation
$('.dropdown').on('hide.bs.dropdown', function(e){
$(this).find('.dropdown-menu').first().stop(true, true).slideUp();
});
You need to stop event from bubbling up the DOM tree:
$('.dropdown-menu').click(function(e) {
e.stopPropagation();
});
event.stopPropagation prevents event from reaching the node where it's eventually handled by Bootstrap hiding menu.
Demo: http://jsfiddle.net/wkc5md23/3/
I believe this should be a more proper solution, as stopping propagation on the click event might sometimes cause issues later on in development. You may read more into it here: http://css-tricks.com/dangers-stopping-event-propagation/ Instead this solution stops propagation on the Bootstrap hide (hide.bs.dropdown) event, which stops it from continuing on to the hidden (hidden.bs.dropdown) event.
The following code has been taken and edited by myself to make it work on all Bootstrap dropdowns, as it has originally been taken from here: Preventing bootstrap dropdown from closing on click I personally prefer this way also because it uses the built in Bootstrap dropdown events, which could be found here: https://getbootstrap.com/docs/3.4/javascript/#dropdowns-events.
$(function () {
$('.dropdown').on({
'click': function (event) {
if ($(event.target).closest('.dropdown-toggle').length) {
$(this).data('closable', true);
} else {
$(this).data('closable', false);
}
},
'hide.bs.dropdown': function (event) {
hide = $(this).data('closable');
$(this).data('closable', true);
return hide;
}
});
});
You can disable the dropdown functionality temporarily. This is a workaround.
Example with input field inside the drop-down "menu":
//for dropdown field not closing when clicking on inputfield
$(document).on('focus', 'input', function (e) {
// this attribute can be anything except "dropdown", you can leave it blank
$('#yourDropdownID').attr('data-toggle', 'off');
});
//for dropdown field back to normal when not on inputfield
$(document).on('focusout', 'input', function (e) {
$('#yourDropdownID').attr('data-toggle', 'dropdown');
});
This can be used on anything that is clickable and you can define individually what items clicked can close or not close the drop-down menu.
Not close in click out side menu
$(function() {
var closeble = false;
$('body').on('click', function (e) {
if (!$(event.target).is('a.dropdown-toggle')) {
closeble = false;
}
});
$('.dropdown').on({
'click': function (event) {
if ($(event.target).closest('.dropdown-toggle').length) {
closeble = true;
} else {
closeble = false;
}
},
'hide.bs.dropdown': function () {
return closeble;
}
});
});

Categories

Resources