Call the function only when the event starts
I have the following function:
format : function(){
//function body
if(condition){
//execute this condition only on focus event
}
}
This function is called on page load and on focus of an input element. I have a condition inside this function that I would only like to call when this function is called manually from a focus event and not on page load. Is there a way to achieve this?
Sometimes there are cases where the "condition" in the if statement is true on page load. Any help would be appreciated. Thanks in advance.
source to share
You can just check for the existence of the parameter event
:
format: function(event) {
if (event) {
// called form an event
} else {
// called manually (without a parameter)
}
}
For added reliability, check the parameter event.type
- it will contain the name of the event that was triggered.
source to share
you can just give an argument when called manually on focus and check for no argument, for example with the special keywords "arguments", when you call it on page load with no argument, then the length will be zero, otherwise it will not be zero, so the condition will only be true for focus functions
format : function(){
if(arguments.length){
//execute this condition only on focus event
}
}
source to share
just thought to share: This is what worked for me from the solutions provided to me, thanks to this:
format : function(e){
//function body
if(e && e.type == 'focus'){
//execute this condition only on focus event
}
}
Just FYI, we don't explicitly need to pass the event parameter, it can be that simple:
format : function(){
//function body
if(e && e.type == 'focus'){
//execute this condition only on focus event
}
}
e will by default refer to the event that triggered it. Thanks for all the input.
source to share