0

I am trying o learn jQUERY , i am trying with different types of things in jquery . I got this query , on click of a button , i am using the click funcion of a button to call another function , as shown .

But this isn't working .

Could you please tell me , cant we use the click this way

$("button").click() instead of standard  $("button").click(function(){

=====

This is my code

<html>
<head>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" >
 </script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click()
{
   callMe();

}
});

function callMe()
{
 $("p").hide();
}
</script>
</head>

<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
</body>
</html>
1
  • Can I know why you want to use it that way. function() inside the click is called a callback. So, it is like the return value after your operation is done. You can use the code below. Commented Nov 1, 2011 at 6:24

2 Answers 2

2

jQuery is a library built for the JavaScript language, not an actual language itself, and is thus restricted to what JavaScript lets it do.

$("button").click()
{
   callMe();
}

So why the above won't work is because .click() is a method in jQuery that takes in arguments/parameters, not an actual part of the JavaScript language itself, which doesn't let you use a block in that way.

$("button").click(function()
{
   callMe();
});

The function itself is an argument/parameter being passed to the click method. See if you can understand what's going on this way:

var myFunction = function()
{
   callMe();
};
$("button").click(myFunction);

Or this way:

function myFunction()
{
   callMe();
}
$("button").click(myFunction);

The above three code blocks would all cause callMe() to be called when anything matching button is clicked.

Sign up to request clarification or add additional context in comments.

1 Comment

Hey thanks a lot , you have spend enough time for presenting the answer in a good manner , thanks once again .
1
function callMe()
{
 $("p").hide();
}


$(function(){
  $("button").click(callMe)// just provide the reference to call me
});

DEMO

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.