Search code examples
javascripthtmlcssfrontendstyling

How to style a data-target anchor tag


So the issue is I use data-target in the anchor(a) tag instead of href, so I am not able to style it when its active . So I usually use 'a:active{styling}' , but its not working for this one.

Here is the JS fiddle: https://jsfiddle.net/sp1vh94u/4/

Here is the code:

<ul >
        <li>
            <a data-target="#a" aria-controls="a" role="tab" data-toggle="tab">A</a>
        </li>
        <li>
            <a data-target="#b" aria-controls="b" role="tab" data-toggle="tab">B</a>
        </li>
        <li>
            <a data-target="#c" aria-controls="c" role="tab" data-toggle="tab">C</a>
        </li>
</ul>

Everything is working just fine, I need help with the styling thats all. :)


Solution

  • If you want avoid href then it is possible with JS.

    const as = document.querySelectorAll('.nav-tabs a')
    as.forEach(a => a.addEventListener('click', e => {
      e.target.classList.add('visited');
    }))
    
    
    <!-- begin snippet: js hide: false console: true babel: false -->
    .nav-tabs a{  
      cursor: pointer;
      text-decoration: none;
      color: black;
    }
    
    .nav-tabs a:hover{
      color: orange;
    }
    .nav-tabs a:active{
      color: red;
    }
    .visited {
      color: white !important;
      background: red;
    }
    <div class="navcontent" role="tabpanel">
    <ul id="BarTab" class="nav nav-tabs" role="tablist">
        <li role="presentation" class="active">
            <a href="#" data-target="#Mat" aria-controls="Mat" role="tab" data-toggle="tab">Mat</a>
        </li>
        <li role="presentation">
            <a href="#" data-target="#Bat" aria-controls="Bat" role="tab" data-toggle="tab">Bat</a>
        </li>
        <li role="presentation">
            <a href="#" data-target="#Cat" aria-controls="Cat" role="tab" data-toggle="tab">Cat</a>
        </li>
    </ul>       
      </div>