TheRedDwarf
TheRedDwarf

Reputation: 183

jQuery settimeout not working with anonymous function

I have this setup to add a mouseenter event to each of my DIVs:

  $(document).ready(function () {
  $('div[id^=domainEnter]').mouseenter(function () {


                toggleSearchDisplay($(this).attr('domaincount'), 'show');

            });
 });

Then I have this function defined:

  function toggleSearchDisplay(num, showhide) {

            if ($('div[id=domainDiv' + num + ']').css('display') == "block" || showhide == "hide") {
                $('div[id=domainDiv' + num + ']').hide('fast');
                $('a[id = domainLink' + num + ']').text('+');
                $('input[id ^= SearchControls_' + num + '__SearchControlVisible]').val('false');
            } else {

                $('div[id=domainDiv' + num + ']').show('fast');
                $('a[id = domainLink' + num + ']').text('-');
                $('input[id ^= SearchControls_' + num + '__SearchControlVisible]').val('true');


            }
        }

this all works well and does what I need it to, but now I'm trying to get a timeout/delay setup on the MouseEnter bit in the first block... I tried this, and it never executes:

$('div[id^=domainEnter]').mouseenter(setTimeout(function () {

                toggleSearchDisplay($(this).attr('domaincount'), 'show');

            },1000));

I then tried this, which executes, but there's no delay... it runs normally:

 $('div[id^=domainEnter]').mouseenter(function () {

            setTimeout(toggleSearchDisplay($(this).attr('domaincount'), 'show'),1000);

        });

I don't know what to do... any thoughts?

Upvotes: 0

Views: 490

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382122

In your first try, you're not giving a function as argument to mouseenter but the result of setTimeout, that is a timer.

In the second one, when the callback provided to setTimeout is executed, this is the window.

Here's a way to fix it :

$('div[id^=domainEnter]').mouseenter(function(){
     var $this = $(this);
     setTimeout(function () {
        toggleSearchDisplay($this.attr('domaincount'), 'show');
     },1000)
});

Upvotes: 1

Related Questions