0

I can't use the script in header, Here is the code:

<!DOCTYPE html>
<html>
<head> 

<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
 <a href="javascript:void" class="sl-start">Click Here</a> 
<p class="slide" style="display: none">Something to display</p>

<script>
    $(".sl-start").click(function () {
    $(".slide").show();
    });
    </script>
</body>
</html>
1

3 Answers 3

4

Wrap your code in a document.ready event handler like so:

<!DOCTYPE html>
<html>
<head> 

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
        $(document).ready(function(){
            $(".sl-start").one('click', function () {
                $(".slide").show();
            });
        });
    </script>
</head>
<body>
 <a href="javascript:void" class="sl-start">Click Here</a> 
<p class="slide" style="display: none">Something to display</p>

</body>
</html>

Or else, the script will get executed before the element exists!

1
  • Thanks, is this possible to remove the href after displayed the function ?
    – Suresh
    Aug 21, 2012 at 13:16
0

Because the DOM isn't ready yet in the head for which to attach the event.

If you make it run when the document's ready event fires it'll work:

$(document).ready(function(){
    $(".sl-start").click(function () {
        $(".slide").show();
    });
});
0

If you want to use it in the <head> area then you have to use the $(document).ready() event.

<script type="text/JavaScript">
    $(document).ready(function() {
        $(".sl-start").click(function () {
            $(".slide").show();
        });
    });
</script>

Or the shorthand:

$(function() {
    ...
});

Because the $(document).ready() event is triggered after the HTML/CSS documents have been read. Which means the browser is already aware of the full content & structure of the HTML document.

Otherwise the HTML structure is not available (has not been fully read yet) so your jQuery calls will fail to find any objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.