1

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>

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Khanh TO css :hover is fine but I am looking the jQuery way :)
@Joy07: then you have to add !important
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.