Question

I'm attempting to create a mouseover event function that contains a variable. I plan on using if and else to achieve the mouseover and mouseleave (or out). I've attempted to explain this further at this link in the //comments. http://jsfiddle.net/EsEBY/14/

jQuery:

var n = $("#block").mouseover(function () {});

if (n) { //if variable n (mouseover) occurs on #block, make #block opacity 1
$("#block").css("opacity", "1"),
alert("Working!");
} else { //else #block opacity .5
$("#block").css("opacity", ".5");
}

CSS:

#block {
width:5em;
height:5em;
background:#CCC;
margin:1em;
}

I've probably got this all wrong but am trying to do this in a different way from .hover method.

Was it helpful?

Solution

What you need is

$("#block").hover(function () {
    $(this).css("opacity", "1");
}, function(){
    $(this).css("opacity", ".5");
});

Demo: Fiddle

The mouseover does not work like that, the code that is suppose to run on mouse over has to be in the callback function passed to the event.

In your case you need to change the opacity to 1 when mouser enter to #block and it has to changed to .5 when mouse leaves, for this purpose you can use the .hover() event handlers

OTHER TIPS

If you are simply trying to change the opacity on mouseover using jQuery, then this is probably what you are trying to do:

$("#block").mouseover(function () {
    $(this).css('opacity', '1');
}).mouseout(function(){
    $(this).css('opacity', '.5');
});

However, this is probably better accomplished with CSS:

<style type="text/css">
#block {
    opacity: .5;
}

#block:hover {
    opacity: 1;
}
</style>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top