Bram Vanroy
Bram Vanroy

Reputation: 28437

Delay following link in jQuery

Because I want to display a short animation when a user clicks a link, I want to make sure that the animation is complete before redirecting. To do so, I thought I could set a simple time out to follow the link, like so:

$("a[href^='http://'], a[href^='https://']").click(function(e) {
    setTimeout(function() {
        window.location.href = $(this).attr("href");
    }, 1200);
    console.log($(this).attr("href"));
    e.preventDefault();
});

Apparently, it doesn't. Though I don't understand why. The console.log isn't called, but I'm pretty sure my selector is correct. What am I missing here?

Fiddle.

Upvotes: 1

Views: 591

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

It is looking like a bug in the load method in jQuery edge, if you see the below code it is calling off = url.indexOf(" "), but when $(window).load(function(){}) the value of url is a function which does not have the indexOf property.

jQuery.fn.load = function( url, params, callback ) {
    if ( typeof url !== "string" && _load ) {
        return _load.apply( this, arguments );
    }

    var selector, type, response,
        self = this,
        off = url.indexOf(" ");

    if ( off > -1 ) {
        selector = jQuery.trim( url.slice( off ) );
        url = url.slice( 0, off );
    }

    // If it's a function
    if ( jQuery.isFunction( params ) ) {

        // We assume that it's the callback
        callback = params;
        params = undefined;

    // Otherwise, build a param string
    } else if ( params && typeof params === "object" ) {
        type = "POST";
    }

In the jsfiddle you can see an error like Uncaught TypeError: url.indexOf is not a function. It is because by default jQuery adds the script in a dom ready handler. If you change the script location to head/body then use dom ready handler as given below it is working fine

jQuery(function($){
    $("a[href^='http://'], a[href^='https://']").click(function(e) {
        setTimeout(function() {
            window.location.href = $(this).attr("href");
        }, 1200);
        console.log($(this).attr("href"));
        e.preventDefault();
    });
})

Demo: Fiddle

Upvotes: 1

Related Questions