onfocus ਈਵੈਂਟ

ਪਰਿਭਾਸ਼ਾ ਅਤੇ ਵਰਤੋਂ

onfocus ਈਵੈਂਟ ਐਲੀਮੈਂਟ ਫੋਕਸ ਹੋਣ ਉੱਤੇ ਪੈਦਾ ਹੁੰਦਾ ਹੈ。

onfocus ਈਵੈਂਟ ਸਭ ਤੋਂ ਜ਼ਿਆਦਾ <input>、<select> ਅਤੇ <a> ਨਾਲ ਵਰਤਿਆ ਜਾਂਦਾ ਹੈ。

ਸੁਝਾਅ: onfocus ਈਵੈਂਟ ਨਾਲ onblur ਈਵੈਂਟਵਿਰੋਧੀ

ਸੁਝਾਅ: onfocus ਈਵੈਂਟ ਨਾਲ ਮਿਲਣ ਵਾਲਾ ਹੈ onfocusin ਈਵੈਂਟ。ਮੁੱਖ ਅੰਤਰ ਇਹ ਹੈ ਕਿ onfocus ਈਵੈਂਟ ਬੁੱਲਟ ਨਹੀਂ ਹੁੰਦਾ। ਇਸ ਲਈ ਆਪਣੇ ਇੱਕ ਐਲੀਮੈਂਟ ਜਾਂ ਇਸ ਦੇ ਸਬ-ਐਲੀਮੈਂਟ ਨੂੰ ਫੋਕਸ ਹੋਣ ਨੂੰ ਨਿਸ਼ਚਿਤ ਕਰਨ ਲਈ onfocusin ਈਵੈਂਟ ਵਰਤ ਸਕਦੇ ਹੋ ਸਕਦੇ ਹਨ। ਪਰ, ਆਪਣੇ onfocus ਈਵੈਂਟ ਦੀ ਵਰਤੋਂ ਨਾਲ addEventListener() ਮੈਥਡਦਾ useCapture ਪੈਰਾਮੀਟਰ ਨਾਲ ਇਹ ਕਰਨਾ ਹੈ。

ਮਾਡਲ

ਉਦਾਹਰਣ 1

ਜਦੋਂ ਇੰਪੁਟ ਫੀਲਡ ਫੋਕਸ ਹੋਣ ਤੇ ਜਾਵਾਸਕ੍ਰਿਪਟ ਚਲਾਉਣਾ ਹੈ:

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

ਸਵੈ ਮੁਸਕਰਨ

ਪੰਨੇ ਦੇ ਹੇਠਾਂ ਹੋਰ TIY ਉਦਾਹਰਣ ਹਨ。

ਗਿਆਨ ਤਰੀਕਾ:

ਜਿਸ ਵਿੱਚ HTML ਵਿੱਚ ਵਰਤਣਾ ਹੈ:

<element onfocus="myScript">

ਸਵੈ ਮੁਸਕਰਨ

ਜਿਸ ਵਿੱਚ ਜਾਵਾਸਕ੍ਰਿਪਟ ਵਿੱਚ ਵਰਤਣਾ ਹੈ:

object.onfocus = function(){myScript};

ਸਵੈ ਮੁਸਕਰਨ

ਜਿਸ ਵਿੱਚ ਜਾਵਾਸਕ੍ਰਿਪਟ ਵਿੱਚ ਵਰਤਣਾ ਹੈ addEventListener() ਮੈਥਡ:

object.addEventListener("focus", myScript);

ਸਵੈ ਮੁਸਕਰਨ

ਟਿੱਪਣੀਆਂ:Internet Explorer 8 ਜਾਂ ਪੁਰਾਣੇ ਸ਼ਾਮਲ ਨਹੀਂ ਹੈ addEventListener() ਮੈਥਡ

Technical details

Bubble: Not supported
Cancelable: Not supported
Event type: FocusEvent
Supported HTML tags: All HTML elements except: <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style> and <title>
DOM version: Level 2 Events

Browser support

Event Chrome IE Firefox Safari Opera
onfocus Support Support Support Support Support

More examples

Example 2

Use "onfocus" and "onblur" events together:

<input type="text" onfocus="focusFunction()" onblur="blurFunction()">

ਸਵੈ ਮੁਸਕਰਨ

Example 3

Clear the focused input field:

/* When the input field gets focus, replace its current value with an empty string */
<input type="text" onfocus="this.value=''" value="Blabla">

ਸਵੈ ਮੁਸਕਰਨ

Example 4

event delegation: set the useCapture parameter of addEventListener() to true:

<form id="myForm">
  <input type="text" id="myInput">
</form>
<script>
var x = document.getElementById("myForm");
x.addEventListener("focus", myFocusFunction, true);
x.addEventListener("blur", myBlurFunction, true);
function myFocusFunction() {
  document.getElementById("myInput").style.backgroundColor = "yellow"; 
}
}
  function myBlurFunction() { 
}
</script>

ਸਵੈ ਮੁਸਕਰਨ

Example 5

event delegation: using focusin event (not supported in Firefox):

<form id="myForm">
  <input type="text" id="myInput">
</form>
<script>
var x = document.getElementById("myForm");
x.addEventListener("focusin", myFocusFunction);
x.addEventListener("focusout", myBlurFunction);
function myFocusFunction() {
  document.getElementById("myInput").style.backgroundColor = "yellow"; 
}
}
  function myBlurFunction() { 
}
</script>

ਸਵੈ ਮੁਸਕਰਨ