Vince Vince - 5 months ago 5x
Javascript Question

How do I use a function as a variable in JavaScript?

I want to be able to put the code in one place and call it from several different events.

Currently I have a selector and an event:

$("input[type='checkbox']").on('click', function () {
// code works here //

I use the same code elsewhere in the file, however using a different selector.

$(".product_table").on('change', '.edit_quantity', function () {
// code works here //

I have tried following the advice given elsewhere on StackOverflow, to simply give my function a name and then call the named function but that is not working for me. The code simply does not run.

$(".product_table").on('change', '.edit_quantity', function () {
calculateTotals() {
// code does not work //

So, I tried putting the code into it's own function separate from the event and call it inside the event, and that is not working for me as well.

calculateTotals() {
// code does not work //

So what am I doing wrong ?


You could pass your function as a variable.

You want to add listeners for events after the DOM has loaded, JQuery helps with $(document).ready(fn); (ref).

To fix your code:

 $(document).ready(function() {
   $("input[type='checkbox']").on('click', calculateTotalsEvent)
   $(".product_table").on('change', '.edit_quantity', calculateTotalsEvent)

 function calculateTotalsEvent(evt) {
   //do something 

Vince asked:

This worked for me - thank you, however one question: you say, "pass your function as a variable" ... I don't see where you are doing this. Can you explain ? tks. – Vince

In JavaScript you can assign functions to variables. You probably do this all the time when doing:

function hello() {

You define window.hello.
You are adding to Global Namespace.
JavaScript window object
This generally leads to ambiguous JavaScript architecture/spaghetti code.
I organise with a Namespace Structure.
A small example of this would be:


var app = {
  controllers: {}

You are defining (just a json object) with a key of controllers with a value of an object.


app.controllers.somethingCtlr.eventName = function(evt) {
  //check origin of evt? switch? throw if no evt? test using instanceof?

You are defining a new key on the previously defined app.controllers.somethingCtlrcalled eventName.

The javascript files would be structured like so:


Invoke via chrome developer tools with:


You can pass it as a variable like so:

$(document).ready(function() {

JQuery (ref).

I hope this helps, Rhys