views:

590

answers:

2

I need a javascript on a page that could catch an event whenever i click something and that click could lead to redirect, open in a new window, etc.

As links sometimes are not directly open a new window, they call a javascript function (window.open, document.location.href). Is it possible that I can catch them and edit the url.

Thanks.

A: 

You could achieve this using the click event of links. If you were using jQuery, it could go something like this:

$("a").click(function() {
    /* Open the site in a new window */
    var strNewURL = "http://example.com/redirect.php?id=" + this.href;
    window.open(strNewURL, "myFancyNewWindow");

    /* Stop the browser following the original link */
    return false;
});

This shows how you could add an extra bit to the front of the href to send the user there via your own redirect script.

If you only wanted to do this to certain links, you could refine the selector, e.g. $("#content a").

See also: https://developer.mozilla.org/En/DOM/Window.open and http://docs.jquery.com/Events/click.

Olly Hodgson
Ive rewrite the question. I felt I didnt explain it correctly. Hope this will give a good understanding on what I am exactly looking for. Thanks.
Ramiz Uddin
A: 

You could assign an onclick handler to the document.body, and detect which element has been clicked by using the event.target, this is basically doing event delegation.

By having the event target, you can know everything about the clicked element, like its tagName, and all the element attributtes:

document.body.onclick = function(event){
  if (event.target.tagName == 'A'){ //Handle anchors
    var url = event.target.href;
    // redirect, window.open, or whatever you want...

    event.preventDefault();
  }
}
CMS
Thanks. And what if there is a javascript function there that do some calculation and use window.open or window.location.href. Is there a way to catch such things?
Ramiz Uddin