2

I am trying a transition where a line becomes a long rectangle. I want to make it so that when the transition finishes, the final state remains in place even when the mouse is not hovered on it.

This is my current code:

#line {
    width: 300px;
    height: 1px;
    background-color: darkblue;
    transition: height 2s;
    -webkit-transition: height 2s;
}

#line:hover {
    width: 300px;
    height: 200px;
    background-color: darkblue;
}
<div id="line"></div>
TylerH
  • 20,799
  • 66
  • 75
  • 101
Asem H
  • 93
  • 9
  • This is definitely a duplicate question, but while I find a good target, the answer is `animation-fill-mode: forwards;` – TylerH Oct 15 '15 at 19:01
  • @TylerH That's for an animation. Does it work for transitions too? – GolezTrol Oct 15 '15 at 19:04
  • @GolezTrol I think it does, though I don't know about on `:hover`. Anyway it looks like OP isn't actually dealing with animations here; I'll edit the question. – TylerH Oct 15 '15 at 19:09
  • @GolezTrol Hey, I have a small follow-up question. What if, instead of hovering my mouse, I want the animation to start after it is clicked? – Asem H Oct 15 '15 at 19:19
  • There is no relationship between maintaining the final state of an animation and keeping a transitioned hover state. So, I would answer to @GolezTrol that no, it won't work in this scenario – vals Oct 15 '15 at 21:08

2 Answers2

4

I think the best solution is to add a small script that adds a class. The class remains after unhovering:

window.addEventListener('DOMContentLoaded', function() {
  document.getElementById('line').addEventListener('mouseover', function(event) {
    document.getElementById('line').classList.add('activated');
  });
});
#line {
  width: 300px;
  height: 1px;
  background-color: darkblue;
  transition: height 2s;
  -webkit-transition: height 2s;
}
#line.activated{
  width: 300px;
  height: 200px;
  background-color: darkblue;
}
<body>

  <div id="line"></div>

</body>
GolezTrol
  • 114,394
  • 18
  • 182
  • 210
0

A tricky way to get this effect only with CSS: set the transition-delay on the element to a huge value. and set it to 0 on the hover state

When you hover, the element changes to the hover state, and this way the transition is immediate.

When you un-hover, there will a 9999s delay before it begins (well, not really for ever, but nobody will notice)

#line {
  width: 300px;
  height: 10px;
  background-color: darkblue;
  -webkit-transition: height 1s 9999s;
  transition: height 1s 9999s;
}
#line:hover{
  width: 300px;
  height: 200px;
  background-color: darkblue;
  -webkit-transition-delay: 0s;
  transition-delay: 0s;
}
<body>
  <div id="line"></div>
</body>
vals
  • 61,425
  • 11
  • 89
  • 138