Home > database >  what happen when you use onclick={} instead of onclick=""?
what happen when you use onclick={} instead of onclick=""?

Time:07-20

<script>
    function hello(val)
    {
        alert(val);
    }
</script>
<button onclick="hello('hello')"">hello</p> <!-- works and prints hello -->
<button onclick={hello()}>hello 2</button> <!-- works and prints undefined -->
<button onclick={hello("hello3")}> hello 3</button> <!--also works even though intellisence put a squigly red line under the first quote "-->
<button onclick={hello("does not work")}> hello 3</button> <!-- does not work, error is show in console Invalid or unexpected token -->

I know that inline js should be treated carefully, im trying to explain that to other people with this example, however i dont what is happening underneath.

My explnation is that if you change something that is expected you would get undesired results, however i feel that my explanation is superficial and not enough, so could someone explain what is happening underneath that is casuing this wierd behaviour?

CodePudding user response:

If it is only about HTML and no framework is involved, then what you observe is partially explained in HTML attribute with/without quotes

An attribute value can either be enclosed in " or ' or consist of a value that is not enclosed by quotes, and such a value must not contain spaces.

So <button onclick={hello()}>hello 2</button> it is equivalent to <button onclick="{hello()}>hello 2</button> and onclick has the value {hello()}, which is valid JS (the hello() is just within a block).

For <button onclick={hello("does not work")}> the value ends at the first space so it is equivalent to <button onclick="{alert(&quot;hel" lo3")}="">, there onclick has the value {alert(&quot;hel and that's not valid JS.

  • Related