Reputation: 59
The jQuery code I'm using on my HTML isn't working. I want the "dropbtn" to be clicked on to display it's hidden contents instead of being hovered on. I tried removing all "hover" effects on CSS but the jQuery code still wouldn't work. The jQuery works fine on other codes except this one. How can I fix this?
Upvotes: 1
Views: 65
Reputation: 376
To refer to a class in JQuery, you need to include a .
before the class name:
$(".dropbtn").click(function(){
$(".dropdown-content").toggle();
});
Upvotes: 0
Reputation: 337714
Your jQuery code was almost correct, you were just missing the .
prefix on the class selectors.
To make the styling work in the same manner you simply need to remove the :hover
rules from your CSS and instead use a class selector which you toggle on successive clicks of the .dropbtn
element. In the example below I used active
. Try this:
$(document).ready(function() {
$(".dropbtn").click(function() {
$(this).toggleClass('active');
$(".dropdown-content").toggle();
});
});
.dropdown {
position: relative;
display: inline-block;
}
.dropbtn {
width: 115px;
height: 28px;
border: solid 1px #cebbb1;
background-color: white;
color: #897f63;
margin-left: -5px;
position: relative;
cursor: pointer;
}
.dropbtn.active {
border: solid 1px #0093dc;
color: #0093dc;
}
#mainspan {
font-weight: bold;
position: absolute;
padding-left: 7px;
padding-top: 4px;
}
.dropdown-content {
display: none;
position: absolute;
background-color: white;
min-width: 160px;
z-index: 1;
border: solid 1px #cebbb1;
width: 170px;
margin-left: -5px;
}
.dropdown-content a {
padding: 1px 14px;
display: block;
color: #897f63;
}
.dropdown-content a:hover {
background-color: #f1f1f1;
text-decoration: none;
color: #897f63;
}
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="DROPDOWN.css">
</head>
<body>
<div class="dropdown">
<div class="dropbtn">
<span id="mainspan">main</span>
</div>
<div class="dropdown-content">
<a href="#">item 1</a>
<a href="#">item 2</a>
</div>
</div>
<script type='text/javascript' src="DROPDOWN.js"></script>
</body>
</html>
Upvotes: 1