Adjust this code so the video only plays once on the website - javascript

I am helping a friend make a website and am a novice with javascript so could do with a little help. I have researched on here and see that some similar questions have been asked before but would like to know exactly how to relate this back to my code. So far this code works well, when you load up the homepage, the video clip runs IF the window is wider than 600px, but the video clip doesn't run if the window is less than 600 pixels. Also the other javascript makes the video disappear once it's played. However the problem I have is if you go to another page on the site, and then back to the home page, the video plays again and again, but I want the video to play only once when the visitor arrives to the site. Could anyone advise how I would edit the code so that the video only runs once per visit? All relevant code is below:
<script type="text/javascript">
window.addEventListener('load', function() {
if (window.innerWidth >= 600) {
var vid = document.getElementById('video');
var wrap = document.getElementById('videowrapper');
wrap.classList.toggle('hide');
vid.play();
vid.addEventListener('ended',function(e) {
wrap.classList.toggle('hide');
});
}
})
</script>
<div id="videowrapper" class="hide">
<video id="video" controls>
<source src="clip.mp4" type="video/mp4">
Your browser does not support HTML5 video.
</video>
<div id="videoEnd" style="display:block">Chris Presents</div>
</div>
<script>
document.getElementById('video').addEventListener('ended',myHandler,false);
function myHandler(e) {
if(!e) { e = window.event; }
// What you want to do after the event
document.getElementById('video').style.display="none";
document.getElementById('videoEnd').style.display="none";
}
</script>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="oldhomestyle.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="soundmouseover.js"></script>
</head>

Not sure what is this code doing in your tag! (the divs)
Other than that, as mentioned, you could definitely use cookies for what you need.

You can set localStorage to store value representing if video has been played at ended event, read localStorage at load event of window
window.addEventListener('load', function() {
if (window.innerWidth >= 600 && localStorage.getItem("played") === null) {
var vid = document.getElementById('video');
var wrap = document.getElementById('videowrapper');
wrap.classList.toggle('hide');
vid.play();
vid.addEventListener('ended', function(e) {
wrap.classList.toggle('hide');
localStorage.setItem("played", true)
});
}
})

Related

How do I get an audio snippet to play when hovering over an image element?

After too many hours on YT and Google, I'm here. Thanks for taking the time to read & help. :)
I'm trying to make it so that when the mouse hovers over the image, an audio snippet plays automatically. I've tried a few different things, but this is where I stopped.
Can't seem to get anything to work.
HTML file snippet
<head>
<link rel="stylesheet" href="./stylesheet.css">
<script type="text/javascript" src="./scripts.js"></script>
...other stuff etc etc
<div class="deviruchi" data-tooltip="no touchy!">
<audio id="devi">
<source src="./sounds/deviruchi_idle.mp3">
<source src="./sounds/deviruchi_idle.ogg">
</audio>
<img src="./images/deviruchi.gif">
</div>
Javascript file
let deviruchi = $("#devi")[0];
$(".deviruchi").onmouseenter(function () {
deviruchi.play();
});
Thanks again! :)
Probably because you are using jquery...(j/k, but no really)
Make sure that the audio files are present on the server, check devtools for error messages (javascript as well as network)
Also, user must first interact with the webpage (click/focus, etc) before browser will allow play media files.
hoverMe.addEventListener("mouseenter", e =>
{
myAudio.play().catch(er => console.error(er.message, "Now, click here and try again"));
});
hoverMe.addEventListener("mouseleave", e =>
{
myAudio.pause();
});
<div id="hoverMe">Hover over here</div>
<audio id="myAudio" src="https://sample-videos.com/audio/mp3/crowd-cheering.mp3"></audio>

Web Audio API - Can't get simple audio to play

