Dropdown menu should not be closed if it is clicked inside - javascript

I put a panel inside a bootstrap dropdown, but when I click inside the panel, the dropdown goes away. I got many solution on stackoverflow but it didn't work for me. How can i prevent panel from disappearing when i click inside.enter code here
<span class="input-group-addon dropdown">
<label class="dropdown-toggle " id="dropdownMenu1" data-toggle="dropdown aria-expanded="false">Advanced Search <span class="caret"></span></label>
<div class="panel panel-default panel-body dropdown-menu " role="menu"" aria-labelledby="dropdownMenu1" style="width:860px; margin-left:-700px">
Panel content
</div>
</span>

Try to do something like this:if you click on the body it checks the parent class,if you click on the dropdown if parent has class .dropdown-parentclass then the dropdown does not close.
$('body').click(function(event){
if ($(event.target).parent('.dropdown-parentclass').size()>0) {
return false;
}
});

try using the code below. It will close the dropdown only when you click out side the container.
$(document).on("mouseup", function (e) {
var container = $(".panel");
if (!container.is(e.target) // if the target of the click isn't the container
&& container.has(e.target).length === 0) // nor a descendant of the container
{
container.hide();
}
else {
}
});

Related

Focus trap in a dialog modal and after exiting, focus on the last element clicked

I have multiple modals with different id's.
<div id="#Modal" tabindex="-1" class= active" style="left: Opx;" role="dialog" >
<div id="#Modal-text' tabindex="0">
<div class="container">
<div class= close-btn">
<a class="closer noprint href=" javascript:void(0) aria-label="Close dialog" tabindex="0"></a>
</div>
</div>
<div class= content">..modal content goes here</div>
<div class="focus-guard" tabindex="0"></div>
</div>
<div id="#Modal-anothertext' tabindex="0"></div>
<div id="#Modal-sample' tabindex="0"></div>
</div>
The jquery function add a focus guard div and add an event listener to it whenever a tab or keyboard navigation, through it, it will go again to the close button:
"use strict"
jquery(document).ready(function ($) {
// Check if modal exists
if ($(" [id+='Modal-']").length {
// Check id's if containstring of 'Modal-' and check if modal has child with #focus-guard
if ($("[id*='Modal-']").find("focus-guard").length === 0) {
console.log("does not exist");
const focusGuard = document.createElement("div");
focusGuard.setAttribute("class", "focus-guard");
focusGuard.setAttribute("tabindex", "0");
// Add focus guard to parent
$("[id*='Modal-']").append(focusGuard);
// The closer button is being added in the DOM upon clicking modal, that's why I used DOMNodeInserted
$(document).bind("DOMNodeInserted", function (e) {
if (e.target.className="container") {
const close = document.querySelector(".closer");
console.log(close);
focusGuard.addEventListener("focus", () => {
close.focus();
});
}
});
}
});
}
Have tried also some possible selectors and isolating a single modal.
Unfortunately, the eventlistener on focus guard div does not trigger and I cannot target speciffically the "closer noprint" class.
I know it's not right to have a selector like an array("[id=Modal-]"*) to refer to the parent element of the modal but since it's multiple, not sure if this will be the right thing to do. Might there be a simple solution for this one.
Also stuck with a function that focuses on the last item clicked after dismissing the modal.

Close bootstrap dropdown only when mouse is clicked outside of dropdown

I have a bootstrap dropdown menu:
<div class="dropdown>
<a class="dropdown-toggle" href="#" id="menu1" data-toggle="dropdown"><img src="#imagePath" class="img-circle dropbtn" alt="Product" style="width:30px;height:30px;" /></a>
<ul class="dropdown-menu" id="productDD" role="menu" aria-labelledby="menu1"></ul>
</div>
Now the ul load the products on page load through ajax call. The issue is when I click any product in the dropdown, the dropdown gets closed. But I want to close dropdown only when mouse is clicked anywhere outside of the ul
Try something like this:
$(document).click(function(e) {
// get the clicked element
$clicked = $(e.currentTarget);
// if the clicked element is not a descendent of the dropdown
if ($clicked.closest('.dropdown').length === 0) {
// close the dropdown
$('.dropdown').removeClass('open');
}
});
In 2021 you do it this way:
$('.dropdown').on({
"shown.bs.dropdown": function() { /* whatever you want to do when it fires */ },
"click": function(e) { // handles click event
console.log(e.target) // just to check which element is on top
if($('.dropdown-menu').is(e.target)) { // if dropdown is clicked
this.closable = false // do not close it
return;
} else {
this.closable=true; // else close it
}
},
"hide.bs.dropdown": function() { return this.closable; } // save state
});
}
Bootstrap has a built-in solution
<a class="dropdown-toggle" href="#" id="menu1" data-toggle="dropdown" data-bs-auto-close="outside"><img ... /></a>
just place this script in your code
<script>
$(document).click(function() {
$(".dropdown").removeClass('open');
});
</script>

