0

htmlfile:

<!DOCTYPE html>
<head>
    <script src="script.js"></script>
</head>
<body>
    <div class="q" id="cooki" onclick="cookie()">Accept!</div>
</body>

js:


function cookie() {
    alert("hi");
}

and I even tested with console.log, I used script source in body tags , nothing worked

Z3N1X
  • 47
  • 8
  • @jabaa — No, it isn't reserved. `document.cookie` is predefined and is what `onclick` is trying to access (because `onclick` is awful) so the (successfully defined) `window.cookie` never gets a look-in. – Quentin Jun 06 '22 at 14:39
  • @Quentin To be honest, I didn't understand the technical details. I only knew how to fix it. With you explanation I understand why I can use the function in the JavaScript code, but not access it from HTML. – jabaa Jun 06 '22 at 18:26

1 Answers1

-3

Hi @Z3N1X Welcome to Stackoverflow. To fix your issue try renaming your function to something else, since how all of the comments below the answer has said(Thanks for correcting me) when you use the cookie name in the function or variable the onclick thinks your trying to use the document.cookie function. that's why this is happening.

Sasen Perera
  • 473
  • 1
  • 5
  • 12
  • 3
    This is not true. `cookie` is not reserved in JS. – trincot Jun 06 '22 at 14:34
  • Hello, Thank you so much, It Worked! Its so crazy that it was only a name problem , I searched the whole web for it ! – Z3N1X Jun 06 '22 at 14:36
  • 3
    This answer is **wrong**. See the duplicate question. `onclick` is trying to access `document.cookie` instead of `window.cookie`. – Quentin Jun 06 '22 at 14:39
  • @kiranvj — That particular error is because you're testing the code in a sandboxed iframe. Normally you'd get a "cookie is not a function" error because there's a predefined property in the scope of `onclick` attributes. – Quentin Jun 06 '22 at 14:42
  • ok. so the browser just thinks that the `cookie` function might be a call to `document.cookie` property. Thanks for the info I will keep it in mind – Sasen Perera Jun 06 '22 at 14:45
  • I changes the answer according to your comments and some more research – Sasen Perera Jun 10 '22 at 14:43