Simen Lande
Simen Lande

Reputation: 3

Using jQuery/javascript to automatically center a div that is bigger than the window

I've been having some trouble making a div that is 1920px in width auto-center on the website. Right now i've been using this jQuery code to auto center the div when the page gets opened:

<script type="text/javascript">
$(window).load(function() {
    $('#slider').nivoSlider();

    var extra= 1920 - $(window).width(); 
    var extraleftside= extra/2;
    $("div#scroller").css("left", "-" + extraleftside + "px");
});
</script> 

But that code only adjusts when the website is refreshed, is it possible to make it do it in real time?

If you want to see the effect i want, it is the same as the scrolling background in this site: http://www.apps.no

LeGEC answered this quite nice, this code did the trick:

    <script type="text/javascript">
$(window).load(function() {
    $('#slider').nivoSlider();

    var extra= 1920 - $(window).width(); 
    var extraleftside= extra/2;
    $("div#scroller").css("left", "-" + extraleftside + "px");
}


);

$(window).bind("resize", resizeWindow);
function resizeWindow( e ) {
    var extra= 1920 - $(window).width(); 
    var extraleftside= extra/2;
    $("div#scroller").css("left", "-" + extraleftside + "px");
}
</script> 

Upvotes: 0

Views: 545

Answers (1)

LeGEC
LeGEC

Reputation: 52236

Do you mean recalculating it on resize ?

function doResize(){
    var extra= 1920 - $(window).width(); 
    var extraleftside= extra/2;
    $("div#scroller").css("left", "-" + extraleftside + "px");
}

$(window).load(function(){
    // maybe the slider should also be updated on resize...
    $('#slider').nivoSlider();

    doResize();
});

$(function(){
    $(window).resize(doResize);
});

Upvotes: 1

Related Questions