Search code examples
javascriptjqueryheaddelegation

Can't link jQuery


Here is my HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <!-- jQuery library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.0.js" type="text/javascript"></script>

    <!-- Latest compiled JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="script.js"></script>
    <meta charset="UTF-8">
    <title>RNG</title>
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <div class="col-md-3"></div>
        <div class="col-md-6 text-center">

            <h1>Random Number Generator</h1>

            <button class="btn btn-primary" id="generateButton">Generate</button>

            <p id="randomNumber"></p>

        </div>
        <div class="col-md-3"></div>

    </div>

</div>
</body>
</html>

And my JS/jQuery:

$("#generateButton").on("click", function() {
    alert("Hello");
})

If you are wondering why the only thing my Random Number Generator is supposed to do is saying "Hello", that's because I was trying to figure out why my code wasn't working properly, and then I found out it was jQuery not working.

The file 'script.js' is linked properly though, because when I tried the normal JS alert with no jQuery code, it worked fine.

This is the part of the code where I am linking to jQuery:

<!-- jQuery library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.0.js" type="text/javascript"></script>

Yes, I am linking jQuery from 3 different sources, just in case. That is because the first one didn't work, the second one didn't either, so I just wanted to make sure.


Solution

  • Assuming script.js is where your code lives, when you do

    <script src="script.js"></script>
    

    There is no $("#generateButton"). You can either move your script to just before the </body>, or wrap you code in

    $(function() {
        //your code goes here
    });
    

    which tells it to wait for the document to load before executing.