-2

Is there a way to affect a div that is out of view? Ex: when you scroll down the page and the div is no longer visible.

I have an embedded youtube video and I would like to mute it only when the video is no longer in view.

No Sssweat
  • 358
  • 1
  • 6
  • 24

2 Answers2

0

This will mute every video player that is not visible:

$(function() {
    var $w = $(window), oldw = 0, oldh = 0, oldt = 0;

    function checkVideoVisible() {
        if (oldw !== $w.width() || oldh !== $w.height() ||
                oldt !== $w.scrollTop()) {
            oldw = $w.width();
            oldh = $w.height();
            oldt = $w.scrollTop();
            var top = oldt, bottom = oldt + oldh;
            $("video").each(function() {
                var $this = $(this);
                if ($this.offset().top + $this.height() >= top &&
                        $this.offset().top < bottom) {
                    $this.prop("muted", false);
                } else {
                    $this.prop("muted", true);
                }
            });
        }
    }

Now to trigger the checking, you can either use a timer:

    var timerId = setInterval(checkVideoVisible, 200);
}

Or handle the scroll event:

    $w.on("scroll", checkVideoVisible);
}

In the latter case, you will also need to perform a check when any change is made to the dom.

Maurice Perry
  • 32,610
  • 9
  • 70
  • 97
  • sorry I'm such a noob, I don't really know javascript. I'm trying to get it working here http://jsfiddle.net/EGTbV/30/ I'm probably doing something wrong. – No Sssweat Jun 16 '14 at 13:40
  • 1) I've used jquery, so you will need to include it in your fiddle, 2) the script is in the onLoad handler, which makes $(function() { redundant, 3) your video is in an – Maurice Perry Jun 16 '14 at 13:50
  • Can't use video tag, unfortunately youtube made it that the video source url expires after x amount of time. Thus, I have to use the iframe way. What about using the mute from the youtube iframe API? https://developers.google.com/youtube/iframe_api_reference#mute – No Sssweat Jun 16 '14 at 14:36
0

Use this as its probably your best bet im guessing as you;ve posted no code that a pre-written lib will help you

JQ Visible Lib

To implement you need to give your element an id and reference it in script tags or in a js file like this:

$('#element').visible() will return true if visible.

You can then add the part to mute/pause the video based on that state.

Derple
  • 865
  • 11
  • 28