HTML DOM focus() मेथड का उपयोग किसी HTML तत्व को फोकस देने के लिए किया जाता है। फोकस सभी HTML तत्वों पर लागू नहीं किया जा सकता। उदाहरण के लिए: आप <p> टैग को फोकस नहीं कर सकते। किसी तत्व से फोकस हटाने के लिए blur() मेथड का उपयोग करें।
सिंटैक्स
सिंटैक्स निम्नलिखित है:
HTMLElementObject.focus()
उदाहरण
आइए focus() मेथड का एक उदाहरण देखते हैं:
<!DOCTYPE html> <html> <head>
<style>
input[type=text]:focus, p:active {
color: blue;
font-size:35px;
background-color:lightpink;
border:2px solid blue;
}
input[type=text]{
color:black;
font-size:20px;
}
</style>
<script>
function enableFocus() {
document.getElementById("USR1").focus();
}
function disableFocus() {
document.getElementById("USR1").blur();
}
</script> </head> <body>
<h1>focus() मेथड उदाहरण</h1>
<label>USERNAME :<input id="USR1" type="text" size=5 maxlength=10></label>
<br><br>
<input type="button" onclick="enableFocus()" value="FOCUS">
<input type="button" onclick="disableFocus()" value="BLUR">
</body> </html>
आउटपुट
यह निम्नलिखित आउटपुट देगा:

FOCUS बटन पर क्लिक करने पर:

BLUR बटन पर क्लिक करने पर:

उदाहरण की व्याख्या
उपरोक्त उदाहरण में:
- हमने पहले id "USR1" के साथ एक टेक्स्ट बॉक्स बनाया और size और maxlength प्रॉपर्टी मान 5 और 10 के बराबर हैं:
<label>USERNAME :<input id="USR1" type="text" size=5 maxlength=10></label>
- हमने दो अलग-अलग CSS स्टाइल बनाए जब टेक्स्टबॉक्स फोकस में हो, एक्टिव हो और जब यह न हो:
input[type=text]:focus, input[type=text]:active {
color: blue;
font-size:35px;
background-color:lightpink;
border:2px solid blue;
}
input[type=text]{
color:black;
font-size:20px;
}
- फिर हमने दो बटन FOCUS और BLUR बनाए जो यूज़र द्वारा क्लिक किए जाने पर क्रमशः enableFocus() और disableFocus() मेथड को एक्ज़िक्यूट करेंगे:
<input type="button" onclick="enableFocus()" value="FOCUS"> <input type="button" onclick="disableFocus()" value="BLUR">
- enableFocus() मेथड getElementById() मेथड का उपयोग करके टाइप "text" वाले इनपुट तत्व को प्राप्त करता है और इसकी focus() मेथड को सक्षम करता है ताकि टेक्स्टबॉक्स पर फोकस सेट हो सके जो हमारे टेक्स्टबॉक्स पर :focus स्टाइल लागू करता है। disableFocus() मेथड id "USR1" वाले इनपुट तत्व को प्राप्त करता है और इस पर blur() मेथड को कॉल करता है जो टेक्स्टबॉक्स से फोकस हटा देता है जो हमारे सामान्य CSS स्टाइल को इस पर लागू करता है यानी यह डिफ़ॉल्ट स्टाइल पर वापस आ जाता है:
function enableFocus() {
document.getElementById("USR1").focus();
}
function disableFocus() {
document.getElementById("USR1").blur();
}