Link to home
Start Free TrialLog in
Avatar of MJ
MJFlag for United States of America

asked on

JavaScript- Detect when Anchor Tag Element is clicked? (ES5)

How to detect when element is Clicked using JavaScript?
<a data-target="#botwDisclosuresModal" data-toggle="modal" href="#botwDisclosuresModal"> Application Disclosures </a>

Open in new window

Thanks!
Avatar of leakim971
leakim971
Flag of Guadeloupe image

test page : https://jsfiddle.net/h8u2fgyo/

     var links =  document.getElementsByTagName("a");
     for(var i=0;i<links.length;i++) {
         if (links[i].dataset.target == "#botwDisclosuresModal" && links[i].dataset.toggle == "modal" && links[i].href.indexOf("#botwDisclosuresModal")>0) {
             links[i].addEventListener("click", function(event) {
                 event.preventDefault();
                 alert("you clicked on it!");
             });
         }
     }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
<a data-target="#botwDisclosuresModal" data-toggle="modal" href="#botwDisclosuresModal" onclick="function(){alert('clicked - you can also call a function here');"> Application Disclosures </a>

Open in new window


https://www.w3schools.com/jsref/event_onclick.asp
Avatar of MJ

ASKER

Sorry, Geoff! I should have mentioned that I can't modify the element in any way. I have to use a TMS.
what miss in my solutions?
Then add the event listener as suggested above 😊.  Using JQuery is the easiest by far.

Use $("[href=#botwDisclosuresModal]").click(function(){ //function code here });
You can detect if the tagName is anchor ('A') like this
HTML
<div><a data-target="#botwDisclosuresModal" data-toggle="modal" href="#botwDisclosuresModal">
   Application Disclosures
 </a></div><br/>
 <div data-target="#botwDisclosuresModal" data-toggle="modal" href="#botwDisclosuresModal">
   Application Disclosures Div Element
 </div>

Open in new window


JS script
document.addEventListener('click',function(a){
    if (a.target.tagName=='A'){
      console.log(true)
    // You can add your code here
    }else{
      console.log(false)
    }       
});

Open in new window


JSFiddle here
Avatar of MJ

ASKER

Thank you all!
you welcome!