1

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>
2
  • Me either ! What is not working? the event is not trigger? trigger twice ? Commented Dec 14, 2011 at 11:47
  • No, the code is not right. Check my answer. Commented Dec 14, 2011 at 11:49

4 Answers 4

4

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");
        }); 
});
Sign up to request clarification or add additional context in comments.

1 Comment

As I suggested. Wrap your code in the $(function() { //your code here })
2

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>

Comments

0

@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.

Comments

0

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..

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.