开发者

Perform a jQuery event before opening up a link

开发者 https://www.devze.com 2023-03-22 17:55 出处:网络
I have a simple javascript/jQuery related question: I have the following markup in my tumblr blog: <a href=\"/page/#\" class=\"pagination\">NEXT</a>

I have a simple javascript/jQuery related question:

I have the following markup in my tumblr blog:

<a href="/page/#" class="pagination">NEXT</a>

The # above changes according to which page the user is on. ie: # is variable, and cannot be static.

With jQuery, I would like to perform an effect (slideUp();, to be specific) before the new link is opened.

Is that possible?

I have tried both .click() and .mousedown(). Doesn't seem开发者_StackOverflow社区 to work, since when I click the link, the new page opens up before any effects take place.

I have heard of preventDefault(), but I'd like to shy away from that, for that would mean I must create a separate function to detect the page #, etc. (too much work~)


I recommend against doing that. Just let the user change pages.

However, if you really want to, what you need to do is indeed preventDefault (explicitly, or by returning false from your handler), do the slideUp, and then in the slideUp completion function, trigger the change in URL.

Like this:

$("a.pagination").click(function() {
    // Grab the link's href
    var href = this.href;

    // Slide up the content you want to slide up
    $("some_selector_here").slideUp(function() {
        // Slide is finished, navigate
        location.href = href;
    });

    // Prevent the default action of the link
    return false;
});


You just need to defer changing of page's url:

$('.pagination').click(function(){
    var link = this;
    $('.some-other-element').slideUp(500, function(){
        location.href = this.getAttribute('href');
    });
    return false;
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号