Reputation: 71
I am currently creating a dropdown menu so I want the menu to be displayed when clicked by adding class via Javascript but classList is not working at all. I tried lots of time but couldn't. Also if i add style.display = "block"
, then it works! I am unable to figure out! Please Help me!
document.getElementById('dbtn').addEventListener('click', function() {
document.getElementById('d-content').classList.toggle('show');
});
#wrapper {
position: relative;
display: inline-block;
}
#dbtn {
background-color: #F44336;
font-size: 27px;
font-family: 'Droid Sans', sans-serif;
border: none;
padding: 0.3em 0.6em;
color: #FFFFFF;
cursor: pointer;
outline: none;
}
#d-content {
position: absolute;
display: none;
background-color: #F44336;
font-family: 'Droid Sans', sans-serif;
font-size: 22px;
border-top: 2px solid #FFFFFF;
z-index: 1;
box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
}
#d-content a {
color: #FFFFFF;
text-decoration: none;
display: block;
padding: 0.3em 5em 0.3em 0.3em;
}
#d-content a:hover {
background-color: darkorchid;
}
.show {
display: block;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dropdown Menu</title>
</head>
<body>
<div id="wrapper">
<input type="button" id="dbtn" value="Select..." />
<div id="d-content" class="drop">
<a>USA</a>
<a>Canada</a>
<a>Europe</a>
</div>
</div>
</body>
</html>
Upvotes: 0
Views: 766
Reputation: 559
The problem is you are using the wrong approach (Don't worry it happens, and it's okay). it would be easier if you just toggle the display property it will save lot of your time. you can toggle the display property using following snippest:
document.getElementById('dbtn').addEventListener('click', function () {
var dContent = document.getElementById('d-content');
dContent.style.display = dContent.style.display === 'none' ? 'block' : 'none';
});
Upvotes: 1
Reputation: 9709
Browser calculates css properties based on selectors order and selectors weight. In your case #id
selector overrides your class selector.
.show {
display: block !important;
}
Or it's better not to use important at all:
#d-content.show{
display: block ;
}
You can read more about selectors weight here. Also you can alaways check those kind of things in dev console.
Upvotes: 2
Reputation: 1123
In CSS, the id selector has far more weight over the class selector.
You need to add !important;
to your .show
display
rule.
Upvotes: 1