4

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>

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The amount of time I've spent on something so dumb is insane. I never thought it required 2 elements. Thanks a lot.
No problem. We've all been there. :)
1

Move your scripts into the head element like this:

<html>
<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <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>
</head>
<body>    
    <a href="#">Link</a>
</body>
</html>

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.