Search code examples
javascriptjquerymathgsap

Recalculate Radius on Window Resize


Here is a Simple truth.

Here is a guy at Change variable values on window.resize who has solved the Window resize update problem.

var windowHeight = $(window).height();

$(window).resize(function(){
    windowHeight = $(window).height(); // get new height after change

});

However it does not work when i try to It in this manner by doing:

radius = Math.round( (($(window).width()) * 0.1302) / Math.tan( Math.PI / itemLength ) );


$(window).resize(function(){
    radius = Math.round( (($(window).width()) * 0.1302) / Math.tan( Math.PI / itemLength ) );
});

The calculation works as it is supposed to but it never refreshes the calculation on resize.

can you help me figure out why that is ?


Solution

  • The Solution turned out to involve more than I had expected. It was a line by Mario Werner that finally led me to the solution. After hours of flaming and indications that I was stupidity itself. Mario finaly gave the clue I needed. He said; "Outside the function's scope the radius variable is not available and thus will not be changed by this event."

    This made me realize the problem and went on to do this:

    $(window).resize(function(){
    $(document).ready( init )
    
    function init()
    {
        w = $(window);
        container = $( '#contentContainer' );
        carousel = $( '#carouselContainer' );
        item = $( '.carouselItem' );
        itemLength = $( '.carouselItem' ).length;
        fps = $('#fps');
        rY = 360 / itemLength;
        radius = Math.round( (($(window).width()) * 0.1302) / Math.tan( Math.PI / itemLength ) );
    
    
        // set container 3d props
        TweenMax.set(container, {perspective:600})
        TweenMax.set(carousel, {z:-(radius)})
    
        // create carousel item props
    
        for ( var i = 0; i < itemLength; i++ )
        {
            var $item = item.eq(i);
            var $block = $item.find('.carouselItemInner');
    
    TweenMax.set($item, {rotationY:rY * i, z:radius, transformOrigin:"50% 50% " + -radius + "px"});
    
            animateIn( $item, $block )                      
        }
    
        // set mouse x and y props and looper ticker
        window.addEventListener( "mousemove", onMouseMove, false );
        ticker = setInterval( looper, 1000/60 );            
    }
    });
    

    I simply placed the resize event outside the init function and copy pasted the exact same init function inside resize event. This works!

    Thank you Mario!