jelly46
jelly46

Reputation: 243

Javascript code that reads if a link has been clicked

I have a simple bit of code (contained in a CMS and cant be edited) that and needs to be read by Javascript in the header if it has been clicked.

Here is the code

<div id="example" class="page-element-outer" style="text-align: left">
    <div class="page-element-inner" >
        <input type="image" name="Button1" id="Button" src="/getresource.axd?AssetID=16813" alt="Submit" style="text-align:left;" />
    </div>
</div>

Can you assist?

Upvotes: 0

Views: 103

Answers (1)

Christofer Eliasson
Christofer Eliasson

Reputation: 33865

You can select the element through its ID and attach a click-event listener using the addEventListener method.

document.getElementById("Button").addEventListener("click", callback, true);

function callback() {
   // Do some stuff in here when clicked
   alert("clicked");

   // Return false to prevent the browser default 
   // click-behaviour, if that is desired
   return false;
}

For legacy browsers

Older versions of IE doesn't support addEventListener, so for those you might need to do something like this:

var el = document.getElementById("Button");
if (el.addEventListener) {
  el.addEventListener('click', callback, false); 
} else if (el.attachEvent)  {
  el.attachEvent('onclick', callback);
}

Wait for the DOM to be ready

If you plan to run this in the head of your page, you'll need to wrap it a DOM-ready event listener as well, otherwise there is a change that the click event isn't attached to the element, as that element doesn't exist in the DOM when your script is run.

Upvotes: 1

Related Questions