Close list of Dropdown Menu - javascript

I have this dropdown menu:
document.addEventListener("DOMContentLoaded", function(event) {
allNameMuseums().forEach(function(item) { // ITERAZIONE
document.getElementById("myDropdown").innerHTML += '<a onclick="updateData(this)">' + item + '</a>';
})
});
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
function filterFunction() {
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
div = document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
for (i = 0; i < a.length; i++) {
if (a[i].innerHTML.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
} else {
a[i].style.display = "none";
}
}
}
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Museo1</button>
<div id="myDropdown" class="dropdown-content">
<input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
</div>
</div>
I want that when I click an item in the list of dropdown menu, the list closes automatically.

What are you need is remove the "show" class from the element.
Example:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.dropbtn { background-color: #4CAF50; color: white; padding: 16px; font-size: 16px; border: none; cursor: pointer; }
.dropbtn:hover, .dropbtn:focus { background-color: #3e8e41; }
#myInput { border-box: box-sizing; background-image: url('searchicon.png'); background-position: 14px 12px; background-repeat: no-repeat; font-size: 16px; padding: 14px 20px 12px 45px; border: none; border-bottom: 1px solid #ddd; }
#myInput:focus { outline: 3px solid #ddd; }
.dropdown { position: relative; display: inline-block; }
.dropdown-content { display: none; position: absolute; background-color: #f6f6f6; min-width: 230px; overflow: auto; border: 1px solid #ddd; z-index: 1; }
.dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; }
.dropdown a:hover { background-color: #ddd; }
.show { display: block; }
</style>
</head>
<body>
<h2>Search/Filter Dropdown</h2>
<p>Click on the button to open the dropdown menu [...]</p>
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
Item1
Item2
</div>
</div>
<script>
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
function filterFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
div = document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
for (i = 0; i < a.length; i++) {
if (a[i].innerHTML.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
} else {
a[i].style.display = "none";
}
}
}
function select() {
//Your item selection logic here...
myFunction();
}
</script>
</body>
</html>

Follow the example in W3C School here:
What you are missing is, closing the dropdown when the click is outside the button:
// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
Try yourself
And notice, this example doesn't have your search bar, so in this function, you'll have to check with the search bar as well to exclude it from closing the drop down.

Related

Searchable drop down

I have a list of items in a drop down which is filterable using a search within the dropdown.
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Please select</button>
<div id="myDropdown" class="dropdown-content">
<input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
Abyssinian
American Bobtail
Amercian Curl
</div>
</div>
And the js...
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
function filterFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
div = document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
for (i = 0; i < a.length; i++) {
txtValue = a[i].textContent || a[i].innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
} else {
a[i].style.display = "none";
}
}
}
https://codepen.io/RSA_James/pen/LYZqYym
What I'm after is a way of showing a message if a user starts searching for something and there's no matches.
Any help appreciated! Thanks
ES6 shrinks the code a bit:
function filterFunction(sText) {
[...document.querySelectorAll('#myDropdown a')].forEach(elA => elA.classList.toggle('hide', !new RegExp(sText, 'gi').test(elA.textContent)));
document.querySelector('#myDropdown span.err').classList.toggle('hide', document.querySelectorAll('#myDropdown a:not(.hide)').length);
}
.hide { display: none; } .err { color: red; }
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Please select</button>
<div id="myDropdown" class="dropdown-content">
<input type="text" placeholder="Search.." id="myInput" oninput="filterFunction(this.value)">
Abyssinian
American Bobtail
Amercian Curl
<span class="err hide">Nothing found</span>
</div>
</div>
Have a look here, added some new code and created a new element when there is no found result.
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
function filterFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
div = document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
var empty = document.createElement("a");
empty.classList.add("empty");
empty.innerHTML="No Reault Found...";
var emptyVisiable= true;
for (i = 0; i < a.length; i++) {
txtValue = a[i].textContent || a[i].innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
emptyVisiable = false;
} else {
a[i].style.display = "none";
}
}
if (emptyVisiable)
div.appendChild(empty);
else {
empty= div.querySelector(".empty")
if (empty!== null)
empty.remove();
}
}
.dropbtn {
background-color: #e3e3e3;
background-image: url('https://image.flaticon.com/icons/png/512/25/25243.png');
background-position: 270px center;
background-repeat: no-repeat;
background-size: 5%;
color: #333 ;
border: 1px solid red;
border-radius: 5px;
min-width: 300px;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
text-align: left;
}
.dropbtn:hover, .dropbtn:focus {
background-color: #d3d3d3;
}
#myInput {
box-sizing: border-box;
background-image: url('https://www.w3schools.com/howto/searchicon.png');
background-position: 14px 12px;
background-repeat: no-repeat;
font-size: 16px;
padding: 14px 20px 12px 45px;
border: none;
border-bottom: 1px solid #ddd;
width: 100%;
}
#myInput:focus {outline: 3px solid #ddd;}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f6f6f6;
min-width: 230px;
width: 100%;
max-height: 260px;
overflow: auto;
border: 1px solid #ddd;
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {background-color: #ddd;}
.show {display: block;}
<h2>Search/Filter Dropdown</h2>
<p>Click on the button to open the dropdown menu, and use the input field to search for a specific dropdown link.</p>
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Please select</button>
<div id="myDropdown" class="dropdown-content">
<input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
Abyssinian
American Bobtail
Amercian Curl
American Longhair
American Shorthair
American Wirehair
Angora
Asian
Asian Blue
Balinese
Bengal
Bengal Tiger
Bicolour
Bicolour Longhair
British Bicolour Shorthair
Birman
Black
Black and White
Black and White Longhair
Black and White Shorthair
Black Longhair
Black Shorthair British Black
</div>
</div>
you can accomplish this by adding a p tag for the error in the html and a counter that increments each time no res is found in the loop of your filter function followed by an if at the end that checks to see if the counter === the lengths of links
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
function filterFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
div = document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
let count = 0;
for (i = 0; i < a.length; i++) {
txtValue = a[i].textContent || a[i].innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
} else {
count++;
a[i].style.display = "none";
}
}
if(count == a.length )
displayNoResults(filter);
}
function displayNoResults(searchTxt) {
let noResFound = document.getElementById("noResFound");
noResFound.style.display = "block"
noResFound.innerHTML = `No results for "${searchTxt}" were found`
}
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Please select</button>
<div id="myDropdown" class="dropdown-content">
<input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
<p id="noResFound"></p>
Abyssinian
American Bobtail
Amercian Curl
</div>
</div>

