Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
HTML
<html>


<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>

<style type="text/css">

.abc
{
    background-color:green;
    font-size:200%;
}

.red
{
    background-color:red;
    font-size:200%;
}



</style>
<body>

<p class="abc">ABC</p>



</body>


<script type="text/javascript">


$(document).ready(function(){
  $(".abc").mouseenter(function(){
    $(".abc").css("background-color","yellow");
  });
  $("p").mouseleave(function(){
    $("p").addClass("red");
  });
});

</script>



</html>
Posted
Updated 29-Sep-21 0:31am
Comments
ZurdoDev 31-Jul-13 11:29am    
I don't know why? Did you look in your developer tools to see if it did apply it?

The class 'red' is added to the div when the mouse leaves. However because you are adding in-line CSS styling during the mouseenter function, it supersedes the CSS styling.

<style type="text/css">
#ex
{
background: red;
}
</style>

<div id="ex" style="background: yellow">

</div>


The div will show up with a yellow background. This is essentially what you are doing.

I would create a second class named 'yellow' on mouseenter add the 'yellow' class. on mouseleave remove the 'yellow' class and add the 'red' class.


HTML
<html>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<style type="text/css">
.abc
{
    background-color:green;
    font-size:200%;
}
.red
{
    background-color:red;
}
.yellow
{
	background-color: yellow;
}
</style>
<body>
<p class="abc">ABC</p>
</body>
<script type="text/javascript">
$(document).ready(function(){
  $(".abc").mouseenter(function(){
	$(this).removeClass("red");
    $(this).addClass("yellow");
  });
  $("p").mouseleave(function(){
	$(this).removeClass("yellow");
	$(this).addClass("red");
  });
});
</script>
</html>
 
Share this answer
 
v2
This is just the pure logic looks entangled. You add a class but never remove any.

Do a simple thing: have two different classes. On enter and leave, always remove one class and add another one. Also, you can simplify your code if you use the .hover method instead, it accepts two handler, one for moving in, another one for moving out:
http://api.jquery.com/hover/[^].

See also:
http://api.jquery.com/category/css/[^],
http://api.jquery.com/addClass/[^],
http://api.jquery.com/removeClass/[^].

—SA
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900