Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

HTML

Does anyone know how to have an autoplayed video stop audio from playing and disappear at a specific media query bpoint?

I am having an issue with my video code. I need it to auto play at a desktop size but have the whole video disappear at 768px. I was able to take out the video with the code below but I can't pause the audio. If you guys also know how to have the video refresh and restart playing from the beginning when it goes back to desktop size that would be great? Code below! If there is a way to do it with jquery let me know, thanks :)

<!DOCTYPE html> <html>

<style>

video{ visibility:visible;}

@media (max-width: 768px) {

video{ display:none;}


}

</style> <body>

<video width="320" height="240" controls autoplay> <source src="movie.mp4" type="video/mp4"> <source src="movie.ogg" type="video/ogg">

</video>

</body> </html>

1 Answer

Well, you have a lot of goals that I can say would probably be handled best by JavaScript.

You can have video muted by adding the boolean attribute "muted" to the video element. Your HTML should follow a mobile first build scheme, so I would suggest:

<video width="320" height="240" class="video" controls autoplay muted> <source src="movie.mp4" type="video/mp4"> <source src="movie.ogg" type="video/ogg">

Your CSS (or <style> tag) should target everything below thresholds first.. so basically it changes styling once you resize to bigger screens. The code below shows the video once the browser is resized to 768. By the way, you mentioned "desktop" but keep in mind that 768px is basically considered a default tablet breakpoint.

.video {
     display: none;
}

@media (min-width: 768px) {
    .video {
          display: block;
   }
}

As for the video refresh upon breakpoint, I have recently played around with the window resize listener function, and matchMedia...

So something like this:

$(window).resize(function(){
        if (window.matchMedia("(min-width: 768px)").matches) {
                $(".video").load();
                $(".video").play();
    }
});

Keep in mind that matchMedia doesn't work for most versions of internet explorer.. IE 10 or less.