Jonas Gröger
Jonas Gröger

Reputation: 1638

Why does this super simple jquery not work?

I'm having hard time getting this snippet to work. I have made a minimal example. You can view it online: http://jsfiddle.net/qnnZe/ where it is working!

test.html

<!DOCTYPE html>
<head>
    <title>test</title>
    <meta charset="utf-8">
    <script src="jquery.min.js"></script>
    <script src="test.js"></script>
</head>
<body>
    <p>I am going to test right now.</p>
</body>
</html>

test.js

$("p").click(function () {
      $(this).hide("slow");
});

However, on my server it does not work. Here is the link to my server: http://techinf.de/sleepytime/test.html

As always, any help appreciated.

Upvotes: 0

Views: 175

Answers (3)

Dave Newton
Dave Newton

Reputation: 160321

It will execute before the DOM is ready. Click handlers should be added in any of the normal jQuery "ready" methods, like:

$(function() {
    $("p").click(function () {
          $(this).hide("slow");
    });
});

Upvotes: 1

pete
pete

Reputation: 25091

You need to wrap your click handler in a document ready function.

Try either:

$(document).ready(function () {
    $("p").click(function () {
          $(this).hide("slow");
    });
});

or

$(function () {
    $("p").click(function () {
          $(this).hide("slow");
    });
});

Upvotes: 2

BrokenGlass
BrokenGlass

Reputation: 161002

Because in jsFiddle your script code is executed after the DOM has loaded (that's the default option, see the dropdown set to "onDomReady"), on your page it's executed before that. It would work if you wrap your code in a ready() handler:

$(function()
{

 $("p").click(function () {
      $(this).hide("slow");
  });

});

Upvotes: 3

Related Questions