Skip to content Skip to sidebar Skip to footer

Javascript To Run A Function When Input Focus

What is the code to run a function, say called 'myfunction' when a user clicks within an input box (focus). I have seen examples in jquery but I cant see how to do it with straight

Solution 1:

use the onfocus attribute

<inputtype="text"onfocus="someFunc()"><script>functionsomeFunc(){

  }
</script>

Solution 2:

var addEvent = (function(){
  /// addEventListener works for all modern browsersif ( window.addEventListener ) {
    /// I'm returning a closure after the choice on which method to use/// has been made, so as not to waste time doing it for each event added.returnfunction(elm, eventName, listener, useCapture){
      return elm.addEventListener(eventName,listener,useCapture||false);
    };
  }
  /// attachEvent works for Internet Explorerelseif ( window.attachEvent ) {
    returnfunction(elm, eventName, listener){
      /// IE expects the eventName to be onclick, onfocus, onkeydown (and so on)/// rather than just click, focus, keydown as the other browsers do.return elm.attachEvent('on'+eventName,listener);
    };
  }
})();

Using the above cross browser function you can then do the following (once the dom is fully loaded):

addEvent(document.getElementById('your_input'),'focus',function(e){
  var input = e.target || e.srcElement;
  alert('this input has gained focus!');
});

Solution 3:

document.getElementById("elementId").addEventListener("focus",function(e){
 //Do Something here
});

Post a Comment for "Javascript To Run A Function When Input Focus"