1

I am currently unable to get this code to work using jQuery. The same event works when I add it specifically on the "a" link element. I would expect jQuery to register an alert to be shown when the link is clicked but nothing happens when I click on that link. I am running this html in Chrome and DevTools console does not show any errors at all! I am not sure what I could be doing wrong as I am doing it just by the book! Overall I have seen jQuery is not working for anything javascript but I have posted this small piece of code to illustrate. Appreciate any help figuring out what I could be doing wrong!

<html>

<head>
  <!-- jQuery version 3.3.1 -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" />
  <script>
    $(document).ready(function() {
      $("a").click(function() {
        //This should show an alert when any link on the page is clicked.
        alert("This is a test");
      })
    });
  </script>
</head>

<body>
  <a href="#">Click here to see alert</a>
  <!-- This does not work! -->
  <!-- This works fine!
                <a href="#" onclick="javascript:alert('This is a test');">Click here to see alert</a> -->
</body>

</html>

1 Answer 1

1

The problem is because a script tag is not self-closing. You need to add a separate </script> tag after your jQuery.js reference:

<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script>
    $(document).ready(function() {
      $("a").click(function() {
        console.log("This is a test");
      })
    });
  </script>
</head>
<body>
  <a href="#">Click here to see alert</a>
</body>
</html>

The reason your onclick="javascript:alert('This is a test');" still works is because it doesn't rely on the broken reference to jQuery.

That said, you should avoid using on* event attributes as they are very outdated. Unobtrusive event handlers are by far the best practice here.

Sign up to request clarification or add additional context in comments.

2 Comments

Wow, that worked! Thank you so much for the quick reply! :)
I cannot visibly upvote the answer but I have upvoted. thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.