Indika Rajapaksha
Indika Rajapaksha

Reputation: 1168

Simple jquery function does no work on click event

I'm new to jquery and trying to learn it by example. I see there is a id selector for handling events. Here is a very simple function to handle a click event of a button. Unfortunately it does not work as expected. I could not find any syntax errors. I'm using jquery-3.2.1 for this.

html file

<!DOCTYPE html>
<html>
    <head>
        <title>This is a test</title>
        <script type="application/javascript" src="main.js"></script>
        <script type="application/javascript" src="jquery-3.2.1.min.js"></script>
    </head>
    <body>
        <button type="button" id="test">Click</button>
    </body>
</html>

js file:

$("#test").click(function () {
    alert('You clicked me');
});

Upvotes: 0

Views: 29

Answers (2)

user5316279
user5316279

Reputation: 43

Hello I think you need to bind the event to the button after your page is completely rendered...

To do that use the following:

$(document).ready(function(){
  $("#test").click(function () {
   alert('You clicked me');
    });
 })

Upvotes: 0

Martijn van der Woud
Martijn van der Woud

Reputation: 127

I think you need to change 2 things:

  • Load your main JavaScript file after JQuery instead of before
  • Postpone binding to the click event until after the document has loaded, using

$(document).ready( ...)

See https://learn.jquery.com/using-jquery-core/document-ready/

Upvotes: 1

Related Questions