Jeff Hu Jeff Hu - 5 months ago 17
Javascript Question

Assign onfocus to DOM elements in runtime

I am interested in assigning onfocus or other similar functions to a DOM elements in runtime.

General Case:

<input type="text" id="box" onfocus="inputFocused()"/>


Runtime Assignment Case:

<input type="text" id="box"/>


And in the script

$('#box').onfocus = inputFocused();


inputFocused()
is nothing more than a simple function. It appears not working properly.

Thanks for any help.

Answer

You could use it as :

$('#box').on('focus',inputFocused);

Hope this helps.

$('#box').on('focus',inputFocused);

function inputFocused(){
  alert('focused');  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="box"/>