I'm trying to learn the Web Audio API from the MDN tutorial but even the most basic example — no modular synthesis, just playing a simple mp3 file — doesn't seem to work on my end.
I can see the dataset value being switched in the console, the play/pause on the controls change state, and in Firefox and Safari (but not in Chrome) the track locator even advances and the "playing" icon displayed on the browser tab.
(I've added the controls attribute to the audio tag just to have a progress indicator visible).
I can also download the file from the DOM controls and play it using the OS, and I've tried it with three different MP3 files. The computer's speakers are obviously working.
BTW, creating audio with oscillators and the AudioContext object works fine.
I'm out of ideas.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<audio controls src="song.mp3"></audio>
<button data-playing="false" role="switch" aria-checked="false">
<span>Play/Pause</span>
</button>
<script src="audio.js"></script>
</body>
</html>
JS
'use-strict'
const aCtx = new AudioContext();
const el = document.querySelector('audio');
const track = aCtx.createMediaElementSource(el);
const button = document.querySelector('button');
button.addEventListener('click', function() {
console.log(this);
if (aCtx.state === 'suspended') {
aCtx.resume();
}
if (this.dataset.playing === 'false') {
el.play();
this.dataset.playing = 'true';
} else {
el.pause();
this.dataset.playing = 'false';
}
}, false);

Add time left to HTML video

I am trying to see a video using Chrome. In particular, I would like to add some useful commands to it, such as a countdown element. This is my code:
<html>
<head>
<meta name="viewport" content="width=device-width">
<script>
var video = document.getElementById('video');
video.addEventListener('timeupdate', updateCountdown);
function updateCountdown() {
var timeSpan = document.querySelector('#countdown');
timeSpan.innerText = video.duration - video.currentTime;
}
</script>
</head>
<body>
<video id="video" controls="" autoplay="" name="media"><source src="file://..........." type="video/mp4"></video>
<div style="color:RED;" id="countdown">Video ends after <span id="countdown">xx</span> seconds.</div>
</body>
</html>
I would like it to show how much time is left, but it is not working. How can I fix it?
And how can I make it ring every time 5 minutes of the video have passed?
Thank you very much in advance
You have not given your video element an id so the getElementById can't find it. There must be some errors on your browser's dev tools console, do you see them?
To time the 5 minutes you could use a setTimeout function and get it to call a function that creates a sound.
(1) Create your HTML elements first so they are existing when using Javascript to control them.
<html>
<head> <meta name="viewport" content="width=device-width"> </head>
<body>
<video id="myVideo" name="media" controls autoplay>
<source src="file://..........." type="video/mp4"></video>
<div style="color:RED;" id="countdown">Video ends after <span id="countNumbers"> xx </span> seconds.</div>
</body>
<script>
var vid = document.getElementById("myVideo");
vid.addEventListener("timeupdate", updateCountdown, true);
var timeSpan = document.getElementById("countNumbers"); //# was document.querySelector('#countdown');
function updateCountdown()
{ timeSpan.innerText = Math.round(vid.duration - vid.currentTime); }
</script>
</html>
(2) For sound every 5 minutes, remember JS is counting in millisecs (eg 1 second is 1000 ms, so you need a value of 60,000 x 5 to represent 5 mins). So you need logic like the below example.
if( video.currentTime >= (lastTime + five_mins) )
{
//# update new "lastTime" to start from here onwards
//alert(" 5 mins have passed ... ");
lastTime = video.currentTime;
soundFile.play; //# play the audio tag by its ID
}
PS: Your idea might break if user seeks the video etc, so if you just want a timer that plays a sound every 5 mins regardless of .currentTime then use either settimeout or setinterval...
Try adding a html countdown and sync it with the "Video ends after xx seconds" text. If that doesnt work then try doing something like Youtube's countdown thing (if you can inspect the element code and find the right code) you can do it!

.play JavaScript not playing sound sometimes

I have made and alarm page using .play() method. But sometimes audio does not play and sometimes it plays. My code it gets executed but the MP3 audio does not get played.
What could be the problem?
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
if (alrm4 != alrm4a) {
alrm4 = alrm4a;
audio.play();
blinker = 4;
}
}, 1000);
});
</script>
</head>
<body>
<script>
var audio = new Audio('Sound.mp3');
</script>
</body>
</html>
Providing more context would be helpful. Your code refers to two variables (alrm4 and alrm4a) that are not defined in the sample code you provided.
Chances are there was a problem loading the mp3 file or your condition, alrm4 != alrm4a, is not evaluating to true. Please edit your question to include the code which defines and manipulates these variables.

how to build video playlist having youtube videos?

how to build a video-playlist that supports you-tube embedded videos?
i don't want page to be refreshed, just video changes dynamically if user clicks on another video,take a look at this for your reference.
Does any of jplayer/video-js/flowplayer etc support this feature?
If you're using video.js and the YouTube plugin you can update the source using the video.js API. You do need to specify the video/youtube type.
videojs("myPlayer").src({ type: "video/youtube", src: "http://www.youtube.com/watch?v=dQw4w9WgXcQ"});
Example: http://jsfiddle.net/mister_ben/g7mrs/
This is a JS trick. If you have a console to the browser (or firebug), you can see, it goes a JSON get request and response from the browser to the server and reverse. The server read out from the database, the correct embedded video, it sends to the browser, and that insert into the page DOM.
Try this example to dynamically change youtube src:
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="http://vjs.zencdn.net/5.4.4/video-js.css"/>
</head>
<body>
<video
id="vid1"
class="video-js vjs-default-skin"
controls
width="640" height="264"
data-setup='{ "techOrder": ["youtube"], "sources": [{ "type": "video/youtube", "src": "https://www.youtube.com/watch?v=xjS6SftYQaQ"}] }'
>
</video>
<button id="change">change video</button>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="http://vjs.zencdn.net/5.4.4/video.js"></script>
<script
src="https://raw.githubusercontent.com/eXon/videojs-youtube/637a2916c2c4fd2b5fc55dafa3df923a92fec6d0/src/Youtube.js"></script>
<script>
(function ($) {
$(document).ready(function () {
// An example of playing with the Video.js javascript API
// Will start the video and then switch the source 3 seconds latter
// You can look at the doc there: http://docs.videojs.com/docs/guides/api.html
videojs('vid1').ready(function () {
var myPlayer = this;
myPlayer.src({type: 'video/youtube', src: 'https://www.youtube.com/watch?v=y6Sxv-sUYtM'});
$("#change").on('click', function () {
myPlayer.src({type: 'video/youtube', src: 'https://www.youtube.com/watch?v=09R8_2nJtjg'});
});
});
});
})(jQuery);
</script>
</body>
</html>
or see the discussion here: https://github.com/eXon/videojs-youtube/issues/339#issuecomment-164592838

Categories