Joy07
Joy07

Reputation: 47

After jquery click function hover not working

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

Answers (2)

sglazkov
sglazkov

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

Khanh TO
Khanh TO

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");
  });
});

http://jsfiddle.net/yyqwkaqp/

If you're looking for a jQuery approach, you have to add !important to star-hover:

.star-hover {
   background-color: blue !important;
 }

http://jsfiddle.net/d8wmhmrp/

But I would prefer the :hover solution

Upvotes: 1

Related Questions