Search / Filter Dropdown: Change value variable when click

I just implemented a Search / Filter Dropdown, following this guide: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_js_dropdown_filter.
<h2>Search/Filter Dropdown</h2>
<p>Click on the button to open the dropdown menu, and use the input field to search for a specific dropdown link.</p>
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
</div>
</div>
This Search / Filter Dropdown takes the array of the allNameMuseums () method as values, ie ["ACQUARIUM", "Museo2", "Museo3"].
document.addEventListener("DOMContentLoaded", function(event) {
allNameMuseums().forEach(function(item) {
document.getElementById("myDropdown").innerHTML += '' + item + '';
})
});
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
function filterFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
div = document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
for (i = 0; i < a.length; i++) {
if (a[i].innerHTML.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
} else {
a[i].style.display = "none";
}
}
}
function allNameMuseums() {
return ["ACQUARIO", "Museo2", "Museo3"];
}
I have two asynchronous methods, specificoMuseo(name) and allMuseums (), and a variable var data = proof; that takes the result of the allMuseums() method.
specificoMuseo(name).then(proof2 => {
allMuseums().then(proof => {
var data = proof;
});
});
I want that when I click on ACQUARIO of Search / Filter Dropdown the variable 'data' takes as input the result of specificoMuseo ("ACQUARIO").
You need to similar logic as below,
var name; //globle variable so you can access in your method
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
function fnclick(obj) {
name = obj.innerHTML;
alert(name);
console.log(name);
}
function filterFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
div = document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
for (i = 0; i < a.length; i++) {
if (a[i].innerHTML.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
} else {
a[i].style.display = "none";
}
}
}
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropbtn:hover, .dropbtn:focus {
background-color: #3e8e41;
}
#myInput {
border-box: box-sizing;
background-image: url('searchicon.png');
background-position: 14px 12px;
background-repeat: no-repeat;
font-size: 16px;
padding: 14px 20px 12px 45px;
border: none;
border-bottom: 1px solid #ddd;
}
#myInput:focus {outline: 3px solid #ddd;}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f6f6f6;
min-width: 230px;
overflow: auto;
border: 1px solid #ddd;
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {background-color: #ddd;}
.show {display: block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Search/Filter Dropdown</h2>
<p>Click on the button to open the dropdown menu, and use the input field to search for a specific dropdown link.</p>
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
About
Base
Blog
</div>
</div>

Closing dropdown by clicking outside in Javascript (tutorial clarification)

I have attempted to implement the method of opening and closing a drop-down using Javascript via this tutorial on w3schools.com. While the function to "show" the drop-down works, the one to close it does not. Furthermore, there is no explanation alongside this code to explain why it should work, making it difficult to debug.
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
My questions are, therefore,
1) whether the code in the tutorial should work for the purpose of closing the drop-down. (ANSWERED)
2) Could someone please clarify how/why this should work, for the sake of clarity for myself and future newbies who make come across the same tutorial and issue? (UNANSWERED)
Edit (MY ATTEMPT):
HTML:
<div class="sharedown">
<p onclick="shareVis()" class="sharebtn">&nbsp Share</p>
<div id="mySharedown" class="sharedown-content">
Self
<p>User</p><input type="text" name="user-name" placeholder="Share to">
Community
</div>
</div>
JS:
function shareVis() {
document.getElementById("mySharedown").className = "show";
}
window.onclick = function(event) {
if (!event.target.matches('sharebtn')) {
var sharedowns = document.getElementsByClassName("sharedown-content");
var i;
for (i = 0; i < sharedowns.length; i++) {
var openSharedown = sharedowns[i];
if (openSharedown.classList.contains('show')) {
openSharedown.classList.remove('show');
}
}
}
}
CSS:
/* Share dropdown menu */
p.sharebtn {
color: darkgrey;
font-family:calibri;
padding: 0px;
margin: 0px;
font-size: 12;
border: none;
cursor: pointer;
display: inline;
}
/* Dropdown button on hover & focus */
p.sharebtn:hover, p.sharebtn:focus {
color: grey;
}
/* The container <div> - needed to position the dropdown content */
.sharedown {
position: relative;
display: inline-block;
}
/* Dropdown Content (Hidden by Default) */
.sharedown-content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 100px;
box-shadow: 0 2px 4px 1px #C4E3F5;
z-index:1; /* place dropdown infront of everything else*/
}
.sharedown-content a {
color: black;
padding: 5px 5px;
text-decoration: none;
display: block;
}
/* Show the dropdown menu (use JS to add this class to the .dropdown-
content container when the user clicks on the dropdown button) */
.show {display: block;
position: absolute;
background-color: #f1f1f1;
min-width: 100px;
box-shadow: 0 2px 4px 1px #C4E3F5;
opacity: 1;
z-index:1;}
The issue lies in shareVis function. Here
document.getElementById("mySharedown").className = "show";
you are replacing #mySharedown class name to show. Then in window.onclick
var sharedowns = document.getElementsByClassName("sharedown-content");
you are not getting any sharedowns as you already replaced the class name to show.
You can either add show class into classList
document.getElementById("mySharedown").classList.add("show");
or replace the class name with sharedown-content show
document.getElementById("mySharedown").className = "sharedown-content show";
Working solution below:
function shareVis() {
//document.getElementById("mySharedown").className = "sharedown-content show";
document.getElementById("mySharedown").classList.add("show");
}
window.onclick = function(event) {
if (!event.target.matches('.sharebtn')) {
var sharedowns = document.getElementsByClassName("sharedown-content");
var i;
for (i = 0; i < sharedowns.length; i++) {
var openSharedown = sharedowns[i];
if (openSharedown.classList.contains('show')) {
openSharedown.classList.remove('show');
}
}
}
}
document.getElementById("mySharedown").addEventListener('click',function(event){
event.stopPropagation();
});
#mySharedown{
display: none;
border: 1px solid black;
}
#mySharedown.show {
display: block;
}
<div class="sharedown">
<p onclick="shareVis()" class="sharebtn">&nbsp Share</p>
<div id="mySharedown" class="sharedown-content">
Self
<p>User</p><input type="text" name="user-name" placeholder="Share to">
Community
</div>
</div>
Update
To prevent the second click within #mySharedown from hiding #mySharedown, you should add another click event for #mySharedown and prevent it from bubbling up, like this
document.getElementById("mySharedown").addEventListener('click',function(event){
event.stopPropagation();
});
Updates are included in the working solution
Update 2022
Vanilla Javascript now contains a mehtod called Node.closest(Node) to check if the event matches the node in the upper hierarchy. below is an example to open the dropdown menu on click and hide it again on click and if clicking outside the document will also hide the dropdown menu.
const list = document.querySelector('.list')
const btn = document.querySelector('.btn')
btn.addEventListener('click', (e)=> {
list.classList.toggle('hidden')
e.stopPropagation()
})
document.addEventListener('click', (e)=> {
if(e.target.closest('.list')) return
list.classList.add('hidden')
})
.hidden {
display:none
}
ul {
background-color: blue;
}
<button class="btn">open</button>
<ul class="list hidden">
<li class="item1">Item 1</li>
<li class="item2">Item 2</li>
<li class="item3">Item 3</li>
</ul>
Here I leave another "short" example that I implemented to my own code, but is easy to understand.
.tw-hidden is a class "display: none"
window.onclick = function(event) {
let customDropdownsEl = document.querySelectorAll(".custom-dropdown");
let liContainerEl = event.target.querySelector(".custom-dropdown");
customDropdownsEl.forEach(el => el.parentNode !== event.target && !el.classList.contains("tw-hidden") && el.classList.add("tw-hidden"));
event.target.matches('.custom-dropdown-container') && liContainerEl.classList.toggle("tw-hidden");
}
The example is fully functional and should work. Copy the following code below:
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
.dropbtn {
background-color: #3498DB;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropbtn:hover, .dropbtn:focus {
background-color: #2980B9;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
overflow: auto;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {background-color: #ddd}
.show {display:block;}
<h2>Clickable Dropdown</h2>
<p>Click on the button to open the dropdown menu.</p>
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
Home
About
Contact
</div>
</div>

limit the drop down link display in html

I created an dropdown list, it have more than 25 link dropdown to display , So
i need to show only 3 from the dopdown list (not to disable others) , and perform the search option to all . please help me to find a solution
<div class="dropdown">
<input onclick="myFunction()" class="dropbtn" id="myInput"
onkeyup="filterFunction()">
<div id="myDropdown" class="dropdown-content">
About
Base
Blog
Contact
Custom
Support
Tools
</div>
</div>
<script>
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
function filterFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
div = document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
for (i = 0; i < a.length; i++) {
if (a[i].innerHTML.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
} else {
a[i].style.display = "none";
}
}
}
</script>
css file
.dropbtn {
background-color:#E8E0DE;
color: white;
padding: 6px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropbtn:hover, .dropbtn:focus {
background-color:#FAF6F5;
}
#myInput {
border-box: box-sizing;
position:relative;
top: 10px;
color:black;
background-position: 1px 2px;
background-repeat: no-repeat;
font-size: 16px;
padding: 5px 350px 10px 15px;
border: none;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f6f6f6;
min-width: 230px;
overflow: auto;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {background-color: #ddd}
.show {display:block;}
</style>
You just want to return at most 3 at all times you'll want to add a function similar to your filter function, but after it finds 3 items that have a display style set to "" set the rest to "none".
function limitVisibility() {
let div, a, i;
div = document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
for (i = 0; i < a.length; i++) {
let counter = 0;
if (counter < 3 && a[i].style.display === "" ) {
counter += 1;
} else {
a[i].style.display = "none";
}
}
}
and include it in your onClick and onkeyup:
try this:
function filterFunction() {
var input, value, filter, ul, li, a, i, limit, init;
input = document.getElementById("myInput");
value = document.getElementById("myInput").value; // ADD INPUT VALUE
filter = input.value.toUpperCase();
div = document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
init = 0;
limit = 3;
for (i = 0; i < a.length; i++) {
if( (a[i].innerHTML.toUpperCase().indexOf(filter) > -1) ) {
if (init < limit) // LIMIT to FIRST 3 results
{
a[i].style.display = "";
}
else if(value =='') // Case when Input is Empty
{
a[i].style.display = "";
}
else
{
a[i].style.display = "none";
}
init++; // counting results
}
else
{
a[i].style.display = "none";
}
}
}

why my code don't working in IE11

In Internet Explorer 11, when I click outside the button, the submenu does not hide, but it works fine in Google Chrome and Firefox.
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onclick_dropdown
<!DOCTYPE html>
<html>
<head>
<style>
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropbtn:hover, .dropbtn:focus {
background-color: #3e8e41;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
overflow: auto;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {background-color: #f1f1f1}
.show {display:block;}
</style>
</head>
<body>
<h2>Clickable Dropdown</h2>
<p>Click on the button to open the dropdown menu.</p>
<div class="dropdown">
<button id="myBtn" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
Home
About
Contact
</div>
</div>
<script>
// Get the button, and when the user clicks on it, execute myFunction
document.getElementById("myBtn").onclick = function() {myFunction()};
// myFunction toggles between adding and removing the show class, which is used to hide and show the dropdown content
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
</script>
</body>
</html>
event.target.matches doesn't exist in Internet Explorer. The Browser Compatibility table in Element.matches() says that starting with IE 9 this method is available, but with the non-standard name msMatchesSelector.
So try:
window.onclick = function(event) {
matches = event.target.matches ? event.target.matches('.dropbtn') : event.target.msMatchesSelector('.dropbtn');
if (!matches) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
You can use the jQuery library to get cross-browser compatible code which works in IE as well.
In your case, replace your <script> with the following code:
<script src="//code.jquery.com/jquery-1.12.3.min.js"></script>
<script>
$(function(){
$(document).click(function(event){
if(!$(event.target).is('#myBtn')
&& !$(event.target).is('#myDropdown a')) {
$('#myDropdown').hide();
}
if($(event.target).is('#myBtn')) {
$('#myDropdown').toggle();
}
});
});
</script>

Categories

Resources