HTMLElement.focus() मेथड निर्दिष्ट एलिमेंट पर फोकस सेट करता है, यदि वह फोकसेबल है (इनपुट, बटन, लिंक, tabindex वाले एलिमेंट्स)। यह UX सुधार के लिए महत्वपूर्ण है।
उदाहरण
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 20px; }
.sample { font-size: 18px; font-weight: 500; padding: 10px; border: 2px solid #ccc; border-radius: 4px; width: 300px; }
.sample:focus { border-color: #007bff; box-shadow: 0 0 0 3px rgba(0,123,255,0.25); outline: none; }
button { padding: 10px 20px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; margin-top: 10px; }
</style> </head> <body>
<h1>JavaScript focus() मेथड</h1>
<input type="text" class="sample" placeholder="यहां क्लिक करें या बटन दबाएं" />
<br><br>
<button class="Btn">इनपुट पर फोकस करें</button>
<h3>ऊपर दिए गए बटन पर क्लिक करके इनपुट फील्ड पर फोकस सेट करें</h3>
<script>
const sampleEle = document.querySelector(".sample");
document.querySelector(".Btn").addEventListener("click", () => {
sampleEle.focus();
});
</script> </body> </html>
आउटपुट
बटन क्लिक करने पर इनपुट फील्ड फोकस प्राप्त करता है (बॉर्डर नीला होता है, कीबोर्ड इनपुट तैयार)।
फोकस से संबंधित महत्वपूर्ण मेथड्स
| मेथड/प्रॉपर्टी | विवरण |
|---|---|
element.focus() | एलिमेंट पर फोकस सेट करता है |
element.blur() | एलिमेंट से फोकस हटाता है |
element.autofocus | HTML एट्रिब्यूट: पेज लोड पर ऑटो फोकस |
document.activeElement | वर्तमान में फोकस्ड एलिमेंट लौटाता है |
document.hasFocus() | डॉक्यूमेंट में फोकस है या नहीं |
उन्नत उपयोग
// 1. फोकस के साथ कर्सर अंत में रखें
input.focus();
input.setSelectionRange(input.value.length, input.value.length);
// 2. फोकस इवेंट लिसनर
input.addEventListener("focus", () => console.log("फोकस प्राप्त"));
input.addEventListener("blur", () => console.log("फोकस खोया"));
// 3. फोकस ट्रैप (मोडल के लिए)
function trapFocus(element) {
const focusable = element.querySelectorAll('button, input, select, textarea, a[href], [tabindex]:not([tabindex="-1"])');
const first = focusable[0];
const last = focusable[focusable.length - 1];
element.addEventListener('keydown', e => {
if (e.key === 'Tab') {
if (e.shiftKey && document.activeElement === first) {
e.preventDefault(); last.focus();
} else if (!e.shiftKey && document.activeElement === last) {
e.preventDefault(); first.focus();
}
}
});
}
एक्सेसिबिलिटी नोट
फोकस प्रबंधन WCAG अनुपालन के लिए महत्वपूर्ण है। सुनिश्चित करें कि फोकस इंडिकेटर दृश्यमान हों और टैब ऑर्डर तार्किक हो।