Help with basic practice running a function on click

Hello,

I’m trying to practice outside of the course lessons. I’ve just tried to write something so that when I click a button it will change the colour of text on a page:

const btn = document.getElementById("colorButton");
const colorChangeElements = document.getElementById("colorChange");

function changeColor (color) {
    colorChangeElements.style.color = color;
}

btn.onclick = changeColor("red");

I’m finding that the colour is changing before clicking the button. ChatGPT is advising to make the following change to the code because “rhe reason the element’s color is changing before you’ve clicked the button is because you’re invoking the changeColor function immediately when you assign it to btn.onclick.”

// Assign a function to be called on click
btn.onclick = function() {
    changeColor("blue");
};

But I don’t understand why I need to do this when in this lesson, the change the background colour, the function is just called. Any explanation greatly appreciated.

Thanks.

1 Like

Can you post all your HTML code please, plus your complete JS and any CSS.

When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read . You can also use the “preformatted text” tool in the editor ( </> ) to add backticks around text

2 Likes

Welcome back to the forum @brooker

When JavaScript sees the round braces, it executes the code, even though it is attached to an .onclick property.

Try changing

to an arrow function.

Happy coding

1 Like

Thanks both.

Here’s the HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <link rel="stylesheet" href="style.css">
</head>
<body>
   <p id="colorChange">Hello</p> 
   <button id="colorButton">Click me</button>
   <script src="script.js"></script>
</body>
</html>

There is no css

@Teller - ok so that works but why didn’t that need to be done in this lesson?

Hi

I changed your code to the Syntax mentioned on this page using an ordinary function. It worked for me. I think your syntax was wrong on the function on the object.onclick - see how they have done it? You could add a reset button to improve it.

https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onclick_dom
1 Like

You assign a function definition to the event attribute. Calling the function would assign its return value, which isn’t a function. It has to be the function definition.


A standard event handler function is automatically passed the event object, which you can use by giving the handler function a parameter.

<button>Click me</button>
const btn = document.querySelector("button");

function clickHandler(evt) {
  // evt contains the event object that is automatically passed
  console.log(evt.target.innerText); // Click me
}

btn.onclick = clickHandler; // no arguments but still has access to event object

If you need to pass the event handler a custom argument, you usually wrap it inside another function. It doesn’t have to be an arrow function.

const btn = document.querySelector("button");

function clickHandler(evt, someCustomArgument) {
  console.log(someCustomArgument + evt.target.innerText); // The text of the button is Click me
}

btn.onclick = function (evt) {
  clickHandler(evt, "The text of the button is ");
};

Here the event handler is an anonymous function definition which, when called by the click event, in turn will call the clickHandler function. The clickHandler is explicitly called with the event and a custom argument.

Again, it is important to understand that the onclick event attribute is still assigned a function definition, and it can’t be a function call…well, not unless the called function returns a function.

const btn = document.querySelector("button");

function wrapperFn(someCustomArgument) {
  return function clickHandler(evt) {
    console.log(someCustomArgument + evt.target.innerText); // The text of the button is Click me
  };
}

btn.onclick = wrapperFn("The text of the button is ");
1 Like

Ok thanks all. This is a great help.

So, essentially typing the function name with no brackets is referencing the function where as including the () calls the function and calling the function was the mistake I was making. I think I need to re-read all this with a fresher head for it to make sense but thanks again! :raised_hands:

1 Like