Open one drop-down, close another with JavaScript

I am using this script to open a drop down menu and then close it when anything else but the trigger is clicked. Now I am trying to add a second drop down to another area on the page and repeat the script but it is breaking.
For instance, I click button A (Gravatar), and drop down A opens.
However when I add the second script and click button B (category) to open drop down B, down down A stays open.
Also adding the second script breaks the drop down close function of the first script.
Here is the script:
<script>
function openAccount(event) {
event.stopPropagation();
document.getElementById("gravatar").classList.toggle("open");
}
window.onclick = function(event) {
document.getElementById("gravatar").classList.remove("open");
}
</script>
<script>
function openCategory(event) {
event.stopPropagation();
document.getElementById("category").classList.toggle("open");
}
window.onclick = function(event) {
document.getElementById("gravatar").classList.remove("open");
}
</script>
<li class="gravatar">
<a href="#" class="dropbtn" onclick="openAccount(event)">
<img src="<?php echo $gravatar; ?>" alt="" />
<span class="fa fa-icon fa-caret-down"></span>
</a>
<ul class="dropdown" id="gravatar">
<li class="header">
<?php echo $user['email']; ?>
</li>
</ul>
</li>
<div class="category">
Properties<span class="fa fa-icon fa-caret-down"></span>
<div id="category">Test</div>
</div>
Goals:
Multiple drop down menus on different parts of the page.
On click opens drop down.
Click on anywhere else on the page closes the drop down.
On click also closes any previously opened menu.
I'd do something really simple like putting a data* attribute on the element that's clicked on that contains the ID of the element to show or hide, e.g.
// Toggle hidden class on/off
function toggleVis(event) {
// Stop click on element bubbling (to body)
event.stopPropagation();
// Get target element
var el = document.getElementById(this.dataset.id);
// If non-target elements are visible, hide them
hideAll(el);
// Toggle target
el.classList.toggle('hidden');
}
// Hide all, excluding passed element
function hideAll(el) {
Array.from(document.querySelectorAll('ul:not(.hidden)')).forEach(function(node){
if (el != node) node.classList.add('hidden');
});
}
// Attach listeners
window.onload = function() {
// Add to linkLike spans
Array.from(document.querySelectorAll('.linkLike')).forEach(function(node) {
node.addEventListener('click', toggleVis, false);
});
// Add hideAll listener to wndow
window.addEventListener('click', hideAll, false);
// Run hideAll
hideAll();
}
/* style span like link */
.linkLike {
text-decoration: underline;
cursor: pointer;
}
/* class to hide element */
.hidden {
visibility: hidden;
}
<ul id="a"><li>A</ul>
<ul id="b"><li>B</ul>
<ul id="c"><li>C</ul>
<ul id="d"><li>D</ul>
<div><span class="linkLike" data-id="a">Toggle A</span></div>
<div><span class="linkLike" data-id="b">Toggle B</span></div>
<div><span class="linkLike" data-id="c">Toggle C</span></div>
<div><span class="linkLike" data-id="d">Toggle D</span></div>
Of course there are other ways to do the association, but ID is simple, explicit and doesn't depend on document layout or formatting.

Closing dropdown menu on parent's click [duplicate]

