Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why function with name "clear" doesn't work in JavaScript [duplicate]

I wrote a small HTML file. I added few buttons with onclick attributes and wrote my functions inside a "script" tag. All of them are working perfect but the function with name "clear" doesn't work.

HTML:

<div>
  <input type="button" value="Copy" onclick="copy();" />
  <input type="button" value="Clear" onclick="clear();" />
</div>

JavaScript:

  function copy() {
    console.log("copy");
    navigator.clipboard.writeText(
      document.getElementById("result_box").value
    );
  }

  function clear() {
    console.log("clear");
  }

When I click on both of this buttons browser console shows me only one message: "copy". No errors.

If I change the name of this function it starts working. I don't understand why is it happening. I thought the word "clear" is reserved word of JavaScript but I couldn't find this word in the list of keywords in documentation. Any ideas?

like image 652
Gregory Avatar asked Oct 26 '25 10:10

Gregory


1 Answers

The reasoning behind this is that clear() inside a button calls document.clear instead of your clear.

like image 168
GoldenretriverYT Avatar answered Oct 28 '25 23:10

GoldenretriverYT



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!