2

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 can see, 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?

3
  • is the javascript in your test.js file? Commented Aug 16, 2016 at 14:53
  • 1
    If you want to interact with the HTML (in your case by assigning a click handler), you should wait until the HTML is fully loaded. You can do this by wrapping all your JS code in $( document ).ready(...) see: learn.jquery.com/using-jquery-core/document-ready Commented Aug 16, 2016 at 14:54
  • Maybe your path to javascript file is not correct. Look here, it works fine: jsfiddle.net/ovc6p0kq/2 Commented Aug 16, 2016 at 14:54

2 Answers 2

3

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>
Sign up to request clarification or add additional context in comments.

Comments

0

I would definitely use the `$( document ).ready(...) up in the header.

Comments

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.