Buttons & functions assistance (solved)

Buttons & functions assistance (solved)
0.0 0


onclick="doFunction();" Is how i have seen people execute a certain function when that button is clicked. Is there anyway i can know this but when the button is clicked, the function is able to get me the ID of the button?



this is the context in which the event occurs, which is a DOM object, so you can access the DOM object’s attributes directly.

Note that inline event handlers (as opposed to document.querySelector('.myButton').addEventListener('click', (event) => /* your event handling logic here */)) are very, very bad practice outside of a few very specific situations, and you should avoid them if at all possible.


I’m lost? So what the code i’m supposed to use? What does ‘my button’ mean?


this.id is how you get the id inside the function you posted. If there are good reasons for you using inline handlers, then ignore the rest of this. Otherwise:

Inline event handlers are generally bad practice (not always, but kinda 99% of the time).

Putting the event handler in your JavaScript files is normally how it is done.

See https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

.myButton is literally like <button class="myButton", see https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector, but it could be getElementById and #myButton, just whatever your button is identified by, it’s an example because I don’t know what the ID or class of your button is


document.querySelector(’.myButton’).addEventListener(‘click’, (event) => ))

If i try to type anything in where you said to put the code, i get ‘unexpected token’

Even if that works, do i have to go through and put a class for every button?


So any ideas? Am i using thy code wrong?

I just tried -->

    function get() {
    var id = this.id

<button onclick="get()">ON</button> // undefined

I get undefined when i click the ‘on’ button. I get undefined, so the function is running, and it is sending to the console. If you wondering what all of this is for, its for the calculator --> https://codepen.io/Mike-was-here123/pen/PQOYjB


Update: I tried calling get() function and its still not working

<button onClick="get(this.id)">ON</button>
<script type="text/javascript">
              function get(id) {

This might help answering this. I couldn’t figure it out?


your code seems okay… cant figure out why not working from here. ? Can you provide a link where it is not working?


In the above code, this refers to the button element. It does not have an id, your get function will return “”.
If you had the following, then when you clicked on this particular button, “myButtonID” would be displayed in the console.

<button id="myButtonID" onClick="get(this.id)">ON</button>
<script type="text/javascript">
  function get(id) {


DanCouper suggestion with info given was good… reason didnt work was needed to remove end ) and add {} brackets like below

document.querySelector('.myButton').addEventListener('click', (event) =>{ /* */})

But this is not what you need for calculator buttons as above is best suited for a single button … randelldawson works for multiple buttons … but involves adding code inline to every button.

the code below adds a listener to the div surrounding all your buttons … when you click on a button inside the div it lets you know which button was clicked so you can do something when that button is clicked … might seem complicated at first so have a look at this page https://www.kirupa.com/html5/handling_events_for_many_elements.htm

Lol im used to using jquery which makes this type of thing so much easier but since i have started using react and vue i have to go back to vanilla javascript and having to relearn stuff like this … lots of fun

IMPORTANT to get the below code to run you need to add a unique id to each button eg id=‘8’ for button 8 id=‘ce’ for CE button etc etc … and it worked for me so it should work for you

var theParent = document.querySelector("#buttons"); // id of your surrounding div
theParent.addEventListener("click", doSomething, false); //adds click listener to this div
                                                         // and everything in it
function doSomething(e) {
  if(e.target.localName !== 'ul')  // dont want it to do anything if i click on the ul which
                                   // you have your buttons in 
    if (e.target !== e.currentTarget) { // if buttons clicked will now react and tell which
                                        // one was clicked
        var clickedItem = e.target.id;
        alert("Hello " + clickedItem);
      if(clickedItem === '8'){         //now i can use if statements to work on each specific button
        alert('You clicked 8');
        //do stuff here
      if(clickedItem === '5') {
        alert('You clicked 5');
        //do stuff here


Yes, this is the correct approach (also that React/Vue/etc exist to make doing this stuff easy peasy). You don’t need a unique ID either, although that or a data attribute or whatever is probably the best bet, you can just check what the value of the button is, event.target gives you access to all the attributes.

document.querySelector('.calculatorKeypad').addEventListener('click', logStuff)

function logStuff(event) {
  const buttonValue = event.target.textContent;

  switch (true) {
    case ['1','2','3','4','5','6','7','8','9','0'].includes(buttonValue):
      console.log(`Number pressed, number is ${buttonValue}`);
    case ['+','-','/','*'].includes(buttonValue):
      console.log(`Operator pressed, operator is ${buttonValue}`);
    case '=' === buttonValue:
      console.log(`Equals pressed`);

Also @John-freeCodeCamp here are three slightly different ways of defining the event listeners: https://codepen.io/DanielCouper/pen/VQQWQX


Okay so here is what happened:

I did try @DanCouper ’ s code (Buttons & functions assistance) and it wasn’t working, as i was getting unexpected token when i tried inputting my code.

It was a small error, but i couldn’t get that working so i forgot to add ID’s to the buttons. So when i went to use other code like Buttons & functions assistance i was getting "" in the console, because there was no ID. I thought something was wrong, so i came back here asked why.

Thanks everyone for the help, i did give Dan the solution as his this.id recommendation works. Also thanks for the Pen.

I was thinking of something like Buttons & functions assistance . I would just test if isNaN()on my ID, and go further from it.


Guys also real quick. I’m highly confused on why history is undefined???

var nonDouble = ["*", "/", "-", "+", "^", "=", "neg", "right", "sq", "left"];
var equation = [];
var history = []; 
function get(id) {
  history.push(id); // Not a function
  console.log(history); // undefined


Weird. It works when you define your variables inside your function. Like this:

function get(id) {
  var history = [0];

Not sure why this is, have to look a little bit more. Any idea @DanCouper?


Possibly it’s because of being inline, if that’s still the case? Maybe try window.history = [] then window.history.push and console.log(window.history) @john-freeCodeCamp?? On phone so can’t check atm


History is just the name of the array.

I’m calling the get() function from the buttons, so maybe that is just not activating?

Here is my codepen, ill leave code unchanged. https://codepen.io/Mike-was-here123/pen/PQOYjB

I put a comment where the the code i just put is.

@DanCouper ‘Not a function’


@John-freeCodeCamp please see what I mentioned above. For some reason, history is undefined in your function. when a variable is undefined, there are no functions on it. For a fix right now, put the variable declarations inside the function like this:

function get(id) {
  var nonDouble = ["*", "/", "-", "+", "^", "=", "neg", "right", "sq", "left"];
  var equation = [];
  var history = [];

  var recent = history[history.length - 1];
  for (let i of nonDouble) {
    console.log(recent, history);
    if (recent === i) {
      $("#output").html("Syntax Error");
      setTimeout(function() {
      }, 1000);


No, it resets the value of the variables each time i push a button. So i cant make a history of buttons presses, meaning i can’t check if adding a item to the equation would result in a Syntax error (hint nonDouble)


Ah, I see, my bad. I will look at the code again soon.


If you add $( document ).ready(function() { to the code you get 'get is not defined' (console).

This happends if i do it in both HTML and the designated section i codepen.