script code:
(function() {
var doc = document.querySelector("html");
var dd = document.querySelector("#dd");
doc.addEventListener(
"click",
function(event) {
dd.classList.remove("active");
},
false
);
dd.addEventListener(
"click",
function(event) {
dd.classList.toggle("active");
event.stopPropagation();
},
false
);
})();
Here is the HTML →
<div id="dd" class="wrapper">
but that restricts to only one menu on the whole page. what if we want 2 or more menu. In that case, I think ID method should be replaced somehow by the class method.
I did this →
<div id="" class="wrapper dd">
and
(function() {
var doc = document.querySelector("html");
var dd = document.querySelector(".dd");
doc.addEventListener(
"click",
function(event) {
dd.classList.remove("active");
},
false
);
dd.addEventListener(
"click",
function(event) {
dd.classList.toggle("active");
event.stopPropagation();
},
false
);
})();
but it doesnt solve the Problem.
Reference
When going from a single id to potentially multiple matching class names, you cannot use querySelector anymore because that only gets the first matching element. You need to use querySelectorAll(...).forEach
instead.
Where you had var dd
, that’s going to be a collection of multiple dd’s now.
// var dd = document.querySelector(".dd");
var dds = document.querySelectorAll(".dd");
And where you used dd, that needs to be wrapped in forEach
now.
Both for removing the class name:
dds.forEach(function (dd) {
dd.classList.remove("active");
});
and when toggling the class name:
dds.forEach(function (dd) {
dd.addEventListener(...);
});
Here’s an updated pen showing it in action:
2 Likes
A new learning for me, I implemented your code, but that deosnt work anymore
I see that the browser console shows an error. That’s something that you need to fix.
1 Like
codeispoetry:
Fixed still not working.
The scripting code has been updated, but I see that the HTML code still uses identifiers instead of a class name.
1 Like
Please check this . Looks like that there is some minor subtle mistake.
the console is throwing an uncaught syntax error in this line of code →
})();
the above is also the last line of code in that javascript file.
My Chrome browser is showing no console errors on that screencast page.
1 Like
You mean this page . This is what my chrome console is showing .
codeispoetry:
You mean this page .
You have a double parenthesis at the very start, that must be a single parenthesis instead.
1 Like
This is a real learning for me today. I am feeling one step upward towards my Javascripting learning journey.
3 Likes
system
Closed
March 24, 2018, 3:02pm
13
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.