Anchor hash प्रॉपर्टी
hash प्रॉपर्टी लिंक (<a>) के href एट्रिब्यूट के एंकर भाग (anchor part) को सेट या लौटाती है। एंकर भाग URL में # के बाद का हिस्सा होता है (जिसे फ्रैगमेंट आइडेंटिफायर भी कहते हैं)।
सिंटैक्स
// सेट करें anchorObject.hash = "anchor_part" // प्राप्त करें anchorObject.hash
उदाहरण: एंकर भाग प्राप्त करना
<!DOCTYPE html>
<html>
<body>
<h1>कंपनी</h1>
<p><a id="myLink" href="https://www.demo.com/abc/def.html#myteam">हमारी टीम</a></p>
<p>एंकर भाग प्राप्त करें...</p>
<h2 id="display"></h2>
<button onclick="showHash()">एंकर भाग प्रदर्शित करें</button>
<script>
function showHash() {
var hash = document.getElementById("myLink").hash;
document.getElementById("display").innerHTML = "Hash: " + hash;
}
</script>
</body>
</html>
आउटपुट
बटन क्लिक करने पर: Hash: #myteam
URL संरचना
https://www.demo.com/abc/def.html#myteam
↑ ↑
pathname hash (एंकर भाग)
सामान्य उपयोग
- पेज के भीतर नेविगेशन (
<a href="#section1">) - सिंगल पेज एप्लीकेशन्स (SPA) में रूटिंग
- डीप लिंकिंग / शेयर करने योग्य URLS
- टैब/एकॉर्डियन स्थिति ट्रैक करना
संबंधित Anchor प्रॉपर्टीज
anchor.href // पूरा URL anchor.protocol // http: या https: anchor.host // www.demo.com:80 anchor.hostname // www.demo.com anchor.port // 80 anchor.pathname // /abc/def.html anchor.search // ?query=string anchor.hash // #myteam anchor.username // उपयोगकर्ता नाम (यदि कोई) anchor.password // पासवर्ड (यदि कोई) anchor.origin // प्रोटोकॉल + होस्ट + पोर्ट
hashchange इवेंट
window.addEventListener('hashchange', function() {
console.log('नया हैश:', window.location.hash);
});