fightstarr20
fightstarr20

Reputation: 12608

Animate border left to right

I am trying to animate a bottom border on a div so that it looks like a line sliding in from the right.

I am using jQuery but can't seem to work out how to achieve it, can anyone point me in the direction of a tutorial or reading on it?

Upvotes: 1

Views: 8725

Answers (3)

Rory McCrossan
Rory McCrossan

Reputation: 337646

This is not possible using a border. You can only animate the width of the bottom border (which appears to be it's height), not it's left/right position or horizontal width.

Instead, look at creating an absolutely positioned element within the element, and animating the width of that instead.

<div id="foo">
    Foo
    <div class="slider"></div>
</div>
#foo {
    font-size: 2em;
    position: relative;
    padding: 30px;
}
.slider {
    position: absolute;
    bottom: 0;
    left: 0;
    height: 2px;
    background-color: #C00;
    width: 0%;
}
$('.slider').animate({
    width: $('#foo').width()
}, 1000);

Example fiddle

Upvotes: 7

Drea58
Drea58

Reputation: 438

You don't need to use javascript. Using transitions, you can do the animation with css3, too.

fiddle http://jsfiddle.net/Drea/e7sf401q/

relevant code:

html

<div id="foo">hover me
    <div class="slider"></div>
</div>

css

.slider{
    transition: width 2s ease;
    width: 0%;
 }

For a hover effect:

#foo:hover .slider{
    width: 100%;
}

Or add a class with jquery, for use as on-click event.

.sliderAnimate {
    width: 100%;
}

Upvotes: 2

Scott Mitchell
Scott Mitchell

Reputation: 698

Reference per Rory in fiddle

HTML

<div id="example"><div id="sample"></div></div>

JS

$( '#sample' ).animate({
width: "100%",
}, 1500 )

CSS

#example{ height: 100px; width: 100px; }

#sample { border-bottom: 1px solid black; width: 0px; }

http://jsfiddle.net/p4zondkn/

Upvotes: 2

Related Questions