Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery not working inside html file

I'm trying to do a very basic jquery tutorial but I'm not able to get it to work. I'm calling the jquery library from google and then I try to create a script inside html.

If I do the same in a .js file I wouldn't have any problem. What am I missing here?

<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    </head>
    <body>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js">
            $(document).ready(function() {
                $("a").click(function() {
                    alert("Hello world!");
                });
            });
        </script>
            <a href="">Link</a>

    </body>
</html>
like image 480
Nicolas de Fontenay Avatar asked Feb 18 '11 07:02

Nicolas de Fontenay


People also ask

Why jQuery is not working in HTML?

This indicates jQuery is not present so your code is throwing an error on the $(document). ready(); statement. JavaScript doesn't recognize $ as a function. Be sure to import the jQuery library before your custom script is loaded.

How to add JavaScript to HTML file?

Adding JavaScript into an HTML Document You can add JavaScript code in an HTML document by employing the dedicated HTML tag <script> that wraps around JavaScript code. The <script> tag can be placed in the <head> section of your HTML or in the <body> section, depending on when you want the JavaScript to load.

What is '$' in jQuery?

The jQuery object :) From the jQuery documentation: By default, jQuery uses "$" as a shortcut for "jQuery" So, using $("#id" ) or jQuery("#id") is the same.


1 Answers

You need to split this up:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js">
    $(document).ready(function() {
        $("a").click(function() {
            alert("Hello world!");
        });
    });
</script>

...into two script elements:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $("a").click(function() {
            alert("Hello world!");
        });
    });
</script>

In the snippet you gave, the code within the <script> element won't be evaluated because the browser is only evaluating the contents from the src attribute and ignoring everything else.

like image 158
Matt Howell Avatar answered Oct 11 '22 02:10

Matt Howell