Reputation: 47
I am recently started to learning jQuery and now I am stuck with this problem, everything working as expected but after the click function execute jquery hover function is not working...
$(function(){
$("div.star").hover(function(){
$(this).addClass("star-hover");
});
$("div.star").mouseout(function(){
$(this).removeClass("star-hover");
);
});
$(function(){
$("div.star").click(function(){
$(this).addClass("star-chosen");
});
});
.star {
height: 2em;
width: 2em;
border: .1em solid black;
border-radius: 1.1em;
display: inline-block;
margin: 0;
padding: .1em;
}
.star-hover {
background-color: blue;
}
.star-chosen {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div class="star"></div>
<div class="star"></div>
<div class="star"></div>
<div class="star"></div>
<div class="star"></div>
</div>
Upvotes: 1
Views: 549
Reputation: 1066
write in CSS .star-hover after .star-chosen it help you
why you add class if hover? it can make using CSS see this solution:
$("div.star").click(function () {
$(this).addClass("star-chosen");
});
.star {
height: 2em;
width: 2em;
border: .1em solid black;
border-radius: 1.1em;
display: inline-block;
margin: 0;
padding: .1em;
}
.star-chosen {
background-color: red;
}
.star:hover {
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container">
<div class="star"></div>
<div class="star"></div>
<div class="star"></div>
<div class="star"></div>
<div class="star"></div>
</div>
Upvotes: 0
Reputation: 48992
When the element has both classes star-hover
and star-chosen
, it's really the problem as to which background-color
to apply.
Why don't just use css :hover
:
.star {
height: 2em;
width: 2em;
border: .1em solid black;
border-radius: 1.1em;
display: inline-block;
margin: 0;
padding: .1em;
}
.star:hover {
background-color: blue;
}
.star-chosen {
background-color: red;
}
Your js:
$(function(){
$("div.star").click(function(){
$(this).addClass("star-chosen");
});
});
If you're looking for a jQuery approach, you have to add !important
to star-hover
:
.star-hover {
background-color: blue !important;
}
But I would prefer the :hover
solution
Upvotes: 1