Home > Software design >  Replace onclick function of an object using Javascript
Replace onclick function of an object using Javascript

Time:06-05

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?

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

CodePudding user response:

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

CodePudding user response:

A simple way to do it would be by adding a listener and preventing the default behavior of the event

document
  .getElementById('my_button')
  .addEventListener('click', function (event) {
    event.preventDefault();
    window.location.replace('/destination2');
  });

working example

CodePudding user response:

element.onclick requires a function to be assigned and differs from the attribute <node onclick=""> where the content will be wrapped up in a function automatically.

If you want to change the attribute, make use of element.setAttribute("onclick", "...");

element.setAttribute("onclick", "window.location.replace('/destination2');");

Behaves similar to:

element.onclick = function() { window.location.replace('/destination2'); };

Another solution would be using the data-attributes which can be accessed by element.dataset.name.

Example:

<div id="my_button" data-path="/destination2" onclick="window.location.replace(this.dataset.path);">Button</div>

And to change it:

my_button.dataset.path = "/otherPath";
  • Related