I have some html on test.html and JavaScript code on test.js. I put alerts in the functions to test it, and I’m constantly getting only the first alert (1232c) regardless of which hyperlink I click on. I don’t understand, I have a reference to a specific anchor element using its id, why does .onclick think they are all the same if they have the same URL (form.html). I want only function test to happen if I click the hyperlink with id 1232c, and function test2 to happen if I click the hyperlink with id1232b.
function init () {
var jobID = document.getElementById("1232c");
var jobID2 = document.getElementById("1233b");
jobID.onclick = test("1232c");
jobID2.onclick = test("1233b");
}
function test(id) {
alert(id);
}
function test2(id) {
alert(id);
}
window.onload = init;
<a href="form.html" id="1232c">Apply</a>
<a href="form.html" id="1233b">Apply</a>
3
Answers
You are calling your function before clicking
You have to assign a function, not a function call
You have a typo in that
jobID2
callstest()
and nottest2()
. As you describe it, that may be all you need.But, if you are trying to wire up on click handlers, you need to assign functions to the onclick property. What you have assigned is the return values after you call
test()
during window OnLoad. Something like this:or as @Konrad described, an anonymous function if you need to pass in that argument:
(I don’t believe the order of the function definitions is important due to hoisting)
An event listener requires a function to be assigned to it. Currently you’re assigning the result of calling those functions. Note: you don’t need two functions to deal with the clicks. Since you’re passing in an id as an argument just use
test
to cater for both events.Option 1
Assign a function to the listener that calls
test
when the event is fired.Option 1
Assign
test
directly to the listener, and log/alert the id from the clicked anchor.There are a couple of alternative approaches.
Approach 1
Use
querySelectorAll
to grab all the anchors.Iterate over the anchors and assign event listeners to them.
The handler accepts an event
e
. It first prevents the anchor from its default action (going to the page indicated by the href), and then logs the id of the element that was clicked.Approach 2
Use event delegation. Add one listener to a containing element (a
section
perhaps as in this example), and assign it a handler that deals with all the click events from its child elements.Use
querySelector
to grab the container.Add one event listeners to the container.
The handler accepts an event
e
. It first checks to see what element was clicked. If it’s an anchor it prevents the anchor from its default action, and then logs the id of the anchor that was clicked.