+ 1

I am trying to create a button and automatically attach an on click event

I am trying to create a button but doesn't attach the onclick event. What am I doing wrong? https://code.sololearn.com/WROAEdBZ0Vg2/?ref=app

24th Dec 2022, 11:02 AM
Graeme Adamson
Graeme Adamson - avatar
7 Answers
0
Best way is to use addEventListener, you can have many listener at same element yourBtn.addEventListener("click", () => { // function to run on btn click }) yourBtm.addEventListener("keydown", () => { // function to run when user click key on keyboard... }
24th Dec 2022, 2:12 PM
PanicS
PanicS - avatar
+ 1
onclick attribute is needed because it tells the browser what to do when the button is clicked
24th Dec 2022, 11:19 AM
Lamron
Lamron - avatar
+ 1
Graeme Adamson you are trying to assign a string value to the onclick event, which is incorrect. The onclick event should be assigned a function, not a string. You are passing the event array as an argument to the domCreateAButton function, but you are not actually using it in the function. Instead of assigning the onclick event to the button directly, you should loop through the event array and assign the events to the button.
24th Dec 2022, 11:23 AM
CalviŐ˛
CalviŐ˛ - avatar
+ 1
Graeme Adamson If you only want to attach a single event to the button, you can simply use the addEventListener method to attach the event to the button which is a more proper way.
24th Dec 2022, 11:46 AM
CalviŐ˛
CalviŐ˛ - avatar
0
Calvin I know I sent an array but using the values. The reason is I am trying to get things working first before looping thru the Array
24th Dec 2022, 11:27 AM
Graeme Adamson
Graeme Adamson - avatar
0
Yes but I want to add that functionality once I can get an event added that works Building up from what I know to be able to have multiple events added at the same time
24th Dec 2022, 11:54 AM
Graeme Adamson
Graeme Adamson - avatar
0
Seem to have got it sorted out
28th Dec 2022, 4:18 PM
Graeme Adamson
Graeme Adamson - avatar