Sunday, November 3, 2013

Javascript: onfocus event and focus() method

onfocus in HTML

The onfocus event occurs when an element gets focus.

onfocus is often used with <input>, <select>, and <a>.

Check out the onfocus event here.

HTML Example:

<input type="text" onfocus="yourFunction()">


You may also pass the 'input' element as a parameter to your onfocus handler's function using the keyword 'this'.

<input type="text" onfocus="yourFunction(this)">


JavaScript Example:

HTMLElementObject.onfocus = function(){ your javascript code here }


The onfocus attribute can be used within ALL HTML elements, EXCEPT: <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title>.

So in javascript, you can also use the focus() method on any HTML element except on what’s listed above.


focus() Method

The focus() method is used to give focus to a HTML element.

Syntax:

HTMLElementObject.focus()

Example:

<script type="text/javascript">
  document.getElementById("targetElementId").focus();
</script>

Check out the focus() method here.

No comments:

Post a Comment