root
root

Reputation: 137

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?

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

Upvotes: 1

Views: 1098

Answers (3)

Christopher
Christopher

Reputation: 3687

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";

Upvotes: 0

Mero
Mero

Reputation: 763

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

Upvotes: 1

Haris Bouchlis
Haris Bouchlis

Reputation: 2566

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

Upvotes: 0

Related Questions