How do I intercept link clicks in document? It must be cross-platform.
I am looking for something like this:
// content is a div with innerHTML
var content = document.getElementById("ControlPanelContent");
content.addEventListener("click", ContentClick, false);
function ContentClick(event) {
if(event.href == "http://oldurl")
{
event.href = "http://newurl";
}
}
Tracking link clicks on websites For websites, you can use Google Analytics. To do this, enable the analytics tools provided by Google and use their measurements to check all your clicked links arriving at the website. If you use marketing channels to mostly drive traffic to your website, this is a good place to start.
What about the case where the links are being generated while the page is being used? This occurs frequently with today's more complex front end frameworks.
The proper solution would probably be to put the click event listener on the document. This is because events on elements propagate to their parents and because a link is actually acted upon by the top-most parent.
This will work for all links, whether they are loaded with the page, or generated dynamically on the front end at any point in time.
function interceptClickEvent(e) {
var href;
var target = e.target || e.srcElement;
if (target.tagName === 'A') {
href = target.getAttribute('href');
//put your logic here...
if (true) {
//tell the browser not to respond to the link click
e.preventDefault();
}
}
}
//listen for link click events at the document level
if (document.addEventListener) {
document.addEventListener('click', interceptClickEvent);
} else if (document.attachEvent) {
document.attachEvent('onclick', interceptClickEvent);
}
for (var ls = document.links, numLinks = ls.length, i=0; i<numLinks; i++){
ls[i].href= "...torture puppies here...";
}
alternatively if you just want to intercept, not change, add an onclick handler. This will get called before navigating to the url:
var handler = function(){
...torment kittens here...
}
for (var ls = document.links, numLinks = ls.length, i=0; i<numLinks; i++){
ls[i].onclick= handler;
}
Note that document.links
also contains AREA
elements with a href
attribute - not just A
elements.
I just found this out and it may help some people. In addition to interception, if you want to disallow the link to load another page or reload the current page. Just set the href to '#' (as in internal page ref prefix). Now you can use the link to call a function while staying at the same page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With