0

I am trying to delay the link attrib so that it is applied after the content has faded out. But adding a timeout function does not work. Any ideas?

$(function () {
    $(".layout a").click(function () {
        setTimeout(function () { $("link:first").attr("href", $(this).attr('rel')); }, 500)
    $.cookie("Layout", $(this).attr('name'), { expires: 365, path: '/media', secure: true });
    $('.content, .searchresults').fadeOut(500).delay(500).fadeIn(275);
        window.scrollTo(0, 0); // Scroll Window back to Top
        return false;
    });
});

2 Answers2

0

Instead of setting a timeout to correspond to a delay you can assign a callback to the fadeOut function:

$(".layout a").click(function () {
    $.cookie("Layout", $(this).attr('name'), { expires: 365, path: '/media', secure: true });
    $('.content, .searchresults').fadeOut(500, function() {
        $("link:first").attr("href", $(this).attr('rel'));
    }).fadeIn(275);

    window.scrollTo(0,0);
    return false;
}

Look at the jQuery reference for more info: http://api.jquery.com/fadeOut/

I've generally had little to no luck altering a stylesheet loaded through a link tag through javascript though.

David Hamp
  • 151
  • 3
0

You are being defeated more by the scope of this than the timing.

The expression

$(this).attr('rel');

is fine in itself but inside a setTimeout function, this no longer refers back to the clicked element.

Good news is that the problem is easily overcome by assigning $(this).attr('rel') to a local variable at a suitable point where this still refers to the correct object.

In addition, to guarantee the timing, you can move the would-be setTimeout function to make it a callback to the fadeOut() expression.

Adding these two things together, the code is as follows :

$(function () {
    $(".layout a").click(function () {
        var rel = $(this).attr('rel');
        $.cookie("Layout", $(this).attr('name'), { expires: 365, path: '/media', secure: true });
        $('.content, .searchresults').fadeOut(500, function() {
            $("link:first").attr("href", rel);
        }).delay(500).fadeIn(275);
        window.scrollTo(0, 0); // Scroll Window back to Top
        return false;
    });
});
Beetroot-Beetroot
  • 18,022
  • 3
  • 37
  • 44
  • Your example works after correcting a typo in $(that).attr('rel') to $(this).attr('rel') .. thank-you for your help! –  Jan 29 '13 at 21:24
  • Whoops, I played with two different approaches in the editor and ended up posting a hybrid. Well worked out. Corrected above. – Beetroot-Beetroot Jan 29 '13 at 21:34