Question

I basically am using a jQuery cycle for a banner image in which i have images that are an array of sizes. I am trying to get the images to vertically align central to the height of the LI. Now i've got something that roughly works, but in a bad way.

You can view my workings here:

http://jsfiddle.net/X4GQC/

My HTML:

<div id="slider">
    <ul class="slidah">
        <li><img src="img/slide1.jpg" alt=""></li>
        <li><img src="img/slide1.jpg" alt=""></li>
        <li><img src="img/slide1.jpg" alt=""></li>
        <li><img src="img/slide1.jpg" alt=""></li>
    </ul>
</div>

My jQuery:

(function ($) {
    $.fn.vAlign = function(fn) {

        return this.each(

            function(i){

                var ah = $(this).height();
                var ph = $(this).parent().height();
                var mh = Math.ceil((ph-ah) / 2);
                $(this).css('margin-top', mh);
            });
    };
})(jQuery);

$('.slidah').cycle({
    after: function(){
        $(".slidah li img").vAlign();
    }
});

My CSS:

#slider{
    width: 100%;
    height: 200px;
    overflow: hidden;
}

.slidah{
    width: 100%;
    height: 200px;
}

.slidah li{
    width: 100%;
    height: 200px;
}

Now as you can see, the vertical align function does work, but it triggers after the cycle happens. I've tried before however this did not work. I need a way to re-fire the event at the same time the cycle happens perhaps?

Was it helpful?

Solution

i believe because of what jquery .cycle() is doing, you are always going to get wonky results attacking the problem this way. my first thought is to do the calculations for all of the list items on jquery document ready and set each of their margin-tops immediately after DOM load. hence trying to resolve this issue with initial CSS rather then relying on calling a function at / before / or as a callback of each jquery .cycle call.

this approach should yield more stable results. ill see if i can get a fiddle up in a few.

EDIT: here is your modified jquery working for me in a fiddle here with no glitch-y functionality or other issues like the example you provided. enjoy

(function ($) {
    $.fn.vAlign = function(fn) {

        return this.each(

            function(i){

                var ah = $(this).height();
                var ph = $(this).parent().height();
                var mh = Math.ceil((ph-ah) / 2);
                $(this).css('margin-top', mh);
            });
    };
})(jQuery);


$(document).ready(function(){
    $(".slidah li img").vAlign();
});

$('.slidah').cycle({});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top