Reputation: 87
What is wrong in this piece of html code with some jquery functions? I don't understand why is not working jquery functions! Thanks!
<html>
<head>
<style>
p { color:red; margin:5px; cursor:pointer; }
p.hilite { background:yellow; }
</style>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$("p").click(function () {
$(this).slideUp();
return false;
});
$("p").hover(function () {
$(this).addClass("hilite");
}, function () {
$(this).removeClass("hilite");
});
</script>
</head>
<body>
<h2>Click</h2>
<p>First Paragraph</p>
<p>Second Paragraph</p>
<p>Yet one more Paragraph</p>
</body>
</html>
Upvotes: 1
Views: 566
Reputation: 1500
Just put your <script>....</script>
at the end of your body tag and put an alert()
inside the click event to know.It will work..
Upvotes: 0
Reputation: 1500
@david-laberge,
There is no need to put click()
event inside the document.ready()
if it is not an event that have to be executed only after document has been ready.
Upvotes: 0
Reputation: 16061
change your code to :
<html>
<head>
<style>
p { color:red; margin:5px; cursor:pointer; }
p.hilite { background:yellow; }
</style>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){ // that is trigger when the document is loaded
$("p").click(function () {
$(this).slideUp();
return false;
});
$("p").hover(function () {
$(this).addClass("hilite");
}, function () {
$(this).removeClass("hilite");
});
});
</script>
</head>
<body>
<h2>Click</h2>
<p>First Paragraph</p>
<p>Second Paragraph</p>
<p>Yet one more Paragraph</p>
</body>
</html>
Upvotes: 2
Reputation: 7448
Your bindings are executed before the DOM is ready, as you didn't wrap them in the $(function() {})
so the paragraphs do not exist when the bindings are performed.
EDIT
Sample code:
$(function() {
$("p").click(function () {
$(this).slideUp();
return false;
});
$("p").hover(function () {
$(this).addClass("hilite");
}, function () {
$(this).removeClass("hilite");
});
});
Upvotes: 4