0

I have a list of images on: http://johanberntsson.se/dev/fotosida/

What would be a good way to get a data attribute from the image thats currently in the center of the screen? Place an invisible line in the center of the screen and see which image that it collides with? Or do you have any other suggestions?

Hope you get the idea, otherwise ill elaborate.

Thanks!

Johan
  • 31,613
  • 48
  • 166
  • 272
  • Cool photos. Does this help? http://stackoverflow.com/questions/8229291/how-to-check-if-an-element-is-in-the-view-of-the-user-with-jquery – Pekka Mar 12 '12 at 19:47
  • @gdoron I think he means the image that is currently in view while scrolling – Pekka Mar 12 '12 at 19:47
  • ALso http://stackoverflow.com/questions/2556168/how-to-detect-that-an-html-element-is-in-view – Pekka Mar 12 '12 at 19:48
  • @Pekka Thanks, and yes it does. Ill have a look at that :) – Johan Mar 12 '12 at 19:48
  • @Pekka Do you know if there is a way to decrease the viewport size a bit? To maybe 80% instead of the entire screen? – Johan Mar 12 '12 at 19:57
  • You mean resize the browser window? – Pekka Mar 12 '12 at 19:58
  • @Pekka No, i try to log the image which is currently beeing shown, but at the moment i always (almost) get 2 images with `$(".mainimages:in-viewport")`. See the log on my page for example. – Johan Mar 12 '12 at 19:59
  • but that depends on your screen size, doesn't it? You'll have to define which image is *more* "visible"... Possibly using something like Marshall shows below – Pekka Mar 12 '12 at 20:01
  • @Pekka Yep, ill have a look at that, thanks – Johan Mar 12 '12 at 20:02

1 Answers1

0

You could do something like this:

// finding the center point of the screen
// note that $(window).height() returns the height of the viewport
var center = Math.floor(($(window).height() / 2)) + $(window).scrollTop();

// looping through images and checking each for being in middle
$('.mainimages').each(function(i, img) { 
    var top = $(img).offset().top;
    if(top <= center && top + $(img).height() >= center) {
        // $(img) is in the center
    }
});

I don't use jQuery so I'm not certain if there are better methods to use to do this.

Also, not that I do not account for the margin / padding between images. So if you were to do something like put a colored border on the centered image (with no border on others) then there will be moments between images where no image will have a border.

Marshall
  • 4,348
  • 1
  • 16
  • 12