0

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?

2
  • I think you meant document.getElementById("back_button").onclick = () => redirect('" + previous_location + "') Commented Feb 9, 2021 at 14:16
  • That doesn't seem to work either Edit; That did work, i just didn't remove the quotes Commented Feb 9, 2021 at 14:18

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.