views:

38

answers:

3

I need to change the href of any local link when it is clicked on. I've worked out how to select the correct links and create the new url, but not sure how to change the location. I need to be certain that any other click events have also run, so I can't just change the location immediately.

var my_host = 'example.com';
$(document).click(function(e) {
    if(e.target.hostname == my_host)
    {
        alert(e.target.protocol + "//" + e.target.hostname + "/#" + e.target.pathname + e.target.search);
        //...
    }
});

This is related to my earlier question.

+2  A: 

You can bind the event on your local links like this and use the attr method to change the href:

$('a[href*="yourdomain.com"]').click(function(){
  // your code before changing href
  $(this).attr('href', 'new url here');
});

Replace yourdomain.com with your own domain so that the above code only targets your local links.

Sarfraz
Thanks. You've answered my question, and made the code shorter. However, you've also introduced a bug; If the domain was elsewhere in the path, eg as a return url in the query string, this would be erroneously triggered.
SystemicPlural
@SystemicPlural: You can find out url stuff using `document.location.search` and extract the part accordingly.
Sarfraz
A: 

This is completely untested, but should get you where you're going:

var site = "http://yourdomain.com";

// Match anchor tags with an href value that starts with your
// site URL, or that start with / which are relative URLs (also
// your site).
$('a[href^="' + site + '"] a[href^="/"]').click(function(){
    var url = $(this).attr('href');
    if (url.indexOf(site) != -1) {
        url = site + "/#" + url.replace(site, ""); // Quick dirty way to get the path component of the URL
    } else {
        url = "/#" + url;
    }
    $(this).attr("href", url);
});

Note that I read your other question, and I personally don't understand why you would do this on a click event, instead of just replacing all the href values as soon as the page is loaded.

mellowsoon
This does not work for https links. The reason for doing it onclick is that it is a lot less work to replace one link than dozens. Also, in my case, content is loaded dynamically - so a single solution is ideal.
SystemicPlural
The previous answers 1) Didn't work, and 2) Didn't take into account relative URLs. You could have added a few characters to my code to handle https hahaha
mellowsoon
P.S. Not sure what you're doing, but you would want to change all the URLs (not just the clicked URLs) if you want search engine spiders to index the correct URL.
mellowsoon
A: 

Credit to Sarfraz: here is the answer without the bug.

var my_host = "example.com";
$('a[href^="/"], a[href^="http://' + my_host + '"], a[href^="https://' + my_host + '"]').click(function(e){
    $(this).attr('href', e.target.protocol + "//" + e.target.hostname + "/#" + e.target.pathname + e.target.search);
});
SystemicPlural