Alvaro Bascunan Alvaro Bascunan - 6 months ago 43
jQuery Question

TranslateX a child div inside of a 100% width parent

I'm trying to make some jQuery fun on my website, the idea is that when you scroll down the page the parent div grows to be 100% width for responsive design, and works great, and at the same time I want to

translateX
the child div and stay always at the right edge of the parent for the animation and for different viewport sizes, only way I can make this work is with
float: left;
and
addClass
of
right: 0;
. It works, but it just jumps to the right. Is there a way to animate this?

I found this, but it does not solve my problem because the parent has an exact pixel width:

How to use transform:translateX to move a child element horizontally 100% across the parent

<div class = "parent">
<div class = "child"></div>
</div>


CSS

.parent {
position: relative;
width: 180px;
height: 180px;
transition: all ease-in-out 300ms;
}

.child {
position: absolute;
width: 180px;
height: 180px;
float: left;
transition: all ease-in-out 300ms;
}

.moveParent {
width: 100%;
}

.moveChild {
right: 0px;
}


jQuery

$(window).scroll(function(){
var wScroll = $(this).scrollTop();
if(wScroll > $('.parent').offset().top){
$('.parent').addClass('moveParent');
$('child').addClass('moveChild');
}
});

Answer

CSS transitions have to change from something to something else, so it won't work if you just say right: 0;. For the animation to work correctly, you'll need to set a default right value.
Change your css to look like this:

CSS

.child {
    position: absolute;
    width: 180px;
    height: 180px;
    right: calc(100% - 180px);
    transition: all ease-in-out 300ms;
}

This will align the div to the left initially by calculating right: 100% - your div's width (180px). Then after the hover, it will animate to the right with right: 0;.

JSFiddle

Comments