Search code examples
actionscript-3flashactionscript

Flash as3 image slider


Im trying to get an image slider to work properly. But i don't get the next/prev functionality to work.

I have a container mc that holds all images, and a mask that acts as a mask for that container.

Here is how i add the images.

      for(var i:int = 0; i<this.container.numChildren; i++) {
            var mc:DisplayObject = this.container.getChildAt(i);
            if(mc is MovieClip) {
                mc.x = xPos;
                xPos += mc.width + margin;
                mc.y = 0;
            }
        }

So all images are now positioned in nice row with some margin. the mask and container has same x/y-position. So, lets say now that i set the witdth of the mask to display 5 of the images that the container holds.

How would i program the next/prev buttons so it displays or hide only one image on click? eg. tween the container position so it looks correct.

Here is my next and pre function. with is not working. Basically i want the container to always show same amount of items.

    private function slideLeft(event:MouseEvent):void {
        if(!TweenMax.isTweening(container)) {
            var tx:Number = Math.min(container.x + itemWidth, _mask.x);
            TweenMax.to(container, 0.3, {x:Math.floor(tx)});
        }
    }

    private function slideRight(event:MouseEvent):void {
        if(!TweenMax.isTweening(container)) {
            var tx:Number = Math.max(container.x - itemWidth, _mask.x-_mask.width);
            TweenMax.to(container, 0.3, {x:Math.floor(tx)});
        }
    }

Whats wrong? Anyone?


Solution

  • You need to account for the width of the container when showing items to the right. So the minimum x value for the container should be _mask.x - (container.width - _mask.width)

    You should also account for the margins or you will see the offset you described in your comment.

    private function slideLeft(event:MouseEvent):void {
        if(!TweenMax.isTweening(container)) {
            var tx:Number = Math.min(container.x + (itemWidth + margin), _mask.x);
            TweenMax.to(container, 0.3, {x:Math.floor(tx)});
        }
    }    
    
    private function slideRight(event:MouseEvent):void {
        if(!TweenMax.isTweening(container)) {
            var tx:Number = Math.max(container.x - (itemWidth + margin), _mask.x - (container.width - _mask.width);
            TweenMax.to(container, 0.3, {x:Math.floor(tx)});
        }
    }
    

    Good luck!