Best way to hook callback using window resize function

I am trying to create a jQuery Cycle slide show where images of different sizes will be vertically and horizontally centered, and also resize any window size. Some of them are direct css, but I need to dynamically adjust the "top", "left", "extreme top" and "extreme left" in each image before fading in the first image of the slide show.

Thus, I believe that you need to create a callback when sizes and fields are set before the images appear. It is impossible to find a better way to do this.

CSS is simple. Essentially:

#gallery img { max-height: 100%; position:absolute; display:none; } 

And a rough cut .js will be:

 $(window).bind("load resize", function() { $('#gallery img').each(function(i) { var ih = $(this).height(); var iw = $(this).width(); var fh = Math.ceil(ih / 2); var fw = Math.ceil(iw / 2); $(this).css({ 'top' : '50%', 'left' : '50%', 'margin-top' : '-' + fh + 'px', 'margin-left' : '-' + fw + 'px' }); },function() { $('#gallery img:first').fadeIn(3000, function() { $('#gallery').cycle(); }); 

However, I do not see the expected result. The fadeIn of the first img starts before calculation and positioning.

The idea that "display: none" can be confusing (maybe nothing is calculated until it displays: block ", I tried to use:

 #gallery img:first-child { display:block; opacity:0; } 

.. And then the animation to full opacity instead of fadeIn - but the result is the same.

What am I doing wrong?

+4
source share
1 answer

I'm not quite sure what your code is trying to do, but I put that the problem may be more in the logic of events and loops. Your code reads as if you were trying to resume displaying the first image after resizing, not sure if I misunderstood your intention here.

Perhaps the separation in size and the logic of the gallery cycle, as this can help and keep the code more understandable; this will resize the images when resizing and launch the gallery on boot:

 $(document).ready( function() { function resizeThem() { $('#gallery img').each(function(i) { var ih = $(this).height(); var iw = $(this).width(); var fh = Math.ceil(ih / 2); var fw = Math.ceil(iw / 2); $(this).css({ 'top' : '50%', 'left' : '50%', 'margin-top' : '-' + fh + 'px', 'margin-left' : '-' + fw + 'px' }); }); } $(window).bind("resize", resizeThem); $(document).bind("load", function () { resizeThem(); $('#gallery img:first').fadeIn(3000, function() { $('#gallery').cycle(); }); }); 

});

Notice how the resize event behaves differently in browsers. In addition, it seems unnecessary to resize all images. How to resize the image on the display, and then, in turn, always resize the images when they are displayed in accordance with the size of the browser.

0
source

Source: https://habr.com/ru/post/1379827/


All Articles