-2
<!DOCTYPE html>
<html>
    <head>

    </head>
    <body>

        <div id="overdiv">

            <style>
            .cross{
                cursor:Default;
            }
            
            </style>
            
            <script>
              function close(){
              alert("why don't you work");
              }
            </script>
            
            <div id="lowerDiv">
              <a class="cross" onclick=close()>x</a>
            </div>
            
            </div>

    </body>
    </html>

I can not understand why the x's onclick doesnt work, even if i surround the x with a div...

Any way i can fix or any other way i should be doing this? I want to close a window by pressing the x, I know how to do that but i just cant get the onclick to work... any help is appreciated.

  • Duplicate of [JS function named `animate` doesn't work in Chrome, but works in IE](/q/28173800/4642212). Inline event handlers like `onclick` are [not recommended](/q/11737873/4642212). They are an [obsolete, hard-to-maintain and unintuitive](/a/43459991/4642212) way of registering events. Always [use `addEventListener`](//developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead. **This is one of the reasons why.** – Sebastian Simon Jul 06 '21 at 12:17
  • 1
    you need quotes: `onclick="function()"`, but should consider better alternatives to inline event handler (addEventListener). – Sleepwalker Jul 06 '21 at 12:24

3 Answers3

0

https://stackoverflow.com/users/479156/ivar

Ivar let me know that the problem was naming the function "close()", so i just had to name it a little different.

as explained here: onclick calling hide-div function not working

thank you Ivar!

-1

<a class="cross" onclick=close()>x</a>

This code has a problem with onclick function. You didn't specified the function. You need the make the function code between "" tags.

Please change the code like this:

<a class="cross" onclick="close()">x</a>
Arda Yasar
  • 66
  • 9
-1

I maid improvments to your code and it start to work

  • add "" to function in your tag onclick="onClose()",
  • you better add <script> in <header> but not in <body>
  • you can not called your function close() as it is reserved name. For example you also could not name var return etc

<!DOCTYPE html>
<html>
<head>
    <script>
        function onClose() {
            console.log("why don't you work - I work");
        }
    </script>
    <style>
      .cross {
        cursor: Default;
      }
    </style>
</head>
<body>
<div id="overdiv">
    <div id="lowerDiv">
        <a class="cross" onclick="onClose()">x</a>
    </div>
</div>
</body>
</html>
Yana Trifonova
  • 586
  • 7
  • 28