Sheldon Sheldon - 2 months ago 16
jQuery Question

change class :before selector with jquery to animate underscoring

I want to animate the underscoring of a text. This is no problem with css. However, I want to use another text to trigger the animation of the first text. I already know that you can't use :before in jquery as it's not part of the DOM. I've seen these two threads: Access the css ":after" selector with jQuery and Selecting and manipulating CSS pseudo-elements such as ::before and ::after using jQuery

But I couldn't find any solution that works. Here is the code: https://jsfiddle.net/rbsxufsc/4/

html:

<h2 class='uno'>
<a href=''>:hover, please</a>
</h2>
<h2 class='dos'>
<a href=''>Animate above text</a>
</h2>


css:

h2 > a:before {
content: "";
position: absolute;
width: 100%;
height: 3px;
bottom: 0;
left: 0;
background: #9CF5A6;
visibility: hidden;
border-radius: 5px;
transform: scaleX(0);
transition: .25s linear;
}
h2.uno > a:hover:before,
h2.uno > a:focus:before {
visibility: visible;
transform: scaleX(1);
}


When hovering the first text, it is well animated. When hovering the second text, I want to animate the first text again as if the first text is hovered. Is there any way to do that?

Answer

You can add a class to the uno element onmouseover on the dos element.

The css that I added is:

h2.uno.active > a:before {
    visibility: visible;
    transform: scaleX(1);
}

Here is the working example:

$(function() {
	$('.dos a').on('mouseover', function() {
  	$('.uno').addClass('active')
  }).on('mouseout', function() {
  	$('.uno').removeClass('active')
  })
})
@import url(http://fonts.googleapis.com/css?family=Quando);
*, *:after, *:before {
  box-sizing: border-box;
  -moz-box-sizing: border-box;
}
* {margin:0;padding:0;border:0 none;position: relative; outline: none;
}
html, body {
  background:  #004050;
  font-family: Quando;
  font-weight: 300;
  width: 100%;
}
h2 {
  background: #0D757D;
  width: 100%;
  min-height: 200px;
  line-height: 200px;
  font-size: 3rem;
  font-weight: normal;
  text-align: center;
  color: rgba(0,0,0,.4);
  margin: 3rem auto 0;
}
.dos {background: #ff5e33;}

h2 > a, h3 > a {
  text-decoration: none;
  color: rgba(0,0,0,.4);
  z-index: 1;
}

h2 > a:before {
  content: "";
  position: absolute;
  width: 100%;
  height: 3px;
  bottom: 0;
  left: 0;
  background: #9CF5A6;
  visibility: hidden;
  border-radius: 5px;
  transform: scaleX(0);
  transition: .25s linear;
}
h2.uno > a:hover:before,
h2.uno > a:focus:before,
h2.uno.active > a:before {
  visibility: visible;
  transform: scaleX(1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2 class='uno'>
  <a href=''>:hover, please</a>
</h2>

<h2 class='dos'>
  <a href=''>Animate above text</a>
</h2>