-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 ?

3
  • 1
    Please clarify your question. If you want to set a eventListener, you can do that directly. Otherwise, use function clickEvent() Commented Nov 23, 2017 at 8:09
  • Possible duplicate of How to write a reusable jquery click function? Commented Nov 23, 2017 at 8: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? Commented Nov 23, 2017 at 8:56

2 Answers 2

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>

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

3 Comments

dont know @brk I haven't... thanks but can I do the same in javascript without jquery?
can u please add javascript as well
@subhajit have added new snippet with only js
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();

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.