mixerowsky
mixerowsky

Reputation: 217

New value after applying css() in jQuery

I'm scaling a div in order to be visible without scrolling. So I have:

var sliderOffset = $('.field-slideshow-wrapper').offset().top,
    windowHeight = $(window).height(),
    sliderAllowed = (windowHeight - sliderOffset),
    sliderImage = $('.field-slideshow-slide img').height(),
    sliderOriginal = (sliderImage + 150),
    scale = (sliderAllowed / sliderOriginal);

$('.field-slideshow-wrapper').css({ transform: 'scale(' + scale + ')'});

Now that div is not on the same position from top as before and I need to determine new offset from top, after css({ transform: 'scale(' + scale + ')' is applied, so I can calculate some margin to move this div at the top.

How to determine new offset().top of the element?

Upvotes: 3

Views: 87

Answers (2)

KWeiss
KWeiss

Reputation: 3154

There are two ways you could do this and the choice is yours. The transform: scale() shrinks the element toward its center, so the top of the element moves down. The scaled element will still return the non-scaled element's offset().top, so that won't work.

One option is to just make sure the newly scaled element will stick to the top of the old element's space. Just do this:

$('.field-slideshow-wrapper').css({ 
    transform: 'scale(' + scale + ') translateY(-50%)'
});

This makes the element move up by 50% of its new height, thus sticking it to the top of its old dimensions.

The other option is to do some simple calculation. Get the old element's height, then get the number of pixels the scale() method has moved it "down". You can find the number by some calculations (see below), and that's the number you can add to the old offset().top to get the new one:

var sliderOffset = $('.field-slideshow-wrapper').offset().top,
            windowHeight  = $(window).height(),
            elHeight = $('.field-slideshow-wrapper').innerHeight(),
            sliderAllowed   = (windowHeight - sliderOffset),
            sliderImage = $('.field-slideshow-slide img').height(),
            sliderOriginal = (sliderImage + 150),
            scale = (sliderAllowed / sliderOriginal);
var addProportion = 1-scale / 2;

var newOffset = sliderOffset + (addProportion * elHeight);

Whether you should use innerHeight() or outerHeight() depends on your layout.

Upvotes: 3

Michael Maaß
Michael Maaß

Reputation: 104

well just get the new offset after you've applied the scaling

...    
$('.field-slideshow-wrapper').css({ transform: 'scale(' + scale + ')'});
var newOffset = $('.field-slideshow-wrapper').offset().top;

Upvotes: 0

Related Questions