Forum Moderators: open

Message Too Old, No Replies

External jquery

         

Sub_Seven

11:03 pm on Nov 2, 2010 (gmt 0)

10+ Year Member



Hey guys, quick question:

You know how you can have internal, external or inline css or javascript, can that be done with jquery?

I have this example from [api.jquery.com...]

<!DOCTYPE html>
<html>
<head>
<style>
span { color:red; cursor:pointer; }
div { margin:3px; width:80px; display:none;
height:80px; float:left; }
div#one { background:#f00; }
div#two { background:#0f0; }
div#three { background:#00f; }
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<span>Click here...</span>

<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
<script>
$(document.body).click(function () {
$("div:hidden:first").fadeIn("slow");
});
</script>

</body>
</html>


Which works fine, but if I try to send the javascript to an external file it wont work. I am calling that script in the head tag
    after
the script that calls the library so it looks like this:

<!DOCTYPE html>
<html>
<head>
<style>
span { color:red; cursor:pointer; }
div { margin:3px; width:80px; display:none;
height:80px; float:left; }
div#one { background:#f00; }
div#two { background:#0f0; }
div#three { background:#00f; }
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/js.js"></script>
</head>
<body>
<span>Click here...</span>

<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
</body>
</html>



and the js.js looks like this:

$(document.body).click(function () {
$("div:hidden:first").fadeIn("slow");
});


Any ideas people? Thanks everybody :)

daveVk

1:42 am on Nov 3, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



References to Dom elements such as $(document.body) will fail prior to the Dom being loaded.

In external case you need something like below to delay execution

$(document).ready(
$(document.body).click(function () {
$("div:hidden:first").fadeIn("slow");
});
)

Fotiman

2:43 am on Nov 3, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



And/or move the script to the end of the file just before the closing body tag. For performance reasons, it's best to put the scripts at the end anyway.

Sub_Seven

4:57 pm on Nov 5, 2010 (gmt 0)

10+ Year Member



Huh, tricky but it works, thanks a lot daveVk and Fotiman