I want to have my menu closed when the user clicks outside the menu, not only outside the navbar element. Because I have more collapses in my menu, this solution did not work for me: How to close an open collapsed navbar when clicking outside of the navbar element in Bootstrap 3?
The menu disapeares when I click outside the menu, but when I click on the link with a dropdown, the whole menu collapses.
<div class="collapse navbar-collapse nav-mobile" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="list-group panel">
Webshop
<ul class="collapse" id="submenu-1">
Industriƫle verpakkingen
Promotionele verpakkingen
Gelamineerde verpakkingen
Enveloppen &verzend verpakkingen
Medische verpakkingen
Co-packing
</ul>
</li>
</ul>
You can use this to collapse if not clicking a link: fiddle
$(document).click(function(e) {
if (!$(e.target).is('a')) {
$('.collapse').collapse('hide');
}
});
another alternative, you can add code below :
<script>
$(document).ready(function(){
$(".list-group ").hover(
function() {
$('.collapse', this).stop( true, true ).slideDown("fast");
$(this).toggleClass('open');
},
function() {
$('.collapse', this).stop( true, true ).slideUp("fast");
$(this).toggleClass('open');
}
);
});
</script>
another example : dtc-eng
Here is my take on this:
$(document).on('click', function(event){
var $clickedOn = $(event.target),
$collapsableItems = $('.collapse'),
isToggleButton = ($clickedOn.closest('.navbar-toggle').length == 1),
isLink = ($clickedOn.closest('a').length == 1),
isOutsideNavbar = ($clickedOn.parents('.navbar').length == 0);
if( (!isToggleButton && isLink) || isOutsideNavbar ) {
$collapsableItems.each(function(){
$(this).collapse('hide');
});
}
});
This solution handles:
single page website/applications (and will work on multi-pages too).
clicks on:
.navbar-toggle elements (could be <buttons> or <a>, and it handles clicks on potential inner elements like <span> or <strong> or whatever).
on simple <a> elements (again, it handles clicks on inner elements).
just outside some particular parent (ie. .navbar).
multiple collapsable (.collapse) elements that might be open (indistinct to where they are placed in the DOM).
Not enough for you? No problem. You can customize most of the selectors passed to jQuery (document, .collapse, .navbar, etc) to suit your needs or even add more conditions.

Toggle menu when clicked outside div while button is in the header

I'm trying to hide my offcanvas menu while i'm clicking outside the div where the menu is in.
It is a menu which only appears while the bootstrap xs class will be loaded.
My button is inside my header and the menu is a page on his own.
this is how my button looks like:
<p class="pull-left visible-xs">
<?php if($data['title'] == 'Producten' || $data['title'] == 'Winkeltjes' || $data['title'] == 'Home'){?>
<button type="button" onClick="document.getElementById('sidebar').scrollIntoView();"
class="btn btn-primary btn-default" data-toggle="offcanvas">
Filters
</button>
<?php }
</p>
I've found a couple ways on stackoverflow and tried those, but these all didnt workout with my offcanvas div. the div that should be opened has the following class and id:
<div class="col-xs-6 col-sm-3 sidebar-offcanvas" id="sidebar">
I don't have any functions anymore at the moment.
hopefully I've give you guys enough information and I'm looking forward to any reply.
Try This Code...
function hideWhenClickedElseWhere(container, callback){
$(document).mouseup(function (e){
if (!container.is(e.target) && // if the target of the click isn't the container...
container.has(e.target).length === 0) // ... nor a descendant of the container
{
callback();
}
});
}
The first argument is the nodes in which you don't want to close the menu when clicked.
The Second argument is the callback - what should we do if clicked elsewhere.
hideWhenClickedElseWhere( $(".buttonClass, .menuClass") ), function(){
$(".menuClass").hide();
$(".buttonClass").removeClass("acctive");
});
Use this code..
$(document).click(function (e) {
if (
!$(e.target).hasClass('menuClass') &&
!$(e.target).hasClass('') &&
$(e.target).parents('.buttonClass').length == 0 &&
$(e.target).parents('.menuClass').length == 0
) {
$(".menuClass").hide();
$(".buttonClass").removeClass("acctive");
}
});

Categories

Resources