Reputation: 91
I want to create a classic menu bar on a web page using HTML, CSS and JavaScript. Everything works, but clicking on the menu item does not hide the menu. Rather, the menu appears until the cursor moves off the item. This is unnatural, and is particularly troublesome on touch based devices. The solutions online all use jQuery, which looks unfamiliar and alien to me. Is there a way to hide the menu without using jQuery?
function onButtonClick(event) {
event.stopPropagation();
console.log(event.target.id);
//close menu here
}
My fiddle: https://jsfiddle.net/crlab/uq6at5mk/
Upvotes: 1
Views: 1246
Reputation: 38134
Just another approach by handling click event:
HTML:
<li class="dropdown" id="file" onclick="onClick(this)">
...
</li>
<li class="dropdown" id="view" onclick="onClick(this)">
...
</li>
CSS:
/*.dropdown:hover .dropdown-content {
display: block;
}*/
And JavaScript:
function onClick(event) {
let list = event.children;
setDisplayProperty(list);
}
function setDisplayProperty(list) {
for (let item of list) {
console.log(item.id);
if(item.style.display == 'block')
item.style.display = '';
else
item.style.display = 'block';
}
}
Upvotes: 0
Reputation: 5411
First, you specify the element to deal with:
var el = this.parentNode;
Then, using the same logic you did on CSS, you set display
to none
.
el.style.display = "none";
Finally, after 30ms
, you restore the inline style to preserve hover
effect:
setTimeout(function() {
el.style.removeProperty("display");
}, 30);
The final result would be like this:
function onButtonClick(event) {
event.stopPropagation();
console.log(event.target.id);
var el = this.parentNode;
el.style.display = "none";
setTimeout(function() {
el.style.removeProperty("display");
}, 30);
}
Hope it helps.
Upvotes: 2