Search code examples
jquerycssnavigationslide

Sliding Bar Under Navigation jQuery CSS


$(".myNav").hover (
    function () {
          $('.bar').animate({width: "102px"}, 500)
          $(".myNav").animate ({backgroundColor: "#FF9900"}, 500)
  }, 
    function(){
      $('.bar').animate({width: "-0"}, 500)
          $(".myNav").animate ({backgroundColor: "#ffb84d"}, 500)
    }
);

I'm using this code to add a sliding bar under a nav button but it affects every button with the same class when hovered over.

I was also wondering if there was a way to do this purely with CSS?

http://jsfiddle.net/cgcLe1hs/


Solution

  • With pure CSS you can use transition to make the animations and :pseudo-elements to recreate the bar; try this:

    .myTable {
      border-collapse: collapse;
      padding: 0px;
    }
    .myNav {
      width: 100px;
      text-align: center;
      background-color: #ffb84d;
      padding-bottom: 5px;
      position: relative;
      transition: background .5s linear;
    }
    .myNav:hover {
      background: #FF9900;
    }
    .myNav:after {
      content: "";
      height: 3px;
      width: 0;
      background: #000;
      position: absolute;
      left: 0;
      bottom: 0;
      transition: width .5s linear;
    }
    .myNav:hover:after {
      width: 100%;
    }
    <table class="myTable">
      <tr>
        <td class="myNav">
          Home
        </td>
        <td class="myNav">
          About
        </td>
      </tr>
    </table>


    Aside I suggest to avoid the use of tables to create a menu instrad use list with a elements and style it to be side by side