Question

I'm new to JavaScript and am unsure how to do the following:

I've got two links with the same css "class" but different "name" attributes. I need to perform different functions to each one individually when clicked using unobtrusive Javascript. Is there anyway to do this?

Example code:

<a class="ClassName" name="link1">Link 1</a>
<a class="ClassName" name="link2">Link 2</a>

Lets say I need to output "This is link 1" to the console when I click link 1. And "this is link 2" when Link 2 is clicked.

Was it helpful?

Solution

Attach an event handler to the elements, and just check the name and do whatever you'd like

var elems = document.querySelectorAll('.ClassName');

for (var i=elems.length; i--;) {
    elems[i].addEventListener('click', fn, false);
}

function fn() {
    if ( this.name == 'link1' ) {

        console.log('This is link1');

    } else if ( this.name == 'link2' ) {

        console.log('This is link2');

    }
}

FIDDLE

OTHER TIPS

You can do like in this JS Fiddle Demo , its pretty simple:

JS:

var anchorTags = document.querySelectorAll('.ClassName');
for (var i = 0; i < anchorTags.length; i++) {
    anchorTags[i].onclick = function() {
        alert(this.innerHTML);
    }
}

Hope this helps.

It's not very performant but you can use name selectors. .className[name=link1] however, if you have multiple links the best way to handle something like this is to use event delegation. It's really easy if you have access to jquery

I would do something like

parent.on('click', '.ClassName', function(event) {
  var button = $(this),
      name = button.attr(name);

  switch(name):
    case link1
    case link2
    ...
});

this way you don't have to assign individual events to the different links. You could also do something like this without event delegation if you really wanted to it would just be changing it to

 var links = $('.ClassName');
 links.on('click', function() {
   ...
 });

Keep in mind that the latter will attach an eventHandler to each link.

If you don't have jQuery you can still do this you just need to grab the elements differently and handle attachEvent vs addEventHandler. Also, applying the delegation will require delving into the event.currentTarget object.

something like:

var parent = document.getElementById('parentid');
parent.addEventListener('click', function(event) {
  if (event.currentTarget.getAttribute('class')indexOf('ClassName') > -1) {
    ... do stuff w/ that link here
  }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top