Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace onclick function of an object using Javascript

How do I replace the destination URL on a button when using onclick?

<div id="my_button" onclick="window.location.replace('/destination1')">Button<div>

So it would look like this

<div id="my_button" onclick="window.location.replace('/destination2')">Button<div>

The following Javascript code doesn’t work though. Why?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<script>
document.getElementById("my_button").onclick="window.location.replace('/destination2')"
<script>

>Solution :

onclick that you have used in tag – is html event attribute, but onclick in tag, that you also tring to change – is div object property.

Both are like "onclick", but it’s not the same.

So, if you want to make thing work, do this:

document.getElementById("my_button").onclick = () => window.location.replace('/destination2');

onclick div property need function(callback) not a string

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading