3

Recently facebook has added a functionality where when a facebook video is in the screen, it will automatically play and if it leaves the screen OR even just hide a part of it from scrolling, the video will stop playing.

I want to implement this functionality in my site which renders a series of pictures, and when the picture hit the screen, a jquery post will be made to update that photos' view count in the database. The difference with facebook is that it will only post ONCE every page reload. So scrolling up and down repeatedly will not update the view count.

I have found this jquery code and tried it but it uses an elementid of the div attached to window.on('scroll') which in my case won't work as the pictures in my site are loaded dynamically with different id's. Here's how I display pictures in my site:

//note that this is a result of foreach loop
<div class="photoContainer">
  <img src="something1.jpg" />
</div>
<div class="photoContainer">
  <img src="something2.jpg" />
</div>
<div class="photoContainer">
  <img src="something3.jpg" />
</div>

Here is a "somehow" working jquery snippet that I found here Check if element is visible on screen

function checkVisible( elm, evalType ) {
    evalType = evalType || "visible";

    var vpH = $(window).height(), // Viewport Height
        st = $(window).scrollTop(), // Scroll Top
        y = $(elm).offset().top,
        elementHeight = $(elm).height();

    if (evalType === "visible") return ((y < (vpH + st)) && (y > (st - elementHeight)));
    if (evalType === "above") return ((y < (vpH + st)));
}

Can you help me transform this jquery code to be usable in my page as Im not really good with it.. Any help is appreciated. Please ask if you need more details.

EDIT: I need the div to be ENTIRELY visible to the screen before the view count. jQuery code above executes even just a tiny part of the div is visible.

Community
  • 1
  • 1
super-user
  • 827
  • 3
  • 12
  • 37

1 Answers1

2

I would recommend using a library like onScreen to help you do what you want faster. it will fire an event or something when the element is on screen!

here's a sample for the options provided by the library

$('elements').onScreen({
   container: window,
   direction: 'vertical',
   doIn: function() {
     // Do something to the matched elements as they come in
   },
   doOut: function() {
     // Do something to the matched elements as they get off scren
   },
   tolerance: 0,
   throttle: 50,
   toggleClass: 'onScreen',
   lazyAttr: null,
   lazyPlaceholder: 'someImage.jpg',
   debug: false
});

If you want to learn how to do it here's a cool refrence to learn from (It helped me in a tiny project back in time)

http://upshots.org/javascript/jquery-test-if-element-is-in-viewport-visible-on-screen

Khaled Al-Ansari
  • 3,548
  • 1
  • 22
  • 26