Can I put more then 1 of these on a page - javascript

Is there a way to have more then one of these codes on a page. I tried adding 4 and renamed them but still didn't work only the original one still worked. Did i do something wrong or can only 1 work per page. Any help in solving this would be greatly appreciated. Thanks and have a great evening.
/* 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 {
cursor: pointer;
font-size: 16px;
}
.dropbtn a {
color: black;
display: block;
padding: 12px 16px;
text-decoration: none;
}
.dropdown {
margin-left: 5%;
margin-top: 25px;
position: relative;
}
.dropdown-content {
background: rgba(34, 34, 34, .25);
border: 1px solid rgba(34, 34, 34, .50);
display: none;
height: 100x;
padding: 10px 10px 10px 15px;
position: absolute;
width: 525px
}
.show {
display: table
}
<a onclick="myFunction()" class="dropbtn" style="float:right;">Search Amazon</a>
<div class="dropdown">
<div id="myDropdown" class="dropdown-content">
<script type="text/javascript">
amzn_assoc_ad_type = "responsive_search_widget";
amzn_assoc_tracking_id = "capebretons0b-20";
amzn_assoc_marketplace = "amazon";
amzn_assoc_region = "CA";
amzn_assoc_placement = "";
amzn_assoc_search_type = "search_box";
amzn_assoc_width = "auto";
amzn_assoc_height = "auto";
amzn_assoc_default_search_category = "";
amzn_assoc_theme = "light";
amzn_assoc_bg_color = "FFFFFF";
</script>
<script src="//z-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&Operation=GetScript&ID=OneJS&WS=1&Marketplace=CA"></script>
</div>
</div>

Related

Why page reloaded after the table is created by JavaScript

There is a dropdown list inside <div> element.
When an item in the dropdown list is clicked, a table should be created.
However, it is found that when the table is created, the page seems refreshed.
How to keep the result ?
<style>
#map {
margin: 10px 10px;
width: 560px;
height: 560px;
border: 1px solid #000000;
}
#dropdown_1 {
margin: 10px 10px;
position: absolute;
top: 0;
left: 600px;
width: 50px;
height: 10px;
/*border: 1px solid #000000;*/
}
/* Dropdown Button */
.dropbtn {
background-color: #3498DB;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
/* Dropdown button on hover & focus */
.dropbtn:hover, .dropbtn:focus {
background-color: #2980B9;
}
/* The container <div> - needed to position the dropdown content */
.dropdown {
position: relative;
display: inline-block;
}
/* Dropdown Content (Hidden by Default) */
.dropdown-content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
/* Links inside the dropdown */
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
/* Change color of dropdown links on hover */
.dropdown-content a:hover {background-color: #ddd}
/* 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;}
</style>
<div id = "dropdown_1" class="dropdown">
<button onclick="dropdown_toggle()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
</div>
</div>
<script src="myscripts.js">
</script>
<script>
// document.addEventListener('keypress', logKey);
set_drop_down_list();
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function dropdown_toggle() {
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');
// console.log('hit-hit');
// creat_traffic_table();
}
}
}
}
</script>
In myscript.js :
function set_drop_down_list(){
var c = document.getElementById("mycanvas");
var ctx = c.getContext("2d");
var img = new Image();
img.src = './pic/mps.png';
img.onload = () => {ctx.drawImage(img, 0, 0);};
var select = document.getElementById("myDropdown");
var options = ["Ma Wan", "Kap Shui Mun", "North Fairway", "Ha Pang", "Fairway Junction"];
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("a");
el.textContent = opt;
el.value = opt;
el.setAttribute("href", "");
el.onclick = function(event) {
creat_traffic_table();
}
select.appendChild(el);
}
}
function create_traffic_table(){
var myArray = [
{'name':'Michael', 'age':'30', 'birthdate':'11/10/1989'},
{'name':'Mila', 'age':'32', 'birthdate':'10/1/1989'},
{'name':'Paul', 'age':'29', 'birthdate':'10/14/1990'},
{'name':'Dennis', 'age':'25', 'birthdate':'11/29/1993'},
{'name':'Tim', 'age':'27', 'birthdate':'3/12/1991'},
{'name':'Erik', 'age':'24', 'birthdate':'10/31/1995'},
]
const body = document.body;
tbl = document.createElement('table');
tbl.style.width = '100px';
tbl.style.position = 'absolute';
tbl.style.border = '1px solid black';
tbl.style.marginLeft = "800px";
tbl.style.marginTop = "50px";
for (var i = 0; i < myArray.length; i++){
var row = `<tr><td>${myArray[i].name}</td><td>${myArray[i].age}</td><td>${myArray[i].birthdate}</td></tr>`;
tbl.innerHTML += row;
}
body.appendChild(tbl);
}
I checked your code and I see, when looping, you added empty href attributes in every element in that dropdown menu, basically, you are telling them that when that element is clicked, refresh the page please.
el.setAttribute("href", "");
Remove that line, and you got yourself a fix to your problem.

JS todo list item checked, and add item

I am aiming to create a JS todo list similar to https://www.w3schools.com/howto/howto_js_todolist.asp
I have created the basic structure of my todo list application and the function of the close buttons.
These are working well, but I have a problem with adding new todo list items and checking and unchecking todo items.
I'm not sure if I'm using the classlist toggle property well, and also cannot figure why the add button doesn't work at all.
var todoitemlist = document.getElementsByClassName('todo-item');
var i;
for (i = 0; i < todoitemlist.length; i++) {
var span = document.createElement("SPAN");
span.innerHTML = "Close";
span.className = "closebutton";
todoitemlist[i].appendChild(span);
}
var close = document.getElementsByClassName("closebutton");
var i;
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var listitem = this.parentElement;
listitem.style.display = "none";
}
}
var todoitemlistx = document.getElementsByClassName('todo-item');
//checked element
var i;
for (i = 0; i < todoitemlistx.length; i++) {
todoitemlistx[i].onclick = function(ev) {
ev.style.backgroundColor = "red";
ev.classList.toggle("todo-item-checked");
}
}
//add another list item
function add() {
var listitem = document.createElement("LI");
listitem.className = "todo-item";
var text = document.getElementById('todoinput').value;
var myul = getElementById('todo-list');
var t = document.createTextNode(text);
listitem.appendChild(t);
myul.appendChild(listitem);
var span = document.createElement("SPAN");
span.innerHTML = "Close";
span.className = "closebutton";
listitem[i].appendChild(span);
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
}
}
}
* {
box-sizing: border-box;
}
body {
text-align: center;
margin: 0;
padding: 0;
background-color: #dbf9fc;
font-family: Arial, Helvetica, sans-serif;
color: rgba(0, 27, 39);
}
#todoinput {
margin: 5px;
padding: 5px;
width: 65%;
}
#add-button {
padding: 5px;
margin: 5px;
width: 5%;
background-color: rgba(0, 27, 39);
color: #dbf9fc;
border: none;
border-radius: 5px;
height: 1fr;
cursor: pointer;
}
#add-button:hover {
background-color: black;
}
#todo-list {
display: inline-block;
margin: 0;
padding: 0;
list-style: none;
width: 70%;
}
.todo-item {
position: relative;
display: flex;
justify-content: flex-start;
background-color: white;
border: 2px solid black;
padding: 5px;
margin: 5px;
}
.closebutton {
cursor: pointer;
justify-self: flex-end;
background-color: #e6772d;
position: absolute;
right: 0;
top: 0;
color: white;
float: right;
padding: 5px;
width: 30%;
margin: 0;
}
.closebutton:hover {
background-color: #c46526;
}
.todo-item-checked {
position: relative;
display: flex;
justify-content: flex-start;
background-color: rgb(187, 187, 187);
border: 2px solid black;
padding: 5px;
margin: 5px;
text-decoration: line-through;
}
.black {
background-color: black;
}
<main class="centered">
<h1>ToDo List JS</h1>
<h3>js project</h3>
<form action="">
<input type="text" name="" id="todoinput" placeholder="Enter the activity you've wented to do">
<input type="button" value="Add" id="add-button" onclick="add()">
</form>
<ul id="todo-list">
<li class="todo-item">
Hit the lights
</li>
<li class="todo-item">
Hit the lights
</li>
<li class="todo-item">
Hit the lights
</li>
<li class="todo-item-checked todo-item">
Hit the lights
</li>
</ul>
</main>
I remember what it was like starting development and how hard it could be, so I persevered with this.
I thought it would be a few small changes but it turned into a massive rewrite.
Una grande padulo, as the Italians like to say.
I hope you can or try to understand what I did here.
The big lesson would be, don't write the same code twice, put it in a separate function.
So this seems to work.
Let me know if it doesn't.
var todoitemlist=document.getElementsByClassName('todo-item');
for(var i=0;i<todoitemlist.length;i++)
{
myawesomeclosebutton(todoitemlist[i]);
todoitemlist[i].addEventListener('click',myawesomebackground);
}
function myawesomeclosebutton(myawesomeitem)
{
var span=document.createElement('span');
span.innerHTML='Close';
span.className='closebutton';
span.addEventListener('click',myawesomecloseevent);
myawesomeitem.appendChild(span);
}
function myawesomebackground(ev)
{
if(ev.target.style.backgroundColor!='red')
{
ev.target.style.backgroundColor='red';
}
else
{
ev.target.style.backgroundColor='transparent';
}
}
function myawesomecloseevent(event)
{
var div=event.target.parentElement;
div.style.display='none';
}
function add()
{
var listitem=document.createElement('li');
listitem.className='todo-item';
var myawesomeinput=document.getElementById('todoinput');
var text=myawesomeinput.value;
var myul=document.getElementById('todo-list');
var t=document.createTextNode(text);
listitem.appendChild(t);
myul.appendChild(listitem);
listitem.addEventListener('click',myawesomebackground);
myawesomeclosebutton(listitem);
myawesomeinput.value='';
}

Close list of Dropdown Menu

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.

Javascript - Lists created through user input with a sort button

What I want: User types word into input bar -> user presses Add button -> word is added to two lists "unsortedUL" and "sortedUL" - > user presses Sort button -> the list "sortedUL" gets sorted by descending (z-a), while "unsortedUL" remains exactly how the user inputted it.
I cannot figure out how to get TWO lists while only ONE of them is sorted.
var myNodelist = document.getElementsByTagName("LI");
var i;
for (i = 0; i < myNodelist.length; i++) {
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
myNodelist[i].appendChild(span);
}
var close = document.getElementsByClassName("close");
var i;
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
}
}
function newElement() {
var li = document.createElement("li");
var inputValue = document.getElementById("myInput").value;
var t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue === '') {
alert("You must write a word!");
} else {
document.getElementById("sortedUL").appendChild(li);
}
document.getElementById("myInput").value = "";
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
li.appendChild(span);
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
}
}
}
function sortList() {
var list, i, switching, b, shouldSwitch;
list = document.getElementById("sortedUL");
switching = true;
while (switching) {
switching = false;
b = list.getElementsByTagName("LI");
for (i = 0; i < (b.length - 1); i++) {
shouldSwitch = false;
if (b[i].innerHTML.toLowerCase() < b[i + 1].innerHTML.toLowerCase()) {
shouldSwitch= true;
break;
}
}
if (shouldSwitch) {
b[i].parentNode.insertBefore(b[i + 1], b[i]);
switching = true;
}
}
}
document.getElementById("date").innerHTML = new Date().toDateString();
document.getElementById("time").innerHTML = new Date().toLocaleTimeString();
body {
margin: 0;
min-width: 250px;
background-color: green;
}
* {
box-sizing: border-box;
}
ul {
margin: 0;
padding: 0;
width: 100%;
float: right;
}
ul li {
cursor: pointer;
position: relative;
padding: 12px 8px 12px 40px;
list-style-type: number;
background: #eee;
font-size: 18px;
transition: 0.2s;
text-align: center;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.close {
position: absolute;
right: 0;
top: 0;
padding: 12px 16px 12px 16px;
}
.header {
background-color: green;
padding: 30px 40px;
color: white;
text-align: center;
}
.header:after {
content: "";
display: table;
clear: both;
}
input {
border: none;
width: 50%;
padding: 10px;
float: center;
font-size: 16px;
}
.addBtn {
padding: 10px;
width: 10%;
background: #d9d9d9;
color: #555;
float: right;
text-align: center;
font-size: 16px;
cursor: pointer;
transition: 0.3s;
}
.sortBtn {
padding: 10px;
width: 10%;
background: #d9d9d9;
color: #555;
float: left;
text-align: center;
font-size: 16px;
cursor: pointer;
transition: 0.3s;
}
<!DOCTYPE html>
<html>
<title>Assignment Two</title>
<body>
<h1 style="color:white;"align="center"id="date"></h1>
<h1 style="color:white;"align="center"id="time"></h1>
<div id="myDIV" class="header">
<h2 style="margin:5px">Enter a list of words</h2>
<input type="text" id="myInput" placeholder="Word...">
<span onclick="newElement()" class="addBtn">Add</span>
<span onclick="sortList()" class="sortBtn">Sort</span>
</div>
<ul id="sortedUL">
</ul>
<ul id="unsortedUL">
</ul>
</body>
</html>
You have to clone the HTML Node to append it twice.
Or create it twice like I did.
var myNodelist = document.getElementsByTagName("LI");
var i;
for (i = 0; i < myNodelist.length; i++) {
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
myNodelist[i].appendChild(span);
}
var close = document.getElementsByClassName("close");
var i;
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
}
}
function newElement() {
if (inputValue === '') {
alert("You must write a word!");
} else {
var li = document.createElement("li");
var inputValue = document.getElementById("myInput").value;
var t = document.createTextNode(inputValue);
li.appendChild(t);
document.getElementById("sortedUL").appendChild(li);
var li = document.createElement("li");
var inputValue = document.getElementById("myInput").value;
var t = document.createTextNode(inputValue);
li.appendChild(t);
document.getElementById("unsortedUL").appendChild(li);
}
document.getElementById("myInput").value = "";
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
li.appendChild(span);
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
}
}
}
function sortList() {
var list, i, switching, b, shouldSwitch;
list = document.getElementById("sortedUL");
switching = true;
while (switching) {
switching = false;
b = list.getElementsByTagName("LI");
for (i = 0; i < (b.length - 1); i++) {
shouldSwitch = false;
if (b[i].innerHTML.toLowerCase() < b[i + 1].innerHTML.toLowerCase()) {
shouldSwitch= true;
break;
}
}
if (shouldSwitch) {
b[i].parentNode.insertBefore(b[i + 1], b[i]);
switching = true;
}
}
}
document.getElementById("date").innerHTML = new Date().toDateString();
document.getElementById("time").innerHTML = new Date().toLocaleTimeString();
body {
margin: 0;
min-width: 250px;
background-color: green;
}
* {
box-sizing: border-box;
}
p {
font-size: 16px;
margin-left: 20px;
color: white;
text-transform: uppercase;
}
ul {
margin: 0 0 20px 0;
padding: 0;
width: 100%;
float: right;
}
ul li {
cursor: pointer;
position: relative;
padding: 12px 8px 12px 40px;
list-style-type: number;
background: #eee;
font-size: 18px;
transition: 0.2s;
text-align: center;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.close {
position: absolute;
right: 0;
top: 0;
padding: 12px 16px 12px 16px;
}
.header {
background-color: green;
padding: 30px 40px;
color: white;
text-align: center;
}
.header:after {
content: "";
display: table;
clear: both;
}
input {
border: none;
width: 50%;
padding: 10px;
float: center;
font-size: 16px;
}
.addBtn {
padding: 10px;
width: 10%;
background: #d9d9d9;
color: #555;
float: right;
text-align: center;
font-size: 16px;
cursor: pointer;
transition: 0.3s;
}
.sortBtn {
padding: 10px;
width: 10%;
background: #d9d9d9;
color: #555;
float: left;
text-align: center;
font-size: 16px;
cursor: pointer;
transition: 0.3s;
}
<!DOCTYPE html>
<html>
<title>Assignment Two</title>
<body>
<h1 style="color:white;"align="center"id="date"></h1>
<h1 style="color:white;"align="center"id="time"></h1>
<div id="myDIV" class="header">
<h2 style="margin:5px">Enter a list of words</h2>
<input type="text" id="myInput" placeholder="Word...">
<span onclick="newElement()" class="addBtn">Add</span>
<span onclick="sortList()" class="sortBtn">Sort</span>
</div>
<p>Sorted</p>
<ul id="sortedUL">
</ul>
<p>Unsorted</p>
<ul id="unsortedUL">
</ul>
</body>
</html>
While you need list you can use Javascript Array
Here you can have two Arrays which would be SortedList and UnsortedList
I have declare both the list globally so that you can sort one list and keep one list without change
Refer The Below Code for the Work Flow
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form>
<div>
<input type="text" name="txtName" id="txtName"/>
<input type="button" value="Add" onclick="AddToList()"/>
<input type="button" value="Sort" onclick="SortList()"/>
</div>
</form>
</body>
</html>
<script>
var sortedList = [];
var unsortedList = [];
function AddToList() {
var data = document.getElementById("txtName").value;
sortedList.push(data);
unsortedList.push(data);
}
function SortList() {
sortedList.sort();
sortedList.reverse();
console.log(sortedList);
console.log(unsortedList);
}
</script>
Here I have created two buttons as you said
And Called a function to sort and other to add in the List.
As you said you need the Unsorted List to be as it is, So in the SortList() function we have printed sortedList and unsortedList Both two see a diffrence.
As expected sortedList will print the descending order data and unsortedList will print normal data.
You just need to insert it into both lists as each word is added, i.e. where you have:
document.getElementById("sortedUL").appendChild(li);
you should add a second line like this:
document.getElementById("unsortedUL").appendChild(li.cloneNode(true));
The node cloning might be what you were missing if you tried it before, otherwise it would move the same element and it ends up in only one list. The 'true' argument makes a deep copy so that the text node underneath it is copied as well.
Incidentally, this whole operation would be a lot easier with jQuery, it's the kind of DOM manipulation that the library was meant for. However people jump to jQuery so quickly and it's good that you are doing it with vanilla JavaScript.

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