0

I tried to exclude the function (because I'm used to it from php), that should be triggered when you click on the p with the id test1.

I wrote following jQuery

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>click demo</title>
        <style>
            p {
            color: red;
            margin: 5px;
            cursor: pointer;
            }
            p:hover {
            background: yellow;
            }
        </style>
        <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
        <script>
            function test1(){
                $( this ).slideUp();
            }
            $(document).ready(function(){
                    $( "#test1" ).click(test1());
            });

        </script>
    </head>
    <body>
        <p id="test1" class="test2">First Paragraph</p>
        <p>Second Paragraph</p>
        <p>Yet one more Paragraph</p>
    </body>
</html>

The given example works fine with the inline formatting, but not when I write it this way. Can someone tell me why why it does not work ?

3
  • Move the function inside the document.ready Apr 3, 2015 at 16:34
  • @GeoffreyBurdett that's not the problem. See the upvoted answer
    – Dave
    Apr 3, 2015 at 16:34
  • 1
    @mplungjan thanks for your editing :) as expected English is not my mother tongue.
    – Feirell
    Apr 3, 2015 at 17:45

2 Answers 2

5

You are calling your function immediately. What you want to do is pass the reference of your function (without calling it). Try this instead:

$( "#test1" ).click(test1);
0
0

you can do this with defining function

  $(document).ready(function(){
                $( "#test1" ).click(function(){
                $( this ).slideUp();
                });
        });
1
  • Yeah this was what I meant with "inline function" this worked well for me but I looked for a way to do it without the inline formatting.
    – Feirell
    Apr 3, 2015 at 20:59

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.