Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the caller element in href javascript function?

I have an anchor tag element coming in the html like:

<a href="javascript:handleEvent(this, 'abc')"></a>

Now in the javascript function, I have written:

function handleEvent(sourceElement, txt) {
    console.log(sourceElement);
}

the consoled element is coming as the window in this case. I tried sourceElement.document.activeElement but it doesnt seem to work in chrome, where it is coming as body element.

I cannot change the structure of the anchor tag to 'onClick' function as this is coming from some other source. Is there some way to find the calling element in this scenario?

like image 889
Kop4lyf Avatar asked Feb 03 '14 10:02

Kop4lyf


People also ask

Can an A HREF call a JavaScript function?

In JavaScript, you can call a function or snippet of JavaScript code through the HREF tag of a link. This can be useful because it means that the given JavaScript code is going to automatically run for someone clicking on the link. HREF refers to the “HREF” attribute within an A LINK tag (hyperlink in HTML).

Can we pass function to href?

The anwer is: not possible.

Does Onclick work on link?

This is a type of JavaScript link - the onclick attribute defines a JavaScript action when the 'onclick' event for the link is triggered (i.e. when a user clicks the link) - and there is a URL present itself in the onclick attribute.


1 Answers

The real answer here is to change the HTML, which you've said you can't do. I'd push back on that if you can. If you're writing the function, and the function name is in the HTML, how is it you can't change the HTML??

But if you really, really can't, you can update the DOM once it's loaded:

var list = document.querySelectorAll('a[href^="javascript:"]');
var x, link;
for (x = 0; x < list.length; ++x) {
    link = list[x];
    link.onclick = new Function(link.href.substring(11));
    link.href = "javascript:;";
}

Live Copy | Live Source

This is fairly naughty, as it uses the Function constructor (which is very much like eval), but if you trust the source of the HTML, that should be okay.

Or of course, if you don't have to use whatever was in the href to start with, just hook up your event handler in the code above and don't use new Function.

like image 165
T.J. Crowder Avatar answered Sep 28 '22 00:09

T.J. Crowder