Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I bind a click to an anchor without a framework (javascript)

I know this is easily done in jQuery or any other framework, but that's not really the point. How do I go about 'properly' binding a click event in pure javascript? I know how to do it inline (I know this is terrible)

<a href="doc.html" onclick="myFunc(); return false">click here</a>

and this causes my javascript to execute for a JS enabled browser, and the link to behave normally for those without javascript?

Now, how do I do the same thing in a non-inline manner?

like image 215
Stomped Avatar asked Jun 03 '10 13:06

Stomped


People also ask

How do you trigger a click element?

The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.

What method can you use to bind an event to an element?

bind() method is used for attaching an event handler directly to elements.

How do I trigger a click event without clicking?

If you want native JS to trigger click event without clicking then use the element id and click() method of JavaScript.


2 Answers

If you need to assign only one click event, you can assign onclick:

If you have an ID:

myAnchor = document.getElementById("Anchor");
myAnchor.onclick = function() { myFunc(); return false; }

you can also walk through all anchors:

anchors = document.getElementsByTagName("a");

for (var i = 0; i < anchors.length; i++) {   

 anchors[i].onclick = .....

}

There's also a document.getElementsByClassName to simulate jQuery's class selector but it is not supported by all browsers.

If it could be that you need to assign multiple events on one element, go with addEventListener shown by @Jordan and @David Dorward.

like image 123
Pekka Avatar answered Oct 11 '22 00:10

Pekka


The basic way is to use document.getElementById() to find the element and then use addEventListener to listen for the event.

In your HTML:

<a href="doc.html" id="some-id">click here</a>

In your JavaScript:

function myFunc(eventObj) {
  // ...
}

var myElement = document.getElementById('some-id');
myElement.addEventListener('click', myFunc);

Or you can use an anonymous function:

document.getElementById('some-id').addEventListener('click', function(eventObj) {
  // ...
});
like image 25
Jordan Running Avatar answered Oct 10 '22 22:10

Jordan Running