I have an image and it initially does not do anything if a user clicks on it, is it possible that If the user clicks on another button, the onclick attribute of the image changes to some function so that if he clicks on image later, the onclick function assigned to image gets executed?

Problem -> When I click on button, a function is called in which I change the onclick attribute with the below code->

document.getElementById("chip").onclick=bet_amount_displayer(100);

Without even clicking on the image, this function is executed. And when the image is clicked, nothing happens!

I have also tried this ->

document.getElementById("chip").onclick="bet_amount_displayer(100)";

In this case, when user clicks on image, nothing happens.

1 Answers

3
Leibale Eidelman On

You set the onclick to whatever bet_amount_displayer(10) return instead of setting it to a function that calls bet_amount_displayer.

Use

document.getElementById("chip").onclick = function () {
    bet_amount_displayer(100);
};

Or

document.getElementById("chip").onclick = () => bet_amount_displayer(100);

Also, instead of set onclick I recommend you to use addEventListener and removeEventListener