0

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?

3
  • Instead of obj in ClickedLinkEvent, use this. Feb 13, 2020 at 17:45
  • this can point to different things, you don't have full control over it. When event is fired, it contains all event details. Try adding e argument to the handler: ClickedLinkEvent(e). And check what is inside console.log(e);
    – Vlad DX
    Feb 13, 2020 at 17:48
  • 1
    @VladimirSerykh By spec, when a function is attached as shown in the code in the OP, this will refer to the element which is the current target of the event. Feb 13, 2020 at 17:54

2 Answers 2

3

If you adjust the ClickedLinkEvent method declaration and add an argument to the method signature, then you will have the event object. The event object has a target parameter. If I understood you correctly, this is what you need. Don't you?

function ClickedLinkEvent(e) {
    console.log('hello', e);
    var anchor = e.target.href;
    console.log(anchor);
    if (anchor.includes('clientdomain')){
       //do nothing
    }
    else {
         SendLinkEvent(anchor);
    }
}
0
0

You can set custom attributes to the a element like this:

<a href="..." id="myAnchor" data-partner="your_important_data_here">Link A</a>

Then in your js file:

var data_partner= document.getElementById('myAnchor').getAttribute('data-partner');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.