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.

+3


source to share


6 answers


Divide into two functions:



format: function() {
    //Do stuff for focus
}
onload: function() {
    //Do stuff for onload
    this.format();
}

      

+3


source


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.

+2


source


Just use the event parameter.

format : function(e){
   //function body
   if(e && e.type == 'focus'){
       //execute this condition only on focus event 
   }
}

      

Demo: http://jsfiddle.net/mbL5ohwr/

+2


source


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

      

0


source


You can check if an element has focus using for example this === document.activeElement

or $(this).is(':focus')

. If the function is triggered via the focus event, they return true

, and if they are called from the onload event, they return false

.

Hope this helped you!

0


source


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.

0


source







All Articles