Gareth Compton Gareth Compton - 3 months ago 13
CSS Question

Jquery/Css Issue #2: Hover Elements triggering unwanted hovering action

Long time ago, I made a question with the concept: Jquery/CSS challenge, where I use Jquery to fill in for CSS place and was given the hover function (because I haven't learned that before, and is now very useful!) So I copied the code, edited it to my liking to make my homemade 'navigation' buttons made by the span attribute (i know i can use button, but was curious on how it plays here).

So when I begin to test it, I noticed an odd behavior. After I started my hovering activity on multiple 'same' attributes. My mouse acted weirder when my on hover acts like 'off hover' and when I go away it acted like I was 'on hover'. I even edited to mouse enter and mouse leave from the jQuery library and I still run into the same issue, HELP!

Here is my sample of code used for the jQuery-Css Project:

$(document)
.ready(
function() {
var $span = $("span");
$span
.css(
{
"background-color" : "#eef"
}
)
.hover(
function (){
$(this)
.css(
{
"background-color" : "#ddf"
}
)
;
},
function () {
$(this)
.css(
{
"background-color" : "#eef"
}
)
;
}
)
;
}
)
;


Then the appropriate HTML coding used for this scenario:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Jquery Test Page.</title>
<!--[if lte IE 7]>
<style>
.content {
margin-right: -1px;
} /* this 1px negative margin can be placed on any of the columns in this layout with the same corrective effect. */
ul.nav a {
zoom: 1;
} /* the zoom property gives IE the hasLayout trigger it needs to correct extra whiltespace between the links */
</style>
<![endif]-->
</head>
<body>
<div class="menu">
<span id="a">I am button A</span>
<span id="b">I am button B</span>
<span id="c">I am button C</span>
</div>
</body>
</html>


I do spread my coding out just for easy editing purposes, but I need help with this! Thank you all for making this a good community!

Answer

It is not acting weird. That is happening because you have made two functions there in the hover event. The first one is fired when you hover and the second one when you left the button. If you want only the hover event you can make only one function there

$span.css({"background-color" : "#eef"}).hover(function (){
   $(this).css({"background-color" : "blue"});
}); 

And you can use mouseleave function in jquery to understand when the user left the button.

Read this article for better understand http://www.w3schools.com/jquery/event_hover.asp