Search code examples
jquerycss-positionhorizontal-accordion

JQuery horizontal accordion banner absolute positioning error


The following code operates a JQuery based horizontal animation system.

$(document).ready(function(){
    maxWidth = 700;
    minWidth = 65;
    normWidth = 192;

    var featspos = 0;   

    $('.featuredslider a').each(function(){
        $(this).css('left', featspos+'px');
        featspos += 192; 
    });

     $(".featuredslider a").mouseenter(function(){
         var featscur = $(this).index();
         $('.featuredslider a').each(function(){
            featspos = 0;
            $(this).animate({left: featspos},800);
            if($(this).index() == featscur){ featspos += 700 } else { featspos += 65; };
         });
     });
     $(".featuredslider a").mouseleave(function(){
        $(this).css('left', featspos+'px');
        featspos += 192; 
     });
});

There seams to be an absolute positioning problem because as soon as the mouse enters any one of the pictures they all move to left:0px; Additionally the function to get them back again will not work either. They just sit there at 0px;

I have set up a reference FIDDLE so I hope this helps solve the problem. http://jsfiddle.net/FzaxF/1/


Solution

  • I made a few changes: http://jsfiddle.net/mblase75/FzaxF/6/

    You had an .each loop in the mouseenter event when it should have been in mouseleave. I also reset featspos to zero at the start of the mouseleave event and added a stop() to interrupt the animation if the user moused out before it was done animating.

    Finally, resetting the images was moved to a function to eliminate some redundant code.

    $(document).ready(function() {
        maxWidth = 700;
        minWidth = 65;
        normWidth = 192;
    
        function resetter() {
            var featspos = 0;
            $('.featuredslider a').each(function() {
                $(this).stop().css('left', featspos + 'px');
                featspos += 192;
            });
        }
        resetter();
    
        $(".featuredslider a").mouseenter(function() {
            var featscur = $(this).index();
            featspos = 0;
            $(this).animate({
                left: featspos
            }, 800);
            if ($(this).index() == featscur) {
                featspos += 700
            } else {
                featspos += 65;
            };
        });
        $(".featuredslider a").mouseleave(function() {
            resetter();
        });
    
    });