Trigger css change based on video play/pause - javascript

I'm learning and not sure how to ask this but here goes. I have buttons that I made from imgs, and want to use them to play one single video and have it automatically pause at specific times and then the img's css change. Then click the next img to start playing again until the next pause. I have it almost working. How can I change the css of the imgs along with playing/pausing the videos? I want to change their display to none/block once the video plays/pauses depending on my needs. Can I integrate it in what I have here? Can I add something like this.style.display = none/block? Where would I add it?
<video class="vid" id="myvideo" src="assets/fullvideo.mp4" playsinline muted>
</video>
<div class="btnsDiv">
<img src="imgs/btns/start.png" data-start="00" data-end="02" id="start" />
<img src="imgs/btns/continue.png" data-start="02" data-end="08" id="cont1" />
<img src="imgs/btns/continue.png" data-start="08" data-end="18" id="cont2" />
<img src="imgs/btns/yes.png" data-start="18" data-end="22" id="yes1" />
<img src="imgs/btns/no.png" data-start="18" data-end="22" id="no1" />
<img src="imgs/btns/continue.png" data-start="22" data-end="66" id="cont3" />
<img src="imgs/btns/yes.png" data-start="66" data-end="71" id="yes2" />
<img src="imgs/btns/no.png" data-start="66" data-end="71" id="no2" />
<img src="imgs/btns/continue.png" data-start="71" data-end="99" id="cont4" />
<img src="imgs/btns/admin.png" data-start="99" data-end="103" id="admin" />
<img src="imgs/btns/judicial.png" data-start="99" data-end="103" id="judicial" />
<img src="imgs/btns/continue.png" data-start="103" data-end="137" id="cont5" />
<img src="imgs/btns/question.png" data-start="137" data-end="170" id="findout" />
</div>
JS
let end;
const btns = document.querySelector('.btnsDiv');
const vid = document.querySelector('.vid');
btns.addEventListener('click', frag);
vid.addEventListener('timeupdate', stop);
function frag(event) {
const clicked = event.target;
if (clicked.matches('img')) {
let start = Number(clicked.dataset.start);
end = Number(clicked.dataset.end);
vid.currentTime = start;
vid.play();
}
return false;
}
function stop(event) {
const vid = event.target;
if (vid.matches('video')) {
if (vid.currentTime >= end) {
vid.pause();
}
}
// End function
return false;
}

Related

Changing the default button selection image on Javascript

I have found this helpful piece of code from the MartinJHiggings website (thank you).
The code is designed to play streaming audio. But it was designed when autoplay in browsers was allowed. It is no longer. But the default image is still 'pause' as it thinks audio is playing.
I basically want the default image to be 'play', which when clicked it should change to 'pause' and start the stream.
When clicked again, the image should change to 'play' and the stream should stop.
Any idea how I can do this please?
<script type="text/javascript">
function audioControl() {
var playdiv = document.getElementById('playdiv');
var pausediv = document.getElementById('pausediv');
var myAudio = document.getElementById('myAudio');
if (myAudio.paused) {
myAudio.play();
pausediv.style.display = 'block';
playdiv.style.display = 'none';
} else {
myAudio.pause();
pausediv.style.display = 'none';
playdiv.style.display = 'block';
}
}
</script>
<audio id="myAudio" autoplay preload="metadata">
<source src="http://IP:PORT/stream"></source>
Unfortunately your browser doesn't support html5 audio streaming, please update your browser.
</audio>
<button id="control" class="control" onclick="audioControl()">
<div id="playdiv" style="display:none">
<img src="play.png" width="96" height="96" alt="Play"/>
</div>
<div id="pausediv" style="display:block">
<img src="pause.png" width="96" height="96" alt="Pause"/>
</div>
</button>
You should remove the autoplay attribute on your audio element and then you should switch your divs style:
playdiv should be with style="display:block"
pausediv should be with style="display:none"
function audioControl() {
var playdiv = document.getElementById('playdiv');
var pausediv = document.getElementById('pausediv');
var myAudio = document.getElementById('myAudio');
if (myAudio.paused) {
myAudio.play();
pausediv.style.display = 'block';
playdiv.style.display = 'none';
} else {
myAudio.pause();
pausediv.style.display = 'none';
playdiv.style.display = 'block';
}
}
<audio id="myAudio" preload="metadata">
<source src="https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3"/>
Unfortunately your browser doesn't support html5 audio streaming, please update your browser.
</audio>
<button id="control" class="control" onclick="audioControl()">
<div id="playdiv" style="display:block">
<img src="play.png" width="96" height="96" alt="Play"/>
</div>
<div id="pausediv" style="display:none">
<img src="pause.png" width="96" height="96" alt="Pause"/>
</div>
</button>
Also available on JSFiddle.

