How do I autoplay a video after clicking on an image? - javascript

I am using the below code in a WordPress editor. With my current code when I click on the image the actual video shows up, and I have to click the video again to play it.
I want to change it so that an image of the video is displayed and when I click on that the video should start to play. I just have to click once. Right now I have to click twice which is bad user experience. This is required to reduce page load time.
<div class="youtube" id="PpMS2SP_3Fs" style="width:100%; height: 600px;"></div>
<script>
var videos = document.getElementsByClassName("youtube");
for (var i = 0; i < videos.length; i++) {
var youtube = videos[i];
var img = document.createElement("img");
img.setAttribute("src", "https://www.sociosquares.com/wp-content/uploads/2019/04/vid-img1-opti.jpg");
img.setAttribute("class", "thumb");
var circle = document.createElement("div");
circle.setAttribute("class", "circle");
youtube.appendChild(img);
youtube.appendChild(circle);
youtube.onclick = function() {
var iframe = document.createElement("iframe");
iframe.setAttribute("src", "https://www.youtube.com/embed/" + this.id + "?autoplay=1&loop=1&playlist=PpMS2SP_3Fs");
//"https://www.youtube.com/embed/PpMS2SP_3Fs?autoplay=1&loop=1&playlist=PpMS2SP_3Fs");
iframe.style.width = this.style.width;
iframe.style.height = this.style.height;
this.parentNode.replaceChild(iframe, this);
};
}
</script>
I expected the video to autoplay after a click on the image, but it doesn't, and I have to click again to play the video.

jQuery('#image_id').click(function() {
jQuery(".youtube").attr('src', jQuery(".youtube", parent).attr('src') + '?autoplay=1');
});
image_id is your image element id you are clicking and youtube is the class of the iframe your embed has.

Related

Add video to page on Button click

I am a beginner JS user, and I am trying to get a video to play on fullscreen and replace an invisible div further down on the page. I started with a guide from Chris Ferdinandi.
In his guide, the video replaces the image that is clicked. I would like to have the div later down on the page to be replaced on the click.
Any guidance would be great!
HTML
<a data-video="480459339" class="stylsheetref" href="#" target="">Watch the Tour</a>
<div id="video-replace"></div>
Javascript (modified from this guide)
<script>
if (!Element.prototype.requestFullscreen) {
Element.prototype.requestFullscreen = Element.prototype.mozRequestFullscreen || Element.prototype.webkitRequestFullscreen || Element.prototype.msRequestFullscreen;
}
// Listen for clicks
document.addEventListener('click', function (event) {
//Set invisible Div (new code added by me)
var videonew = '#video-replace');
// Check if clicked element is a video link
var videoId = event.target.getAttribute('data-video');
if (!videoId) return;
// Create iframe
var iframe = document.createElement('div');
iframe.innerHTML = '<p>x</p><iframe width="560" height="960" src="https://player.vimeo.com/video/' + videoId + '?rel=0&autoplay=1" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>';
var video = iframe.childNodes[1];
// Replace the image with the video
event.target.parentNode.replaceChild(video, videonew);
// Enter fullscreen mode
video.requestFullscreen();
}, false);
</script>
There are problems in your code.
var videonew = '#video-replace'); there's an orphan ), since you are using this in the `replaceChild``method I assume you want the variable to reference to an element.
So change it to
var videonew = document.querySelector('#video-replace');
Pro tip: Using the Developer console during development can help you figure out such errors in your code.

Sound on mouseover, stop on mouseout

