3

I have the following code which uses Jquery UI Drag and Drop. When the item is dropped into the area, the drop zone changes into the company logo, then I want a delay and a redirect to the URL within the dropped link.

I can get the logo to change OR the url to redirect but not both, when I have both setup the delay doesn't happen and the redirect goes start away. I assume I am doing something wrong with the setTimeout.

Code is as follows:

// let the trash be droppable, accepting the gallery items
$( "#droparea" ).droppable({
  accept: "ul.gallery > li a",
  activeClass: "ui-state-highlight",
  drop: function( event, ui ) {

      var thelink = $(ui.draggable).attr("href");
      $('#droparea').prepend('<img id="theImg" src="../img/logo_navigation.jpg" />');

      setTimeout(redirectLink(url),5000);
  }
});

// URL REDIRECT FUNCTION
function redirectLink(url)
{
   window.location.replace(url);
}
sluggerdog
  • 843
  • 4
  • 12
  • 35

1 Answers1

10

Explanation

You need to pass a function reference (or a string of JavaScript code) to setTimeout, in order for it to be executed when the timeout is reached.

In your code, you were immediately calling the function (which doesn't return anything anyways, so its return value is undefined...so nothing will execute when the timeout is reached).

Approach 1

Use an anonymous function that runs your code:

setTimeout(function () {
    redirectLink(url);
}, 5000);

function redirectLink(url) {
   window.location.replace(url);
}

Approach 2

Make your redirectLink function return a function and call it like you originally did:

setTimeout(redirectLink(url), 5000);

function redirectLink(url) {
    return function () {
        window.location.replace(url);
    };
}

Approach 3

You could use .bind():

setTimeout(redirectLink.bind(null, url), 5000);

function redirectLink(url) {
   window.location.replace(url);
}

Note that .bind() requires a polyfill for some older browsers.


References:

Ian
  • 50,146
  • 13
  • 101
  • 111
  • @pXL You didn't **return a function** like I did. Look: http://jsfiddle.net/pQGKv/2/ – Ian May 15 '13 at 21:17
  • @bfavaretto I think they're trying to prove my second example doesn't work, but they didn't implement it correctly – Ian May 15 '13 at 21:18
  • @pXL No it shouldn't. That's not how `setTimeout` works. I've already pointed it out - the first parameter must be a string (of JavaScript to execute) or a function **reference** – Ian May 15 '13 at 21:19
  • @pXL Cool, glad you understand it now :) – Ian May 15 '13 at 21:20