Question

I have a jQuery function as shown below. I want to call the function within my javascript regardless of the whether the triggering event occurs or not. In other words, there are circumstances where I simply want to call the function below. Is it possibe?

$(document).on('change', '.jq__pAC', function(event) {
  // some working code
}); // end .on('change')
Was it helpful?

Solution 3

The best way to do this is as follows:

function myFunction(event)
{
   // code stuff here
}
...    
$(document).on('change', '.jq_pAc', myFunction);

This way, you can call your function at your discretion, and it will also be called by the change event.

OTHER TIPS

Just use change(); without passing a function this method triggers the action, rather than handling it:

$(document).on('change', '.jq__pAC', function(event) {
 // some working code
}).change();

Alternatively you can use trigger(), which triggers the event passed to the method as a string:

$(document).on('change', '.jq__pAC', function(event) {
 // some working code
}).trigger('change');

References:

You can separate the function from the on method, like this:

$(document).on('change', '.jq__pAC', handlerFunction);

function handlerFunction(event) {
  // some working code
}

// at some other point in your code you can call:
handlerFunction();

PS: Just for completion sake, I would recommend you extract the event variable inside the on method and pass only the appropriate info to handlerFunction. Like this:

$(document).on('change', '.jq__pAC', function(event) {
    var nodename = event.target.nodeName;
    handlerFunction(nodename);
});

function handlerFunction(nodename) {
  // some working code
}

// at some other point in your code you can call:
handlerFunction('div');

So after a couple of minutes of testing and playing around with the change event I have noticed that this only works on input elements.

$(document).on('change', '.myCart-val', function(){
   if ($('.myCart-val').html() == "0") {
     $('.myCart-val').hide();
   } else {
     $('.myCart-val').show();
   }
});

What I have noticed is that for this function to actually go off I would need to apply it to some type of onclick event and the two would need to appreciate one another.

I have finally found a better solution that includes Mutation Events. Mutation events allowed my function to run accordingly when triggered by another function.

My final solution.

if ($('.myCount').text() == "0"){$('.CartCount').hide();}

$('.myCart-val').on('DOMSubtreeModified', function() {
   if ($(this).text() == "0") {
     $(this).hide();
   } else {
     $(this).show();
   }    
});

I found my answer here.. Hope it helps you

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top