onfocus इवेंट एट्रिब्यूट
onfocus एट्रिब्यूट HTML में किसी तत्व को फोकस मिलने पर (क्लिक, टैब, या प्रोग्रामेटिक रूप से) स्क्रिप्ट निष्पादित करता है। यह फॉर्म फील्ड्स, लिंक्स, बटन्स, और tabindex वाले तत्वों पर काम करता है।
उदाहरण
निम्नलिखित कोड onfocus एट्रिब्यूट का उपयोग दिखाता है:
<!DOCTYPE html>
<html>
<body>
<h2>onfocus इवेंट उदाहरण</h2>
<p>विषय नाम नीचे दर्ज करें:</p>
<label>
विषय:
<input type="text" id="sname" onfocus="highlight(this.id)">
</label>
<br><br>
<label>
विवरण:
<textarea id="desc" onfocus="highlight(this.id)" rows="3" cols="30"></textarea>
</label>
<script>
function highlight(id) {
const el = document.getElementById(id);
el.style.backgroundColor = '#e8f5e9'; // हल्का हरा
el.style.borderColor = '#4caf50';
el.style.boxShadow = '0 0 0 3px rgba(76, 175, 80, 0.2)';
}
// वैकल्पिक: फोकस खोने पर रीसेट
document.querySelectorAll('input, textarea').forEach(el => {
el.addEventListener('blur', function() {
this.style.backgroundColor = '';
this.style.borderColor = '';
this.style.boxShadow = '';
});
});
</script>
</body>
</html>
फोकस इवेंट्स का क्रम
focus |
तत्व को फोकस मिलने पर | नहीं |
focusin |
तत्व या उसके बच्चे को फोकस मिलने पर | हाँ |
blur |
तत्व फोकस खोने पर | नहीं |
focusout |
तत्व या उसका बच्चा फोकस खोने पर | हाँ |
आधुनिक दृष्टिकोण: addEventListener
<input type="text" id="email" placeholder="ईमेल दर्ज करें">
<script>
const emailInput = document.getElementById('email');
emailInput.addEventListener('focus', (e) => {
e.target.style.borderColor = '#007bff';
e.target.parentElement.classList.add('focused');
// प्लेसहोल्डर एनीमेशन
e.target.setAttribute('data-placeholder', e.target.placeholder);
e.target.placeholder = '';
});
emailInput.addEventListener('blur', (e) => {
e.target.style.borderColor = '';
e.target.parentElement.classList.remove('focused');
// प्लेसहोल्डर बहाल करें
if (e.target.dataset.placeholder) {
e.target.placeholder = e.target.dataset.placeholder;
}
});
</script>
व्यावहारिक उपयोग के मामले
- इनलाइन सहायता दिखाएँ: फोकस पर टूलटिप या संकेत प्रदर्शित करें
- इनपुट मास्किंग: फोकस पर फॉर्मेट लागू करें (फोन, दिनांक)
- सत्यापन प्रतिक्रिया: रीयल-टाइम सत्यापन शुरू करें
- कीबोर्ड शॉर्टकट्स: फोकस पर शॉर्टकट संकेत दिखाएँ
- एनालिटिक्स: फील्ड इंटरैक्शन ट्रैक करें
फोकस स्टाइलिंग CSS के साथ
<style>
/* फोकस रिंग - पहुँच के लिए महत्वपूर्ण */
:focus-visible {
outline: 2px solid #007bff;
outline-offset: 2px;
}
/* फॉर्म फील्ड फोकस */
input:focus,
textarea:focus,
select:focus {
border-color: #007bff;
box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.25);
}
/* लेबल एनीमेशन (फ्लोटिंग लेबल प्रभाव) */
.form-group {
position: relative;
}
.form-group label {
position: absolute;
top: 10px; left: 12px;
transition: all 0.2s;
pointer-events: none;
color: #666;
}
.form-group input:focus + label,
.form-group input:not(:placeholder-shown) + label {
top: -10px; left: 8px;
font-size: 12px;
color: #007bff;
background: white;
padding: 0 4px;
}
</style>