I am working on a project where a sound plays when you mouseover an image and stops playing on mouseout. I want it to start over each time and there has to be multiple images on each page. I am looking for the most efficient way to make this code work. Here is the sample page: http://inventivewebdesign.com/audio-img/sound.html
Code:
<body>
<script>
function PlaySound(soundobj) {
var thissound=document.getElementById(soundobj);
thissound.play();
}
function StopSound(soundobj) {
var thissound=document.getElementById(soundobj);
thissound.pause();
thissound.currentTime = 0;
}
</script>
<a onmouseover="PlaySound('violin')" onmouseout="StopSound('violin')"><img src="violin.png"></a>
<a onmouseover="PlaySound('xy')" onmouseout="StopSound('xy')"><img src="xy.png" width="300px" height="300px"></a>
<a onmouseover="PlaySound('piccolo')" onmouseout="StopSound('piccolo')"><img src="piccolo.png"></a>
<audio id='piccolo' src='piccolo.wav'/>
<audio id='violin' src='violin.mp3'/>
<audio id='xy' src='xy.mp3'/>
</body>
This all works. My only question is how to make the code more efficient.
I saw that I should be able to do something like this:
<audio>
<source id='piccolo' src='piccolo.wav'>
<source id='violin' src='violin.mp3'>
<source id='xy' src='xy.mp3'>
</audio>
But it doesn't work. Is the first set of code above the best way to do it?
Good question #MattM. I would simply add a function to create new instances of the audio hovers, making make it easier to implement more sounds without code repetition.
function newHover(e){
var audio = new Audio(); // creates audio element
audio.src = e.audio; // the audios location
var image = new Image(); //creates the image element
image.src = e.image; // the images location
image.className = e.title; // applies the name of the instrument to both elements
audio.className = e.title;
image.addEventListener("mouseover", PlaySound); // listens for mouse movement
image.addEventListener("mouseout", StopSound);
document.body.appendChild(audio); // appends the audio and image to the body of the document
document.body.appendChild(image);
}
That way, the below code block is unnecessary:
<a onmouseover="PlaySound('violin')" onmouseout="StopSound('violin')">
<img src="violin.png">
</a>
<a onmouseover="PlaySound('xy')" onmouseout="StopSound('xy')">
<img src="xy.png" width="300px" height="300px">
</a>
<a onmouseover="PlaySound('piccolo')" onmouseout="StopSound('piccolo')">
<img src="piccolo.png">
</a>
<audio id='piccolo' src='piccolo.wav'/>
<audio id='violin' src='violin.mp3'/>
<audio id='xy' src='xy.mp3'/>
Implement this in your code, none of the HTML above is needed in this solution.
(Note: getElementById was changed to querySelector in PlaySound and PauseSound functions)
function PlaySound(e) {
var thissound = document.querySelector("audio." + e.target.className);
thissound.play();
}
function StopSound(e) {
var thissound = document.querySelector("audio." + e.target.className);
thissound.pause();
thissound.currentTime = 0;
}
function newHover(e){
var audio = new Audio();
audio.src = e.audio;
var image = new Image();
image.src = e.image;
image.className = e.title;
audio.className = e.title;
image.addEventListener("mouseover", PlaySound);
image.addEventListener("mouseout", StopSound);
document.body.appendChild(audio);
document.body.appendChild(image);
}
window.onload = function(){
newHover({
audio: "http://inventivewebdesign.com/audio-img/piccolo.wav", // Path to the audio file (the src property of audio tag)
image: "http://inventivewebdesign.com/audio-img/piccolo.png", // Path to the image file (the src property of the image tag)
title: "piccolo" // The name of the instrument (applied as a className to both the image and the audio elements)
});
newHover({
audio: "http://inventivewebdesign.com/audio-img/xy.mp3",
image: "http://inventivewebdesign.com/audio-img/xy.png",
title: "xy"
});
newHover({
audio: "http://inventivewebdesign.com/audio-img/violin.mp3",
image: "http://inventivewebdesign.com/audio-img/violin.png",
title: "violin"
});
}
a{
position: absolute;
}
img{
width: 100px;
}
<body>
<a>Hover over the images!</a>
</body>
In conclusion, your solution works effectively, However it would make it much easier for you to have a function to create the audio hovers for you.
I took a look at inventivewebdesign.com, very nice website there!
EDIT>>>>>>>>>>>>
Note - I have tested the script in Firefox and Chrome. It should work fine.
For clarification on how to use the function:
To insert an image. Call the newHover function Like so:
newHover({
audio: /*audio src here eg. music.wav*/,
image: /*image src here eg. picture.png*/,
title: /*title here eg. violin / xylophone / piccolo*/
});
The images will be inserted into the document. You can then apply css styles or do what ever else you want to them.

Pause video when clicking an overlay element

I am working on a video where during some seconds, an overlay element appears to promote a product.
I would like to know if is possible to pause the video when someone clicks the overlay element and at the same time this will display a window showing the product details. So:
Video plays and displays an overlay element
User clicks the overlay element so:
2.1: Video pauses on the background
2.2: Overlay element opens a window over the paused video to show the product details.
This is my code where the video shows the overlay element for a few seconds during the video:
<video id="myVideo" controls>
<source id='mp4' src="video.mp4" type='video/mp4'>
</video>
<div id="overlay">
Something
</div>
<script>
//Shows link between seconds 5 and 10
var overlay = document.getElementById('overlay');
var video = document.getElementById('myVideo');
video.addEventListener('timeupdate', function() {
console.log( video.currentTime );
var show = video.currentTime >= 5 && video.currentTime < 10;
overlay.style.opacity = show ? '1' : '0';
}, false);
</script>
some sample code:
overlay.addEventListener('click', function() { video.pause() })
You should proably add in something that would play the video once the overlay is clicked again - but i think you get the idea.
Have a look here for the documentation on what is available on the video element:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video
Video can be paused using video.pause()
https://www.w3schools.com/tags/ref_av_dom.asp
You can attach an click event listener to your overlay,
and call the video pause function when the user click on the overlay.
Instead of using opacity on your overlay,
you can perhaps try using display: none instead.
So that, you won't need to handle the situation where the overlay
is always blocking in front of your elements.
See demo: https://jsfiddle.net/amoshydra/pan306jt/
//Shows link between seconds 5 and 10
var overlay = document.getElementById('overlay');
var video = document.getElementById('myVideo');
video.addEventListener('timeupdate', function() {
console.log( video.currentTime );
var show = video.currentTime >= 5 && video.currentTime < 10;
// Try using display style?
overlay.style.display = show ? 'block' : 'none';
}, false);
overlay.addEventListener('click', function() {
var urlToOpen = 'http://stackoverflow.com/questions/14132122/open-url-in-new-window-with-javascript';
window.open(urlToOpen, '_blank');
// Pause video using the video API
video.pause();
});

