-1

I want to store the function reference in a variable and re use it by calling wherever required. Suppose I have a click bound function like this:

var clickEvent = $('#mode').click(function () {
   alert("Hello");
});

And I want to reuse it like this:

//call somewhere
clickEvent();

But it is showing an error clickEvent is not a function, why ?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Subhajit
  • 876
  • 3
  • 17
  • 37
  • 1
    Please clarify your question. If you want to set a eventListener, you can do that directly. Otherwise, use `function clickEvent()` –  Nov 23 '17 at 08:09
  • Possible duplicate of [How to write a reusable jquery click function?](https://stackoverflow.com/questions/22783420/how-to-write-a-reusable-jquery-click-function) – JJJ Nov 23 '17 at 08:20
  • `.click()` doesn't return a function, it returns the jQuery object it was called on, so they can be chained. What are you expecting `clickEvent()` to do? – Barmar Nov 23 '17 at 08:56

2 Answers2

0

Keep the snippet inside a function , but even in that case the click event won't be triggered.

var x = function() {
  $('#mode').click(function() {
    alert("Hello");
  });
   // on call of this function click event will
  $("#mode").trigger('click')
}
x()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="mode"> Click</button>

With only javascript

var x = function() {
  var el = document.getElementById('mode')
  el.addEventListener('click', function() {
    alert('clicked')
  })
  el.click();
}
x()
<button id="mode"> Click</button>
brk
  • 48,835
  • 10
  • 56
  • 78
0

$('#mode').click(...) doesn't return a function, it returns the value of $('#mode') so that you can chain method, e.g. $('#mode').click(...).change(...).

If you want a name for the handler function, define it separately:

function clickEvent() {
    alert("Hello");
}

and then use it in the event binding:

$("#mode").click(clickEvent);

or call it directly:

clickEvent();
Barmar
  • 741,623
  • 53
  • 500
  • 612