Matthieu
Matthieu

Reputation: 16407

Redirect links on a webpage to a javascript function

I am trying to redirect links on a web page and in this simple example, it just goes through a simple check for a cookie to be set.

Not sure if that's the right way to take care of this situation in the first place, and if I am going to run into problem when there are several links with the "download_link" class, but even right now, with only one of such link, the destination is set to undefined, it looks like the $(this) in the call to redirector is actually pointing the the whole HTML document instead of just the element I am trying to change...

    function redirect_link(e, destination) {
        if ($.cookie("contact_set") == "true") {
            window.location.href = destination;
        } else {
            alert("cookie not set");
        }
    }
    function redirector(destination) {
        alert("creating redirector to "+destination);
        return function(e) {redirect_link(e, destination)};
    }
    $(document).ready(function() {
        $('.download_link').click(redirector($(this).attr("href")));
        $('.download_link').attr("href", "#");
    });

Upvotes: 0

Views: 118

Answers (3)

ComFreek
ComFreek

Reputation: 29424

You're accessing $(this) from the scope of document's ready callback, so $this points to a HTMLDocument object!

$(document).ready(function() {
    var $downloadLnk = $('.download_link');
    $downloadLnk.click(redirector($downloadLnk.attr("href")));
    $downloadLnk.attr("href", "#");
});

As you requested it in your comment:

$(document).ready(function() {
  $('.download_link').each(function() {
    var $lnk = $(this);
    $lnk.click(redirector($lnk.attr("href")));
    $lnk.attr("href", "#");
  });
});

Upvotes: 2

adeneo
adeneo

Reputation: 318212

You can always use the target :

$(document).ready(function() {
    $('.download_link').on('click', redirector); //bind to function
    $('.download_link').attr("href", "#");
});​

function redirector(event) {
    alert("creating redirector to "+event.target.href); //event.target
    return function(e) {redirect_link(e, destination)};
}

But by the time your link is clicked the href will be # no matter what you use, as you set it to that value on the next line after the click handler ?

Upvotes: 0

Andreas Louv
Andreas Louv

Reputation: 47099

$(function() { // <-- Short for $(document).ready(function() {
    $('.download_link').each(function() {
        var $this = $(this);

        $this.click(redirector($this.attr("href"));
        $this.attr("href", "#");
    });
});

Upvotes: 1

Related Questions