user3289867
user3289867

Reputation: 119

JQuery external file not working

I have a jQuery file called login.js:

<script type='text/javascript'>
var login = function () {
    $("a#register").click(function () {
        $("form#login").hide();
        $("form#signup").show();
    });
    $("a#login").click(function () {
        $("form#login").show();
        $("form#signup").hide();
    });
}
</script>

with the following HTML:

<script>
$(document).ready(function() {
  login();
});
</script>

and got this in the header:

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="../scripts/login.js"></script>

The jQuery code isn't working like this, while it works if I include it directly in the HTML, any thoughts on why it isn't working?

Upvotes: 1

Views: 6836

Answers (2)

Ignacio T&#233;llez
Ignacio T&#233;llez

Reputation: 451

Try moving login.js to the same location as the page you are calling it (let's say, web/index.php and web/login.js). If that works, then the problem you have is with the location of the JS file you are pointing from your header.

I recommend you always use simple routes to CSS and JS files (like /css and /js), to avoid using ".../path/to/file.js. That way, your code should be this simple:

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="script/login.js"></script>

You can improve it, if it suits you, using PHP variables to point to the server home location and thus making the path absolute, like in this example:

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="<?php echo $_SERVER['HOME']; ?>/script/login.js"></script>

I hope this helps.

Upvotes: 0

Richard Muthwill
Richard Muthwill

Reputation: 336

Header

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="scripts/login.js"></script>

Login.js

$(document).ready(function() {
    $("a#register").click(function() {
        $("form#login").hide();
        $("form#signup").show();    
    });

    $( "a#login" ).click(function() {
        $("form#login").show();
        $("form#signup").hide();    
    });
});

Possible fixes:

  1. <script> tags in JS file
  2. Changed from ../scripts/ to scripts/

Upvotes: 1

Related Questions