0

I want to make a jquery function which will be returning a number and I want to use that function somewhere else. please suggest if below is the rigt way of doing it.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function print()
{
 var count=1;
 $('#forwardbutton').click(function(){
 count++;
 });
 return count;
 };
</script>
asked Aug 5, 2014 at 9:27
3
  • @MohitArora: You can, just not like that. :-) Commented Aug 5, 2014 at 9:29
  • Then what is alternative? @MohitArora Commented Aug 5, 2014 at 9:29
  • You should read this(sitepoint.com/5-ways-declare-functions-jquery) Commented Aug 5, 2014 at 9:31

2 Answers 2

1

You can't have the print function return the number of times that the element has been clicked. Your print function will only ever return 1.

If you want a function that hooks up a click handler and then does something with the number of times the element has been clicked, you can do it by having the function accept a callback. (I wouldn't call the function print, as there's a global print function already, and that can get confusing really fast.)

For example:

function someNameHere(callback) {
 var count = 0;
 $('#forwardbutton').click(function(){
 ++count;
 callback(count);
 });
}

Then you can use it like this:

someNameHere(function(newCount) {
 // ...use `newCount`...
});

Note that the function now accepts a callback function,and calls it each time the element is clicked, with the new click count. (I also started the count at 0 rather than 1.)

answered Aug 5, 2014 at 9:32
Sign up to request clarification or add additional context in comments.

Comments

1

Remove function since you cannot use click event like the way you are doing

Try this :

$(document).ready(function()
{
 var count=1;
 $('#forwardbutton').click(function(){
 count++;
 // your code to use count variable
 });
});
answered Aug 5, 2014 at 9:29

2 Comments

@Rakesh Shetty How will I be able to use this code some where else? I want to give the reference of a function that is returning a number.
"since you cannot use click event inside any function" Sure you can. In fact, you are.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.