1

Quote from Wikipedia:

JavaScript, allow programs to create new code at run-time and execute it using an eval function, but do not allow existing code to be mutated.

Does that include the JS code in event handler attributes and in hrefs with the javascript: prefix? Can you change these attributes at run-time with JS code or not?

Can I create a new <script> element at run time? If I define a new version of a function in there, what happens? Will the browser prefer my new function to the old one?

If I can’t change an event handler attribute, can I add a new event handler attribute which takes precedence over the old? W.g. an onmouseover where the old one is onclick? And change the parts in the call somewhat?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Henrik2
  • 271
  • 1
  • 2
  • 9

2 Answers2

2

You can change an event handler attribute. That's part of the DOM, not Javascript. So if you do:

document.getElementById("someButton").onclick = someFunction;

that will change what happens when you click on the button.

You can also redefine functions, so if the function is called by its name, the new definition will be executed from then on.

But if you pass a function reference, the redefinition has no effect on whatever is using that reference.

As an example, if you do:

<button type="button" onclick="myFun()">Click Me</button>

If you redefine myFun, clicking will use the new definition.

If you instead do:

<button type="button" id="myButton">Click Me</button>
<script>
document.getElementById("myButton").addEventListener("click", myFun);
</script>

redefining the function will not affect that button. The myFun variable is evaluated to get the function object at the time you call addEventListener(), and redefining the function doesn't do anything to that object.

You could change the JS to:

document.etElementById("myButton").addEventListener("click", function() {
    myFun();
});

and then it will look up the function definition every time the anonymous function is called.

Barmar
  • 741,623
  • 53
  • 500
  • 612
1

Yes you can overwrite event handlers and hrefs including JS code by setting the attribute on the html element.

Can create a script element. document.createElement("script") synchronously

Sean Sherman
  • 327
  • 1
  • 16