Reputation: 7956
$("#btnCon").click(function() {
$('#con').slideToggle('slow');
$('.tgg:not(#con)').hide();
});
When I place this code in the head of html - it doesn't work.
In the body - it works.
In a separate file - it doesn't work.
Where is the secret ?
Upvotes: 0
Views: 1905
Reputation: 1074178
When I place this code in the head of html - it doesn't work. In the body - it works. In a separate file - it doesn't work.
It'll work in a separate file if you put the script
tag including the file at the end of the body, just before the closing </body>
tag.
The reason it isn't working is that when it's in the head
, the code runs right away, and the elements don't exist yet, so the handler doesn't get hooked up.
The right answer here is to put the script
tag for the code right at the end. This is what's advocated by the YUI team and the Google closure library team. You'll also see people using jQuery's ready
event for this and putting scripts in head
, and that does work, but there's no need to do that if you control where the script
tags go.
So in short:
This works:
<body>
...content...
<script>
/* ...code... */
</script>
</body>
and this works:
<body>
...content...
<script src="/the/script/file.js"></script>
</body>
and this works:
<head>
...
<script>
jQuery(function($) { // <== This is a shortcut for `ready`
/* ...code...*/
});
</script>
</head>
<body>
...content...
</body>
and this works if the code in the script file is inside a ready
handler:
<head>
...
<script src="/the/script/file.js"></script>
</head>
<body>
...content...
</body>
Upvotes: 4
Reputation: 648
Try it in document.ready
$(document).ready(function () {
$("#btnCon").click(function() {
$('#con').slideToggle('slow');
$('.tgg:not(#con)').hide();
});
});
Shorthand -
$(function () {
$("#btnCon").click(function() {
$('#con').slideToggle('slow');
$('.tgg:not(#con)').hide();
});
});
Upvotes: 2
Reputation: 382122
To make it work in head do this :
$(function(){
$("#btnCon").click(function() {
$('#con').slideToggle('slow');
$('.tgg:not(#con)').hide();
});
});
The problem was that you were looking for the element with id btnCon
before it was ready. The usual solution is to embed the code in this callback that jQuery calls when the DOM is ready.
But note that even while using $(function(){ ... });
is always recommended, the best practice is generally to put your code either
Upvotes: 4