user3052886
user3052886

Reputation: 80

I want to add my jQuery file separate from my HTML

I want to write cleaner and readable code, so I wanted to implement my jQuery code in a separate file. I saved the file in the sam folder as the jQuery code I downloaded from jquery.com. In my HTML I put the reference in there, and it does not work, but if I leave the jQuery code in my HTML it works.

My HTML code is this:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>focusin demo</title>
    </head>

    <body>
        <input type="text" />
        <script type="text/javascript" src="js/jquery.js"></script>
        <script type="text/javascript" src="js/test.js"></script>
    </body>
</html>

My jQuery code is in a separate file called test.js and follows:

$(':text').focusin(function() {
    $(this).css('background-color', 'yellow');
});

But when I run it in my browser it doesn't work. I basically tried everything and decided I need professional help.

Upvotes: 1

Views: 142

Answers (4)

sre
sre

Reputation: 415

You may have a problem with relative links. Try changing this

<script type="text/javascript" src="js/jquery.js"></script>

to this:

<script type="text/javascript" src="/js/jquery.js"></script>

Upvotes: 1

Ghan
Ghan

Reputation: 70

You can first confirm inclusion of a file by putting the alert() function in the test.js file. If included then you can try writing some jQuery code in the test.js file to check whether the jQuery file is included properly or not.

Upvotes: 0

Krish R
Krish R

Reputation: 22711

You need to add a ready handler for jQuery scripts, like

$(function() {
    $('input[type=text]').focusin(function() {
        $(this).css('background-color','yellow');
    });
});

Upvotes: 0

Łukasz
Łukasz

Reputation: 331

You need put your code in $(function() { ... });

Like this:

$(function() {
    $(':text').focusin(function() {
        $(this).css('background-color','yellow');
    });
});

Upvotes: 0

Related Questions