Mike
Mike

Reputation: 33

Jquery: Parent div not selected for fadein

I have a mouseover function but when I try to fade in the optionbox, it does it to all the classes named 'box'. I have tried to set this in there but my jquery-skills (if I have some already) are letting me down.

Aside from this problem the code is working fine.

   $(".box").live({
    mouseenter:
       function()
       {
        optionsTimeout = setTimeout(

            function() {
                $('.optionbox').fadeIn(200);
            }

        , 1000);
       },
    mouseleave:
       function()
       {
        clearTimeout(optionsTimeout);
        $('.optionbox').fadeOut(200);
       }
   }
);

HTML:

<div class="box">
    <div class="optionbox"><a href="">Delete</a></div>
</div>
<div class="box">
    <div class="optionbox"><a href="">Delete</a></div>
</div>

Upvotes: 0

Views: 212

Answers (4)

guzart
guzart

Reputation: 3730

mouseenter: function() {
    (function (self) {
        var optionsTimeout = setTimeout(function() { 
            $('.optionbox', self).fadeIn(200); 
        }, 1000);
        self.data('showTimeout', optionsTimeout);
    })($(this)); 
},
mouseleave: function () {
   var self = $(this),
       optionsTimeout = self.data('showTimeout');
   clearTimeout(optionsTimeout);
   $('.optionbox', this).fadeOut(200);
}

You need to tell jQuery to use elements within the contextual .box, therefore the use of $(selector, context).

The enclosing function with self is to save a reference to the context inside the execution of the timeout, so you pass it as a parameter of a self-executable function, and when the timeout expires it will have a reference to the executing .box

You could also encounter problems by using the same global variable for all timeouts, so you shoul save the contextual timeout code for each one, in my example I use $.data to save the code, and restore it.

Upvotes: 0

bfavaretto
bfavaretto

Reputation: 71908

Try this:

$(".box").live({
    mouseenter: function() {
       var $that = $(this);
       optionsTimeout = setTimeout(function() {
           $that.find('.optionbox').fadeIn(200);
       }, 1000);
    },
    mouseleave: function() {
        clearTimeout(optionsTimeout);
        $(this).find('.optionbox').fadeOut(200);
    }
});

Upvotes: 1

Didier Ghys
Didier Ghys

Reputation: 30666

Use this (the .box element) inside the handler as a context:

$(this).find('.optionbox').fadeIn(200);

.find()

Upvotes: 0

James Montagne
James Montagne

Reputation: 78630

Change it to $(this).find('.optionbox') to only get elements within the current element.

Upvotes: 0

Related Questions