Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does custom function create an error but console.log doesn't on click event?

Tags:

javascript

I have two identical <div> elements with different listeners onClick event.

function onclick() {
    console.log("onclick");
}
.some-styles {
  margin: 10px;
  border: 1px solid black;
}
<div 
  id="fisrt" 
  class="some-styles" 
  onclick="onclick()"
>
  Click the text to see in the console
</div>
<div 
  id="second" 
  class="some-styles" 
  onclick="console.log('without error')"
>
  Click the text to see in the console
</div>

The #first <div> uses the custom function onclick() which creates Uncaught RangeError: Maximum call stack size exceeded

The #second <div> uses console.log() function which doesn't create any error.

Regarding to the above info I have one question:

1) Why does the custom function create the error and console.log doesn't?

like image 558
Roman Roman Avatar asked Dec 07 '25 11:12

Roman Roman


1 Answers

When you use onxxx attributes to create event handler functions, you get a function constructed with a complicated scope. Among the things that will be in scope for the code of your handler function (that is, the code in the attribute text) is the element involved; in this case the <div>. All the properties of the <div> will be available as local symbols to your event handler code, notably including the onclick property.

Thus your code is not calling the function you've declared as (presumably) the global symbol onclick, it's calling the onclick function registered with the <div>, which is of course your handler code. It's therefore an infinite recursive call that overflows the stack.

If you change the name of your handler function to romanRoman() or something else that doesn't exist as a property on the clicked element or any enclosing <form>, then things will work better.

like image 114
Pointy Avatar answered Dec 09 '25 23:12

Pointy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!