1

I have written a function and intend to call it in several circumstances. Here is the function:

var responsive = function(){
    $('#menuicon').toggleClass('menuicon-res');
    $('.fixed-menu-item').toggleClass('res');
}

In a certain case, calling the function works only when written WITHOUT parenthesis after it:

$('#menuicon').click(responsive);

In another, similar case, calling the function works only when written WITH parenthesis after it:

$('#top').click(function(){
    $('html, body').animate({scrollTop: 0},500);
    responsive();
});

I think I understand that the first case (w/o parenthesis) returns the function for callback, and the second case (w/ parenthesis) returns the output of the function. Can anyone help explain why the way to call my function changes in these two scenarios?

Thanks;

CPR

2 Answers2

3

In the first scenario you are assigning the function to be run on your click event, and the click event will do the calling. In the second scenario you are calling the function yourself.

Cameron637
  • 1,659
  • 13
  • 21
2

The first case you are talking about is hooking up your function as an event listener, which will call the passed function when an event is triggered

//this will execute when "#menuitem" is clicked
$('#menuicon').click(responsive);

Your second case you are calling it yourself, here just putting responsive without actually invoking it will do nothing.

$('#top').click(function(){
    $('html, body').animate({scrollTop: 0},500);
    responsive();
});
konkked
  • 3,053
  • 12
  • 19