Reset link background color on previously selected

Hi I have a song playlist & use javascript in the player to set the back ground color to light green on the playing song. I am aware I could use a:focus however if the user selects the lyrics while the song is playing the song will continue to play however it looses focus so the background color reverts to original. I need a way to use javascript to change the color of the song back to its original when the song is no longer playing or another song is selected. code below.
<!-- Video Player Script -->
var video_playlist = document.getElementById("video_player");
var links = video_playlist.getElementsByTagName('a');
for (var i=0; i<links.length; i++) {
links[i].onclick = handler;
};
function handler(e) {
e.preventDefault();
videotarget = this.getAttribute("href");
filename = videotarget.substr(0, videotarget.lastIndexOf('.')) || videotarget;
video = document.querySelector("#video_player video");
source = document.querySelectorAll("#video_player video source");
source[0].src = filename + ".mp3";
video.load();
video.play();
this.style.background = "#AAFF8D";
};
If this is an html5 video then use the onended proptery to detect when the video finishes playing:
video.onended = function(e) {
// change background color here
};
It appears that you are using a <video> for the music. With that in mind by "song is no longer playing." I'm going to assume that means the video has ended. In that case you can have an event onended that will change the background color to the original:
var player = document.getElementById("video_player");
player.onended = function(){
// Change background color here
};
After scouring google & some playing came up with the answer.
Thank you goes out to Spencer Wieczorek & Walker Boh for answers I thought should work.
Code Below:
<!-- Video Player Script -->
<!-- Get Selected Link -->
var video_playlist = document.getElementById("video_player");
var links = video_playlist.getElementsByTagName('a');
**var ele = video_playlist.getElementsByTagName("a");
var activeEle = null;**
for (var i=0; i<links.length; i++)
{
links[i].onclick = handler;
};
<!-- Find Previously Selected Link -->
**for( var i=0; i<ele.length; i++ )
{
if( ele.item(i).style.background == "##AAFF8D" )
{
document.write(ele.item(i).id);
break;
}
}**
<!-- Highlight Selected Link & Remove Highlght On Previous Link -->
**function highlight( )
{
if (activeEle){
activeEle.style.background = "#F9F9F9";
}
var oObj = event.currentTarget;
oObj.style.background = "#AAFF8D";
activeEle = oObj;
}**
function handler(e)
{
e.preventDefault();
videotarget = this.getAttribute("href");
filename = videotarget.substr(0, videotarget.lastIndexOf('.')) ||
videotarget;
video = document.querySelector("#video_player video");
source = document.querySelectorAll("#video_player video source");
source[0].src = filename + ".mp3";
video.load();
video.play();
**highlight();**
};

How to load iframe on load using jquery?

Following is Function to embed youtube video in html.
In this youtube video display on click but I want to do this on load using javascript.
How can be done? Any help?
youtubeLoadVideos : function () {
// Find all the YouTube video embedded on a page
var videos = document.getElementsByClassName("youtube");
for (var i=0; i<videos.length; i++) {
var youtube = videos[i];
// Attach an onclick event to the YouTube Thumbnail
youtube.onclick = function() {
// Create an iFrame with autoplay set to true
var iframe = document.createElement("iframe");
iframe.setAttribute("src", "https://www.youtube.com/embed/" + this.id);
// The height and width of the iFrame should be the same as parent
iframe.style.width = this.style.width;
iframe.style.height = this.style.height;
iframe.style.clear = 'both';
// Replace the YouTube thumbnail with YouTube HTML5 Player
this.parentNode.replaceChild(iframe, this);
};
}
}
As you create it onload, just create a html tag:
<iframe src="https://www.youtube.com/embed/yourid"/>
Or use javascript, as there is only 1 should be loaded as default:
window.onload = function(){
var videos = document.getElementsByClassName("youtube");
if (videos.length > 0){
var youtube = videos[0];
var iframe = document.createElement("iframe");
iframe.setAttribute("src", "https://www.youtube.com/embed/" + youtube.id);
// The height and width of the iFrame should be the same as parent
iframe.style.width = youtube.style.width;
iframe.style.height = youtube.style.height;
iframe.style.clear = 'both';
// Replace the YouTube thumbnail with YouTube HTML5 Player
youtube.parentNode.replaceChild(iframe, youtube);
}
}
Another case, if you need to keep the onclick and load 1 video by default, just keep your code and write some more lines:
window.onload = function(){
var videos = document.getElementsByClassName("youtube");
if (videos.length > 0){
var youtube = videos[0]; //play the first video onload
youtube.click(); //trigger click programmatically, this will cause the event handler to be executed and insert an iframe.
}
}

Categories