zealisreal
zealisreal

Reputation: 505

Problems getting a jQuery .mouseenter()/.mouseleave() script with user interaction to work

Firstly, apologies for the title, I could not think of a suitable one.

I am unsure as to why the hide() function within the below code comes back erroneous in firebug when triggered, I am pretty sure the rest of the code will work fine once I have ironed this flaw out, any help/suggestions would be appreciated.

Firebug Console error:

hide is not defined
it-services() it-services (line 396)
time = setTimeout("hide()",3000); 

Code I have thus far:

        var time;

        $("#form").mouseenter(function() {
            clearTimeout(time);
            $(this).delay(800).animate({
                right: 0
            }, 2000);
        }).mouseleave(function() {
            function hide() {
                $(this).delay(800).animate({
                    right: "-325px"
                }, 1000);
            }
            time = setTimeout(hide,3000);
        });

Thank you all very much for any help in advance,

Dan.

Upvotes: 1

Views: 320

Answers (2)

Ryan
Ryan

Reputation: 3815

There are 2 issues in the new code

  1. Inside the hide function, the context of $(this) is not same as the when it is being called inside the mouseout function.
  2. Secondly, the hide function is defined as an anonymous function inside the mouseout function

I feel it would make more sense if it were a function declared outside the mouseover event handling function. That way you can globally reference it from the setTimeOut as well as the mouseout event handler. Try the below code. I believe this should solve the issue, or at least take you a step ahead.

var time;
var $form;

$("#form").mouseenter(function() {
    $form = $(this);
    clearTimeout(time);
    $(this).delay(800).animate({
        right: 0
    }, 2000);
}).mouseleave(function() {
    hide();
    time = setTimeout(hide,1000);
});
function hide() {
    $form.delay(800).animate({
        right: "-325px"
    }, 3000);
}

Upvotes: 1

karim79
karim79

Reputation: 342695

You're declaring the hide() function after you invoke it using setTimeout. Simply put the declaration before the setTimeout call.

Also, when you pass a string of code as first argument to setTimeout, it gets evaled. eval is evil. Just pass the function object:

function hide() {
    $(this).delay(800).animate({
        right: "-325px"
    }, 1000);
}
time = setTimeout(hide, 3000);

Upvotes: 1

Related Questions