I need to set a variable's value based on the href of a clicked link.
I know that I can set the variable using an event listener that would run this when the link is clicked
var x = document.getElementById("myAnchor").href
But that is set to a single element. I need it to work dynamically based on which link is clicked. For example:
<a href="/link1">Partner A</a>
<a href="/link2">Partner B</a>
<a href="/link3">Partner C</a>
// function to attach click event to all links
function attachClickEvent() {
var linklist = document.getElementsByTagName('a');
var listLength = linklist.length;
var i = 0;
for (; i < listLength; i++) {
linklist[i].addEventListener("click", ClickedLinkEvent);
}
}
window.onload = attachClickEvent;
// function that creates click event
function ClickedLinkEvent() {
var anchor = obj.href;
console.log(anchor);
if (anchor.includes('clientdomain')) {
//do nothing
} else {
SendLinkEvent();
}
}
// function to run on click event
function SendLinkEvent() {
ga('send', {
hitType: 'event',
eventCategory: 'Affiliate Link',
eventAction: 'Click',
eventLabel: anchor
});
}
The anchor variable needs to be set to /link1 if Partner A is clicked, but /link2 if Partner B is clicked.
So, is there a way to do this with vanilla JS?
obj
inClickedLinkEvent
, usethis
.this
can point to different things, you don't have full control over it. When event is fired, it contains all event details. Try addinge
argument to the handler:ClickedLinkEvent(e)
. And check what is insideconsole.log(e);
this
will refer to the element which is the current target of the event.