javascript - Toggling CSS Class Has No Effect on Element -
i trying create basic javascript drop down menu. toggling class called "show," displays drop down content. not work - element stays hidden after class applied.
i imagine have error in here somewhere, can't seem find it. help!
function drop() { document.getelementbyid('content').classlist.toggle('show'); }
.container { display: inline-block; position: relative; } .dropdown_btn { color: white; background-color: black; cursor: pointer; padding: 20px; } .dropdown_btn:hover, .dropdown_btn:focus { background-color: grey; } #content { display: none; position: absolute; background: grey; color: white; width: 160px; } .container { text-decoration: none; display: block; padding: 10px; color: white; } .container a:hover { background-color: #f1f1f1 } .show { display: block; }
<div class="container"> <button class="dropdown_btn" onclick="drop()">menu</button> <div id="content"> <a href="">link 1</a> <a href="">link 2</a> <a href="">link 3</a> </div> </div>
the problem not javascript, it's css.
your #content
style rule more specific .show
rule. when toggle .show
rule on , off, #content
rule overrides , rule says display
should none
.
see selector specificity more information selectors override others. there great site can test selectors see specificity is. using site's "calculator" can see id
based selector override "class" selector.
the solution change #content
selector class selector, i've done here (.menu
). way, you'll have 2 class selectors affecting drop down menu , both have same specificity (the 1 override other determined last 1 applied).
function drop() { document.getelementbyid('content').classlist.toggle('show'); }
.container { display: inline-block; position: relative; } .dropdown_btn { color: white; background-color: black; cursor: pointer; padding: 20px; } .dropdown_btn:hover, .dropdown_btn:focus { background-color: grey; } /* used id based selector (#content), type of selector more specific class selector toggling class selector had no effect. */ .menu { display: none; position: absolute; background: grey; color: white; width: 160px; } .container { text-decoration: none; display: block; padding: 10px; color: white; } .container a:hover { background-color: #f1f1f1 } /* class toggled on , off. because css rule hides menu uses class selector, class selector can override it. */ .show { display: block; }
<div class="container"> <button class="dropdown_btn" onclick="drop()">menu</button> <div id="content" class="menu"> <a href="">link 1</a> <a href="">link 2</a> <a href="">link 3</a> </div> </div>
Comments
Post a Comment