I-CRE8 I-CRE8 - 3 months ago 10
jQuery Question

Converting jQuery Code to detect clicks on links with a specific class to Native JavaScript

ok so I can achieve what I am looking to do using jQuery very easily using the following code:

<script type="text/javascript">
// <![CDATA[
$('.pnTrig').on('click', function(e){

e.preventDefault();
var id = $(this).attr('href').split("_").pop(); // get last character of string
console.log(id); // check correct character is returned
P7_TP3ctrl('p7TP3_1',id); // controls to show accordian panels

});
// ]]>
</script>


What I would like is for someone to show me how to convert this jQuery code to native JavaScript please.

Answer

Here is a documented vanilla Javascript version.

function clickHandler(event) {
  // execute preventDefault() if don't want the link to be followed (default browser behavior)
  event.preventDefault();

  // get the event target (what `this` would refer to in jQuery) 
  var target = event.target;
  // same as before
  var id = target.href.split('_').pop();
  // same as before
  P7_TP3ctrl('P7_TP3', id);
}

// get all elements with `pnTrig` class
var triggers = document.querySelectorAll('.pnTrig');

// apply the event handler to all matching elements
for (var i = 0; i < triggers.length; i++) {
  // attach the event handler (don't define the event handling function here)
  triggers[i].addEventListener('click', clickHandler, false);
}

function P7_TP3ctrl(label, id) {
  console.log("Clicked id: ", id);
}
<a href="/foo/some_id_1" class="pnTrig">Link One</a>
<a href="/foo/some_id_2" class="pnTrig">Link Two</a>