Search code examples
htmlcssanchorhreftarget

Different styles for an element based on the current anchor


In my index.html, i have 3 links that work as anchors. And i also have a div element with a fixed position.

<a href="#1">1</a>
<a href="#2">2</a>
<a href="#3">3</a>

<div></div>

How can I customize the div element based on the current href? With "id" and "target" I can do this for only two hrefs. For example: on the first page the element was red, on the second page it became green and on the third page it became blue. Is this possible?


Solution

  • Yes it's possible. If you listen to the onhashchange event you can then change you DOM to match your requirements.

    Here is a working example:

    window.onhashchange = function() {
      var el = document.getElementById('bar');
      switch (window.location.hash) {
        case '#1':
          el.className = 'red';
          break;
        case '#2':
          el.className = 'green';
          break;
        case '#3':
          el.className = 'blue';
          break;
      }
    }
    #bar {
      width: 100vw;
      height: 10vh;
    }
    
    .red {
      background-color: red;
    }
    
    .green {
      background-color: green;
    }
    
    .blue {
      background-color: blue;
    }
    <a href="#1">1</a>
    <a href="#2">2</a>
    <a href="#3">3</a>
    
    <div id="bar"></div>