Search code examples
jqueryhtmlcssanimationunderline

Animate Link underline on click as opposed to on hover?


Having trouble getting my head around how I can recreate this effect as an on click as opposed to on hover?

I'm not great with jQuery so having trouble working out how I can trigger this to happen on click. I came across this website to help create the effect I'm going for (Underline Left to Right). The demo can be seen in the following link...

http://bradsknutson.com/blog/css-sliding-underline/

I'm currently using the following js to fade in a div and I want the line to slide in at them same time.

New jsfiddle - http://jsfiddle.net/tfgou78c/4/

JS:

$(function() {
    $('.submit_button').click(function() {
        var elem = $('.form_wrap');
        if (elem.css('display') == 'none') {
            elem.fadeIn(1750);
        }
        else {
            elem.fadeOut(1750);
        }
    });
});

CSS:

.form_wrap {
 display: none;
 }

/* sliding underline LEFT TO RIGHT */
.sliding-u-l-r {
display: inline-block;
}

.sliding-u-l-r:after {
content: '';
display: block;
height: 3px;
width: 0;
background: transparent;
transition: width .5s ease, background-color .5s ease;
}

.sliding-u-l-r:hover:after {
width: 100%;
background: blue;
}

Any help would be greatly appreciated.


Solution

  • Since this method are using the CSS event :hover you can't change that for click just on the code because there is no method for click on CSS. You can have:

    1. You tag this with Jquery so you can change the CSS match to:

      .sliding-u-l-r:hover:after
      

      to

      .sliding-u-l-r.clicked:after
      

      And then with Jquery:

      $('.sliding-u-l-r').on('click',function(){
         $(this).toggleClass('clicked');
      })
      

      Check this Demo Fiddle