the play button not working for the external video

When I click on the play/pause button nothing seems to happen, after clicking on the video I want to play, the vs code is not finding me any error nor the dev console.
I don't know what the issue is with the play/pause button.
Also, there is some issue with the third video, when I click on the third video it gives the following error:
Failed to load resource: the server responded :5500/favicon.ico:1 with a status of 404 (Not Found)
window.onload = init;
function init() {
var frame1 = document.querySelector('#video1');
frame1.innerHTML += ' <br> <button id="play">play </button> <button id="pause">pause</button> <button id="volume-up">volume up</button> <button id="volume down">volume-down</button> <button id="mute">mute</button> ';
}
//to play another video
var click = document.querySelectorAll('#videos > div');
click.forEach(function(elem) {
elem.addEventListener('click', nextPlaylist);
function nextPlaylist(evt) {
var save = elem.querySelector('.video').currentSrc;
var save1 = elem.querySelector('.video');
elem.innerHTML = `<video class="video" > <source src="${save}"> </video> <br> <button id="play">play </button> <button id="pause">pause</button> <button id="volume-up">volume up</button> <button id="volume down">volume-down</button> <button id="mute">mute</button> `;
var play = document.querySelector('#play');
play.addEventListener('click', playVid);
var pause = document.querySelector('#pause');
pause.addEventListener('click', pauseVid);
function playVid() {
save1.play();
}
function pauseVid() {
save1.pause();
}
}
}
);
<body>
<header class="head">
VIDEO PLAYER
</header>
<div id="videos">
<div id="video1">
<video class="video" controls>
<source src="https://www.videvo.net/videvo_files/converted/2018_04/preview/180301_06_A_CityRoam_03.mp420186.webm">
</video>
</div>
<div id="video2">
<video class="video" controls>
<source src= "https://www.videvo.net/videvo_files/converted/2016_01/preview/Forest_15_2_Videvo.mov92730.webm">
</video>
</div>
<div id="video3">
<video class="video" controls>
<source src="https://www.videvo.net/videvo_files/converted/2016_09/preview/160820_125_NYC_OutOfFocusCarLights5_1080p.mp444096.webm">
</video>
</div>
</div>
<script src="video.js"></script>
</body>
There are several issues with the code.
You declare the video element but then override it.
var save1= elem.querySelector('.video');
but then, you remove that element and render a different one
elem.innerHTML = `<video class="video" >...
So you need to retrieve it again (or just move var save1= elem.querySelector('.video'); after the line above.
When the user clicks on the buttons the parent's listener (elem.addEventListener('click', nextPlaylist); also get fired, so it re-render the videos.
To avoid that, use stopPropagation to prevent from the event from propagate to the parent
You have multiple id attribute with the same value (when the user clicks on more than one video) so document.querySelector catch the first one (which wasn't work too because the reasons above).
Replace the ids to classes and use elem.querySelector instead of document.querySelector to make sure it will find the buttons in a specific div.
//to play another video
var click = document.querySelectorAll('#videos > div');
click.forEach(function(elem) {
elem.addEventListener('click', nextPlaylist);
});
function nextPlaylist(evt) {
const elem = evt.currentTarget;
var save = elem.querySelector('.video').currentSrc;
elem.innerHTML = `<video class="video" > <source src="${save}"> </video> <br> <button class="play">play </button> <button class="pause">pause</button> <button id="volume-up">volume up</button> <button id="volume down">volume-down</button> <button id="mute">mute</button> `;
var save1 = elem.querySelector('.video');
var play = elem.querySelector('.play');
play.addEventListener('click', playVid);
var pause = elem.querySelector('.pause');
pause.addEventListener('click', pauseVid);
function playVid(e) {
e.stopPropagation();
save1.play();
}
function pauseVid(e) {
e.stopPropagation();
save1.pause();
}
}
<header class="head">
VIDEO PLAYER
</header>
<div id="videos">
<div id="video1">
<video class="video" controls>
<source src="https://www.videvo.net/videvo_files/converted/2018_04/preview/180301_06_A_CityRoam_03.mp420186.webm">
</video>
</div>
<div id="video2">
<video class="video" controls>
<source src= "https://www.videvo.net/videvo_files/converted/2016_01/preview/Forest_15_2_Videvo.mov92730.webm">
</video>
</div>
<div id="video3">
<video class="video" controls>
<source src="https://www.videvo.net/videvo_files/converted/2016_09/preview/160820_125_NYC_OutOfFocusCarLights5_1080p.mp444096.webm">
</video>
</div>
</div>
By the way, you can move the function out. It's a shame to create new function for each element instead of only one.
https://jsbin.com/koritub/edit?html,js,output

Jquery : Play video in bootstrap slider

i want to play video when item gets active class in bootstrap slider below is my code
<div class="item" id='mobileapp'>
<video loop controls width="100%" id='video'>
<source src="../../vid.mp4" width="100%" height="100%" type="video/mp4"> Your browser does not support the video tag.
</video>
<div class="overlay"></div>
<div class="carousel-caption">
<h1 class="super-heading text-white">Heading</h1>
<div class='row'>
<div class='col-sm-2 col-sm-offset-1'>
<img src='../img/googleplay.png' class='img-responsive hidden-xs' />
</div>
<div class='col-sm-2'>
<img src='../img/applestore.png' class='img-responsive hidden-xs' />
</div>
</div>
</div>
</div>
Js
<script>
$(document).ready(function () {
if ($('#mobileapp').hasClass('active')) {
$('#video')[0].play();
}
else {
$('#video')[0].pause();
}
})
</script>
active class gets added but it does not pay video
the functions 'play' and 'pause' are not jquery functions, they belong to the DOM element. Now to make it work try to execute your code every 10 miliseconds or something like that.
Try:
var videoElt = document.getElementById('video');
$(document).ready(function () {
setInterval(function () {
if ($('#mobileapp').hasClass('active')) {
videoElt.play(); // to play the video
}
else {
videoElt.pause(); // to pause the video
}
}, 10);
});

How to create a series of animation in my case?

I have series of images that I want to play them as a series of animation in html
<img src='image1.png' />
<img src='image2.png' />
<img src='image3.png' />
<img src='image4.png' />
<img src='image5.png' />
<img src='image6.png' />
<img src='image7.png' />
<img src='image8.png' />
<img src='image9.png' />
<img src='image10.png' />
<img src='image11.png' />
<img src='image12.png' />
They all need to on the same position but just swap very fast from image 1 to image 12 to make it looks like an animation.
Is there a way to do this properly? I have searched google but had no luck. Thanks for the help!
The best way is only to have one Image and only change the image src attribute. Like
<img src="image1.png" id="animationImage" />
Afterwards you can simply change for example with an setInterval:
var imageId = 1;
window.setInterval("changeImage()", 100);
function changeImage(){
imageId++;
if (imageId > 12)
imageId = 1;
$("#animationImage").attr("src", "image" + imageId + ".png");
// if you are NOT using jQuery, use this line instead:
document.getElementById("animationImage").src = "image" + imageId + ".png"
}
of course you can also simply hide/add the images:
HTML
<img src="image1.png" class="animationImage" />
<img src="image2.png" class="animationImage" />
<img src="image3.png" class="animationImage" />
<img src="image4.png" class="animationImage" />
<img src="image5.png" class="animationImage" />
<img src="image6.png" class="animationImage" />
<img src="image7.png" class="animationImage" />
<img src="image8.png" class="animationImage" />
<img src="image9.png" class="animationImage" />
<img src="image10.png" class="animationImage" />
<img src="image11.png" class="animationImage" />
<img src="image12.png" class="animationImage" />
Javascript:
$(".animationImage:not(:first)").hide();
var imageId = 0;
window.setInterval("changeImage()", 100);
function changeImage(){
$($(".animationImage")[imageId]).hide();
imageId++;
if (imageId > 11)
imageId = 0;
$($(".animationImage")[imageId]).show();
}
In both examples, the number 100 represents the amount of milliseconds the application will wait before showing the next image.
Edit The last solution assumes to use the jQuery library.
Note: jQuery is required for this solution
I will do this using jQuery:
function swap()
{
var images = $("img");
var on = false;
for(var i = 0; i < images.length; i++)
{
if($(images[i]).css("display") != "none")
{
on = true;
$(images[i]).css("display", "none");
}
else if(on)
{
on = false;
$(images[i]).css("display", "block");
}
}
if(on)
{
$(images[i]).css("display", "block");
}
}
This will swap each image to the next in order when called:
$(document).ready(function(){
setInterval(function(){swap();}, 1000/30);
});
JSFiddle

How can I create an image "change" effect in JQuery? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have the following structure:
<div class="container">
<img src="images/1.png" class="image_wall_thumbnail" />
<img src="images/2.png" class="image_wall_thumbnail" />
<img src="images/3.png" class="image_wall_thumbnail" />
<img src="images/4.png" class="image_wall_thumbnail" />
<img src="images/5.png" class="image_wall_thumbnail" />
<img src="images/6.png" class="image_wall_thumbnail" />
</div>
What I want to do is use the existing images I am using in the image tags and every 2-5 seconds I want to slowly fade one image and in it's place show another image (one of the existing images in the other image tags) and I want this effect to take place randomly.
I've never done this before so not sure how to go about this? I am thinking fade in and fade out makes sense but not sure how to tackle this. Any ideas?
Okay, so like any programming task you want to break something like this down into simple steps. In this case, maybe something like this:
When the page loads, only show the first image. To do this, you should have a display:none CSS rule on all of the images EXCEPT for the first one. This can easily be accomplished by created a class called hide and applying it to the HTML. We could also manage this via JS, but that may cause bugs depending on the internet connection that your users have...
Every five seconds, fade the current image out, and fade the next one in.
If we are on the last image, make sure we go back to the first image in the list.
That's pretty much all we need to do, so let's write some code:
First, let's refactor your markup to use an id for the container and then add the CSS class to all images but the first.
<div id="img_container">
<img src="images/1.png" class="image_wall_thumbnail" />
<img src="images/2.png" class="hide image_wall_thumbnail" />
<img src="images/3.png" class="hide image_wall_thumbnail" />
<img src="images/4.png" class="hide image_wall_thumbnail" />
<img src="images/5.png" class="hide image_wall_thumbnail" />
<img src="images/6.png" class="hide image_wall_thumbnail" />
</div>
Next, let's write a little CSS:
.hide {
display:none;
}
Okay now is the "tricky" part where we write some JS:
$(function() {
//cache dom elements and set init vars
var $img = $('#img_container').find('img'),
max = $img.length, //how many images you have in the container
current = 0; //we will start the script at the first item
//Every five seconds, run the code within the handler
setInterval(function(){
$($img[current]).fadeOut('fast', function(){
determineIndex(); //Update the index of the image in the img array
$($img[current]).fadeIn();
});
}, 5000);
function determineIndex () {
current = (current === max - 1) ? 0 : (current + 1);
}
});
Now here's the demo! http://jsfiddle.net/T2nzh/
Comment if you have any questions about how the javascript works. :)
EDIT: Okay, so if you want to just randomly swap out image sources, check this out. The html you want:
<div id="img_container">
<img src="images/1.png" style="background:red" class="image_wall_thumbnail" />
<img src="images/2.png" style="background:silver" class="image_wall_thumbnail" />
<img src="images/3.png" style="background:purple" class="image_wall_thumbnail" />
<img src="images/4.png" style="background:yellow" class="image_wall_thumbnail" />
<img src="images/5.png" style="background:green" class="image_wall_thumbnail" />
<img src="images/6.png" style="background:blue" class="image_wall_thumbnail" />
</div>
<div id="img_spares" style="display:none;">
<img src="images/7.png" style="background:magenta" class="image_wall_thumbnail" />
<img src="images/8.png" style="background:brown" class="image_wall_thumbnail" />
</div>
And the JS:
$(function() {
//cache dom elements and set init vars
var $img = $('#img_container'),
$spares = $('#img_spares'),
max = $img.find('img').length,
spares_max = $spares.find('img').length;
//Every five seconds, run the code within the handler
setInterval(function(){
$($img.find('img')[randomIndex(0,max)]).fadeOut('fast', function(){
var $el = $(this),
el_source = $el.attr('style'),
$swap = $($spares.find('img')[randomIndex(0,spares_max)]),
swap_source = $swap.attr('style');
$el.attr('style', swap_source).fadeIn();
$swap.attr('style', el_source);
});
}, 1000);
function randomIndex (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
});
And the demo: http://jsfiddle.net/T2nzh/3/
take a look:
<div class="container">
<img src="images/1.png" class="image_wall_thumbnail" />
<img src="images/2.png" class="image_wall_thumbnail" />
<img src="images/3.png" class="image_wall_thumbnail" />
<img src="images/4.png" class="image_wall_thumbnail" />
<img src="images/5.png" class="image_wall_thumbnail" />
<img src="images/6.png" class="image_wall_thumbnail" />
</div>
then the jQuery:
var slide = 1;
function slideshow() {
$("#container").find("img").animate({opacity:0});
setTimeout('$("#container").find("img").hide();',400);
setTimeout('$("#container").find("[src='images/"+slide+".png']").show();',400);
setTimeout('$("#container").find("[src='images/"+slide+".png']").animate({opacity:1});',400);
slide++;
}
var slideshow = setInterval("slideshow();",3000);
also, set the opacity to 0 and display to none for all the images. This code has not beenj tested so you might have to make some minor adjustments.

Categories