Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add parameters to an URL from a <a href> just clicked

Tags:

javascript

The scenario is a lot of html files with a lot more of links between them. When I call the first one of them (it would be the index), the link pass several parameters through the URL (we could call them preferences).

Now I want that, when clicking any of the several links of the page, those parameters would be added. So the problem would be similar to this other ( How to add parameters to a URL that already contains other parameters and maybe an anchor) but doing it just after clicking the link.

I know that one solution could be changing the onclick event on each link, but as there may be thousands of them, without a regular url format... I'm looking for a solution that could be on the script at the head; perhaps something relative to onbeforeunload event.

Anyway I couldn't find how to do it. Any ideas?

like image 216
rcerecedar Avatar asked Oct 08 '12 12:10

rcerecedar


2 Answers

This will append a string to anything containing an href-attribute when being clicked:

window.addEventListener("click", function(e) {
    var href = e.target.getAttribute("href");
    if(href) {
        location.href = href + "?q=stackoverflow";
        e.preventDefault();
    }
});​

Example here: http://jsfiddle.net/E5Q7P/

Won't work in < IE9

like image 135
Jan Sommer Avatar answered Nov 08 '22 11:11

Jan Sommer


Instead of changing the onclick-attribute of each link, or using the onbeforeunload-event, I guess one way would be to attach a clickevent-listener to all anchor-elements when the page loads. The callback could then intercept the browsers default behavior to follow the link. You could then get the src attribute of the a-element that was just clicked, add the desired preferences to the URL and then send the user to the proper location (including preferences) by setting window.location.href to the proper URL.

There is a great aricle on MDN about event-listeners, that I believe would be helpful to you. Note specially the section about older versions of IE

A very crude example of what it could look like:

function callback(e){
  // Get the src of the clicked a-element
  var src = this.src;
  // Add preferences to the url, this need 
  // improvement depending on your needs
  src += "?somesetting=foo";
  // Send user to the url with preferences
  window.location.href = src;
}

// Get all anchors on page
var anchors = document.getElementsByTagName("a");

// Loop over the elements and attach listener
for(i=0 ; i < anchors.length ; i++){
  // Extend with support for older IE if needed
  anchors[i].addEventListener("click", callback, false});
}​
like image 35
Christofer Eliasson Avatar answered Nov 08 '22 13:11

Christofer Eliasson