Anon Ymous Anon Ymous - 3 months ago 8
jQuery Question

HTML javascript and jQuery - Beginner

I just started learning HTML javascript and jQuery, but I can't link these three together.
So far what I did is:
HTML file:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script type="text/javascript" src="test.js"></script>
<link rel="stylesheet" href="test.css" type="text/css"/>
</head>
<body>
<button class="alert-btn">Click me for alert</button>
</body>




javascript file:

$(".alert-btn").click(function(){
alert("Hey there!");
});


So as you I tried to put the links in the head part of html file, but it's not working. What am I doing wrong, or what do I need to add?

Answer

If the code:

$(".alert-btn").click(function(){
    alert("Hey there!");
});

is in the file test.js you should load this file after the DOM elements are loaded:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
    <link rel="stylesheet" href="test.css" type="text/css"/>
</head>
<body>
    <button class="alert-btn">Click me for alert</button>
    <script type="text/javascript" src="test.js"></script>
</body>