How to prevent the browser from switching to binding when changing the identifier of the URL fragment?

Possible duplicate:
Change document.location.hash without scrolling the page

I would like to cancel the event, if possible, but I see no precedent for this. Suppose I am currently forced to use the same string for both my fragment identifier and my anchor name. I need to intercept the event and somehow cancel it.

UPDATE: this is a duplicate Change document.location.hash without scrolling the page

+5
source share
1 answer

May be?

<h1 id="header">home</h1>
<ul>
    <li><a href="#home">Home</a></li>
    <li><a href="#product">Product</a></li>
    <li><a href="#about">About</a></li>
</ul>
<script type="text/javascript">

   window.onload = function(e) {
     var links = document.getElementsByTagName('a');
     for (var i=0; i < links.length; i++) {
       links[i].addEventListener('click', function(e) {
           var hash = this.href.split('#')[1];
           if(hash.length) {
              if(hash == 'product') {
                  alert('Sorry, page in development');
                  e.preventDefault();
              }else{
                  document.getElementById('header').innerHTML = hash;
              }
           }
       }, false);
     };  
   };
   // OR
   window.onhashchange = function(e) {
       var hash = window.location.hash.substr(1);
       if(hash.length) {
           if(hash == 'product') {
               alert('Sorry, page in development');
               window.history.back();
           }else{
               document.getElementById('header').innerHTML = hash;
           }
       }
   };

</script>
0
source

All Articles