Skip to content

setting the onclick value from doesn’t work

I have created a button in HTML
<button id = "back_button" type="button" onclick="" value="Home">Go Back</button>
And have the code in the <script> tag
document.getElementById("back_button").onclick = "redirect('" + previous_location + "')"

If I set that manually in the HTML it works fine, but when set via the script it doesn’t even run the function. I put a console.log to check and there was no output in the inspect element console or main

Does anyone know what I’m doing wrong or how I can change the value of the location of the button another way?

Answer

When you assign callback from the script, you must provide a function variable, not a string:

document.getElementById("back_button").onclick = redirect(previous_location)

But like this we would assign the result of redirect to the onclick, which should be a function. So create an anonymous function which calls redirect for you:

document.getElementById("back_button").onclick = function() { redirect(previous_location); }
// OR
document.getElementById("back_button").onclick = () => redirect(previous_location);