views:

2051

answers:

2

This code is not working, what im doing wrong?

Tnks.

 var x;
    x=jQuery(document);
    x.ready(inicializarEventos);

    function inicializarEventos()
    {
      var x;
      x=jQuery(".Caja2");
      x.hover(entraMouse,saleMouse);
    }


    function entraMouse()
    {
      jQuery(".Caja2").stop().fadeOut();
    }

    function saleMouse()
    {
      jQuery(".Caja2").stop().fadeIn();
    }
A: 

Dreas Grech from the comments is correct. You need to check if the element is being animated before calling the .stop() method on it. Try this:

function entraMouse() { jQuery(".Caja2:animated").stop();jQuery(".Caja2").fadeOut(); }
function saleMouse() {jQuery(".Caja2:animated").stop();jQuery(".Caja2").fadeIn(); }
Salty
I still get a js error from the browser.
What is the error you get?
Salty
+3  A: 

It appears (to me) that you want to have a box that will fade out when the mouse is positioned over it, and will reappear when the mouse is moved away. This is actually trickier than it initially appears.

When you call $().fadeOut(), what happens is jQuery animates the fade, and then sets display: none on that element. Because the element is then removed from the display list, the mouseOut event is fired, which of course then begins the fadeIn() effect. This results in an endless loop of mouseIn and mouseOut events as long as your mouse is hovered in that area.

What you may want to try is using the $().fadeTo() method. In the following example, I am animating the opacity property to 0.0 when the mouse enters, and back to 1.0 when the mouse leaves. Because the element is never actually hidden (just invisible), the mouseOut event is able to fire correctly.

jQuery(document).ready(inicializarEventos);

function inicializarEventos() {
    $(".Caja2").hover(entraMouse, saleMouse);        
}

function entraMouse() {
    jQuery(this).fadeTo("slow", 0.0)
}

function saleMouse() {
    jQuery(this).fadeTo("slow", 1.0)
}

In the future, I would suggest explaining why you think "the code is not working". You need to define how you expect the code to function, and what the current result is. That will help me an others better know how to answer your question.

sixthgear
I changed my initial example from using the $().animate method to using the $().fadeTo method. This should handle cross-browser differences better.
sixthgear