JavaScript Toggle with button - javascript

So i have a button that what it does it toggles and displays a video. If clicked again it will hide it and on and on. It works fine the only problem is that when the first time you click it you have to click it twice for some reason i can't seem to figure it out.
function togglevid() {
var e = document.getElementById("movie");
if (e.style.display == 'none') e.style.display = 'block';
else e.style.display = 'none';
if (e.pause == false) e.pause()
else e.pause()
}
#movie {
position:absolute;
top:158px;
left:470px;
display:none;
z-index:10
}
<video controls="" height="400" id="movie" oncontextmenu="return false;"
width="960">
<source src="" type="video/mp4">
Your browser does not support HTML5 video.</video>
<input id="mcodebtn" onclick="togglevid()" type="button" value=
"">
I believe the reason for this error is the fact i have the video set to display: none; by default.

Try below code, style property should be set to display:none.
The problem is that you are trying to access style property and then access display value. But the first time you run it, video tag does not have any style attribute set.
function togglevid() {
var s = document.getElementById("newcode");
var e = document.getElementById("movie");
if (e.style.display == 'none') e.style.display = 'block';
else e.style.display = 'none';
if (s.style.display == 'none') s.style.display = 'block';
else s.style.display = 'none';
if (e.pause == false) e.pause()
else e.pause()
}
#movie {
position:absolute;
top:158px;
left:470px;
display:none;
z-index:10
}
<video controls=""
height="400"
id="movie"
oncontextmenu="return false;"
width="960"
style="display:none;"><!-- Here we set a default value for style attr-->
<source src="" type="video/mp4">
Your browser does not support HTML5 video.</video>
<input id="mcodebtn" onclick="togglevid()" type="button" value=
"">

Try substituting window.getComputedStyle() for e.style.display
function togglevid() {
var e = document.getElementById("movie");
e.style.display = window.getComputedStyle(e, null)
.getPropertyValue("display") === "none"
? "block" : "none";
}
#movie {
position: absolute;
top: 158px;
left: 470px;
display: none;
z-index: 10
}
<video controls="" height="400" id="movie" oncontextmenu="return false;" width="960">
<source src="" type="video/mp4">
Your browser does not support HTML5 video.</video>
<input id="mcodebtn" onclick="togglevid()" type="button" value="toggle">

Related

Use addEventListener to change display style

I am trying to learn addEventListener, but somehow it doesn't work. Console doesn't show any error either.
So, I have these sections:
<section id="media_image-4" class="widget widget_media_image">
<div class="widget-wrap">
<img width="150" height="150" src="https://domains/wp-content/uploads/2019/01/image-150x150.jpg" class="image wp-image-41 attachment-thumbnail size-thumbnail" alt="" style="max-width: 100%; height: auto;" sizes="(max-width: 150px) 100vw, 150px" />
</div>
</section>
<section id="text-12" class="widget widget_text">
<div class="widget-wrap"><div class="textwidget">
<p id="sublinks">
<img class="alignnone size-full wp-image-833" src="https://domains/wp-content/uploads/2019/09/icon-link.png" alt="" width="16" height="16" data-sitemapexclude="true" />
</p>
</div></div>
</section>
By default, the section id media_image-4 is hidden with css "display: none". I would like it's shown when I click to icon-link.png image. So, I created an external javascript, and called it. The file is:
var mID = document.getElementById ("sublinks");
mID.addEventListener ("click", function() {
var x = document.getElementById("media_image-4");
if ( x.style.display == "none" || x.style.display == "") {
x.style.display = "inline-block";
} else {
x.style.display = "";
}
}, false);
Am I doing something wrongly? What should I do to get media_image-4 shown?
Please advice. Thanks.
Instead of
else {
x.style.display = "";
}
write
else {
x.style.display = "none";
}
otherwise everything is ok
But better solve it through specified class
CSS:
#media_image-4 {
display: none;
}
#media_image-4.showMe {
display:inline-block;
}
and JS code
document.getElementById ("sublinks").addEventListener ("click", () => {
document.getElementById("media_image-4").classList.toggle('showMe')
}, false);

eventListener to alter between two elements

What I want is whenever I mouseover on an element for it to set the style of video to display: none; and then the img to display: block;
Here's my code:
Javascript
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("container").addEventListener("mouseenter", function(event) {
alternate(event);
});
document.getElementById("container").addEventListener("mouseout", function(event) {
alternate(event);
});
function alternate(e) {
var target = e.target || e.srcElement;
if (target) {
if (target.nodeName == "IMG") {
target.querySelector(".video").style.display = "block";
target.querySelector(".img").style.display = "none";
} else if (target.nodeName == "VIDEO") {
target.querySelector(".video").style.display = "none";
target.querySelector(".img").style.display = "block";
}
}
}
});
HTML
<div id="container">
<li>
<div>
<video class="video" src="./test.mp4" type="video/mp4" muted autoplay></video>
<img class="img" src="./test.jpg"></img>
</div>
</li>
<li>
<div>
<video class="video" src="./test.mp4" type="video/mp4" muted autoplay></video>
<img class="img" src="./test.jpg"></img>
</div>
</li>
</div>
Essentially what I am trying to achieve is whenever I mouseout from the video, put the image back and then back from. video: hidden, image:shown to video:shown, image:hidden.
I did manage to get something working by using the target.previousSibling technique but it didn't work 100%,
Hopefully I formatted this question right, thank you for reading. Any help is really appreciated.
You could achieve this with pure CSS. A very simple approach would be:
.hover-toggle {
position: relative;
}
.hover-toggle .video {
/* Use absolute positioning to place video along-side image */
position: absolute;
top: 0;
left: 0;
/* Set video to be transparent by default */
opacity: 0;
}
/* When hovering the transparent video, cause it to become opaque */
.hover-toggle .video:hover {
opacity: 1;
}
<div class="hover-toggle">
<video class="video" src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4" muted autoplay></video>
<img class="img" src="https://via.placeholder.com/320x176" />
</div>
<div class="hover-toggle">
<video class="video" src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4" muted autoplay></video>
<img class="img" src="https://via.placeholder.com/320x176" />
</div>
mouseenter and mouseleave are the proper events to use.
If you use <li> then you must use <ol> or <ul> as the parent.
Register the events to each <li>
const items = document.querySelectorAll('li');
for (let item of items) {
item.addEventListener('mouseenter', alternate);
item.addEventListener('mouseleave', alternate);
}
Define the event handler using e.target and .matches('li') to insure that the events only apply to <li>. Then use e.type to insure that only mouseenter and mouseleave` events apply.
const tgt = e.target;
const evt = e.type;
if (tgt.matches('li')) {
if (evt === 'mouseenter') {
...
else if (evt === 'mouseleave') {
...
}
The reason why target.previousSibling worked some of the time is because display: none removes elements from the flow thereby not being recognized as a sibling. Try assigning a class that has visibility and z-index properties and alternate that class between events.
tgt.children[0].classList.add('on');
tgt.children[1].classList.remove('on');
// and vice versa
BTW <img> tags are void elements (no end tag </img>)
const items = document.querySelectorAll('li');
for (let item of items) {
item.addEventListener('mouseenter', alternate);
item.addEventListener('mouseleave', alternate);
}
function alternate(e) {
const tgt = e.target;
const evt = e.type;
if (tgt.matches('li')) {
if (evt === 'mouseenter') {
tgt.children[0].classList.add('on');
tgt.children[1].classList.remove('on');
} else if (evt === 'mouseleave') {
tgt.children[1].classList.add('on');
tgt.children[0].classList.remove('on');
} else {
return false;
}
}
return false;
}
li {
position: relative;
height: 135px;
}
li * {
visibility: hidden;
position: absolute;
z-index: -1;
top: 0;
left: 0;
}
.on {
visibility: visible;
z-index: 1;
}
<ul>
<li>
<video src='https://storage04.dropshots.com/photos6000/photos/1381926/20170326/005610.mp4' muted autoplay loop width='240' height='135'></video>
<img class='on' src='https://branditprintit.com/wp-content/uploads/2017/04/logo-degin-logo-design-design-art-free.png' width='240' height='135'>
</li>
<li>
<video src='https://storage04.dropshots.com/photos6000/photos/1381926/20170326/005609.mp4' muted autoplay loop width='240' height='135'></video>
<img class='on' src='https://branditprintit.com/wp-content/uploads/2017/04/logo-degin-logo-design-design-art-free.png' width='240' height='135'>
</li>
</ul>

JAVASCRIPT audio application : Button does not change according to device

This is a html embed audio player with simple controls . i made this as an addon for my website.
As autoplay is not supported in mobile browsers . The play/pause button changes according to device
ie: Play button shows up in mobile, Pause button shows up on pc's
The mobile side of the player works perfectly. But the pc side of it starts with the play button even though audio is playing in the background. ie. Else condition doesnt work
If the error isnt clear please copy paste the code here and see : www.htmledit.squarefree.com
<head>
<script>
var playing = true;
if (/Android|iPhone|iPad|Mobile|Mobi|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(navigator.userAgent)) {
playing = false;
}
<!-- THIS ELSE DOES NOT WORK . IT IS SUPPOSED TO CHANGE THE ICON TO PAUSE FROM PRE DEFINED PLAY ICON-->
else{
document.getElementById('sound_icon').src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAAuUlEQVRoQ+2YwQ2AIAxFYRwncS3WchLH0YN6IWp/QhtCeJ5rgfd/W0JOg3958P0nDtBbQRRAgUYCWKgRYPPv8yiwlO1QcO1l/YXilefZi6yA18JeeTjAl52w0E3GAoGFsJDRk7FQDcirf3vloYgpYor4IsBlrnaC1b/pQhUxLISFPtqpVUtMYiYxk5hJ/O4Bq3swiaedxMq7aI8Y+S7UY3PKmhxAoRQZgwKRdJXcKKBQioxBgUi6Su4TGV3gMZ8LoyUAAAAASUVORK5CYII=";
}
function EvalSound(soundobj) {
var thissound = document.getElementById(soundobj);
if (!playing) {
thissound.play();
playing = true;
document.getElementById('sound_icon').src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAAuUlEQVRoQ+2YwQ2AIAxFYRwncS3WchLH0YN6IWp/QhtCeJ5rgfd/W0JOg3958P0nDtBbQRRAgUYCWKgRYPPv8yiwlO1QcO1l/YXilefZi6yA18JeeTjAl52w0E3GAoGFsJDRk7FQDcirf3vloYgpYor4IsBlrnaC1b/pQhUxLISFPtqpVUtMYiYxk5hJ/O4Bq3swiaedxMq7aI8Y+S7UY3PKmhxAoRQZgwKRdJXcKKBQioxBgUi6Su4TGV3gMZ8LoyUAAAAASUVORK5CYII=";
} else if (playing) {
thissound.pause();
playing = false;
document.getElementById('sound_icon').src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAABdElEQVRoQ+2YuxWCQBBFl0Rb0TJM9NiFdoAVOHSAHWAZZtoFoXagGZHroOghMHA+++G4JCT7mTvv8VjIzMCvbOD1mwQQWsGkQFJA2IFkIWEDxdP/V4EJHI7G3Fc1LM/iNgoWYCswhYNt97WZgcaOdmeYXQV1sKeKAbqdrwiS19vFnl0Jc6IWwHN7ayzayhZoK7z7uVQB3iUjSNWY8caHrZwA9GxVoq0Kl1q4BHjbClPKrl3ZyjlAz1bt89GCqMauN4APiHLsegfQjt1QAGqxGxRAI3ajAJDEbkwArNiNDgCj9oJv8vaU+9NxJBoAPNreUIKyhgVQ3txRAGDx+8aMcs7ZKSgAFn7CjyL41S7flAkC8LJLltcwryh2iQIAiy/QLiXHLkEBOruof0N7sBAtFqmWcgbAjcUoACSxGBRAIxaDAGjGoncA7Vj0BjD4X4vUTrkaz45RVwVR100A1I5pj08KaHeUul5SgNox7fFJAe2OUtd7AO2p3zFrWh4hAAAAAElFTkSuQmCC";
}
}
</script>
</head>
<body>
<a href="javascript:null()" onClick="EvalSound('sound1'); return false; ">
<!-- PRE DEFINED PLAY ICON IS BELOW -->
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAABdElEQVRoQ+2YuxWCQBBFl0Rb0TJM9NiFdoAVOHSAHWAZZtoFoXagGZHroOghMHA+++G4JCT7mTvv8VjIzMCvbOD1mwQQWsGkQFJA2IFkIWEDxdP/V4EJHI7G3Fc1LM/iNgoWYCswhYNt97WZgcaOdmeYXQV1sKeKAbqdrwiS19vFnl0Jc6IWwHN7ayzayhZoK7z7uVQB3iUjSNWY8caHrZwA9GxVoq0Kl1q4BHjbClPKrl3ZyjlAz1bt89GCqMauN4APiHLsegfQjt1QAGqxGxRAI3ajAJDEbkwArNiNDgCj9oJv8vaU+9NxJBoAPNreUIKyhgVQ3txRAGDx+8aMcs7ZKSgAFn7CjyL41S7flAkC8LJLltcwryh2iQIAiy/QLiXHLkEBOruof0N7sBAtFqmWcgbAjcUoACSxGBRAIxaDAGjGoncA7Vj0BjD4X4vUTrkaz45RVwVR100A1I5pj08KaHeUul5SgNox7fFJAe2OUtd7AO2p3zFrWh4hAAAAAElFTkSuQmCC" id="sound_icon" name="Sound" width="" height="" title="Background Music Controls" class="" /></a>
<audio id="sound1" style="display: none; width: 0px; height: 0px;" src="https://audio.clyp.it/3fnnuaiw.mp3?Expires=1488659248&Signature=01NkRScwYO4XaJO46JuNzPRR6cYQfcL5~rJzAu-gIoNoXkiMVZwazwT--amuqYvreLCSRFnFAFUvwR3v9Xaq1iB4~OmKSWqtF9mSm-CUB2Moqtie8wpGIRxTAkDHnfhN0sy45sINjwFP2xyVumld78USPuCBfNU3kgux69YG-yA_&Key-Pair-Id=APKAJ4AMQB3XYIRCZ5PA" controls preload="auto" autobuffer autoplay>
</body>
When loading the page the script part at the headers is running before the elements where created at the DOM. See this other answer to better understand how it works.
To have it working you can load the script at the end:
<body>
<a href="javascript:null()" onClick="EvalSound('sound1'); return false; ">
<!-- PRE DEFINED PLAY ICON IS BELOW -->
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAABdElEQVRoQ+2YuxWCQBBFl0Rb0TJM9NiFdoAVOHSAHWAZZtoFoXagGZHroOghMHA+++G4JCT7mTvv8VjIzMCvbOD1mwQQWsGkQFJA2IFkIWEDxdP/V4EJHI7G3Fc1LM/iNgoWYCswhYNt97WZgcaOdmeYXQV1sKeKAbqdrwiS19vFnl0Jc6IWwHN7ayzayhZoK7z7uVQB3iUjSNWY8caHrZwA9GxVoq0Kl1q4BHjbClPKrl3ZyjlAz1bt89GCqMauN4APiHLsegfQjt1QAGqxGxRAI3ajAJDEbkwArNiNDgCj9oJv8vaU+9NxJBoAPNreUIKyhgVQ3txRAGDx+8aMcs7ZKSgAFn7CjyL41S7flAkC8LJLltcwryh2iQIAiy/QLiXHLkEBOruof0N7sBAtFqmWcgbAjcUoACSxGBRAIxaDAGjGoncA7Vj0BjD4X4vUTrkaz45RVwVR100A1I5pj08KaHeUul5SgNox7fFJAe2OUtd7AO2p3zFrWh4hAAAAAElFTkSuQmCC" id="sound_icon" name="Sound" width="" height="" title="Background Music Controls" class="" /></a>
<audio id="sound1" style="display: none; width: 0px; height: 0px;" src="https://audio.clyp.it/3fnnuaiw.mp3?Expires=1488659248&Signature=01NkRScwYO4XaJO46JuNzPRR6cYQfcL5~rJzAu-gIoNoXkiMVZwazwT--amuqYvreLCSRFnFAFUvwR3v9Xaq1iB4~OmKSWqtF9mSm-CUB2Moqtie8wpGIRxTAkDHnfhN0sy45sINjwFP2xyVumld78USPuCBfNU3kgux69YG-yA_&Key-Pair-Id=APKAJ4AMQB3XYIRCZ5PA" controls preload="auto" autobuffer autoplay>
<script>
var playing = true;
var flag = false;
if (/Android|iPhone|iPad|Mobile|Mobi|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(navigator.userAgent)) {
playing = false;
} else{
document.getElementById('sound_icon').src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAAuUlEQVRoQ+2YwQ2AIAxFYRwncS3WchLH0YN6IWp/QhtCeJ5rgfd/W0JOg3958P0nDtBbQRRAgUYCWKgRYPPv8yiwlO1QcO1l/YXilefZi6yA18JeeTjAl52w0E3GAoGFsJDRk7FQDcirf3vloYgpYor4IsBlrnaC1b/pQhUxLISFPtqpVUtMYiYxk5hJ/O4Bq3swiaedxMq7aI8Y+S7UY3PKmhxAoRQZgwKRdJXcKKBQioxBgUi6Su4TGV3gMZ8LoyUAAAAASUVORK5CYII=";
}
function EvalSound(soundobj) {
var thissound = document.getElementById(soundobj);
if (!playing) {
thissound.play();
playing = true;
document.getElementById('sound_icon').src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAAuUlEQVRoQ+2YwQ2AIAxFYRwncS3WchLH0YN6IWp/QhtCeJ5rgfd/W0JOg3958P0nDtBbQRRAgUYCWKgRYPPv8yiwlO1QcO1l/YXilefZi6yA18JeeTjAl52w0E3GAoGFsJDRk7FQDcirf3vloYgpYor4IsBlrnaC1b/pQhUxLISFPtqpVUtMYiYxk5hJ/O4Bq3swiaedxMq7aI8Y+S7UY3PKmhxAoRQZgwKRdJXcKKBQioxBgUi6Su4TGV3gMZ8LoyUAAAAASUVORK5CYII=";
} else if (playing) {
thissound.pause();
playing = false;
document.getElementById('sound_icon').src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAABdElEQVRoQ+2YuxWCQBBFl0Rb0TJM9NiFdoAVOHSAHWAZZtoFoXagGZHroOghMHA+++G4JCT7mTvv8VjIzMCvbOD1mwQQWsGkQFJA2IFkIWEDxdP/V4EJHI7G3Fc1LM/iNgoWYCswhYNt97WZgcaOdmeYXQV1sKeKAbqdrwiS19vFnl0Jc6IWwHN7ayzayhZoK7z7uVQB3iUjSNWY8caHrZwA9GxVoq0Kl1q4BHjbClPKrl3ZyjlAz1bt89GCqMauN4APiHLsegfQjt1QAGqxGxRAI3ajAJDEbkwArNiNDgCj9oJv8vaU+9NxJBoAPNreUIKyhgVQ3txRAGDx+8aMcs7ZKSgAFn7CjyL41S7flAkC8LJLltcwryh2iQIAiy/QLiXHLkEBOruof0N7sBAtFqmWcgbAjcUoACSxGBRAIxaDAGjGoncA7Vj0BjD4X4vUTrkaz45RVwVR100A1I5pj08KaHeUul5SgNox7fFJAe2OUtd7AO2p3zFrWh4hAAAAAElFTkSuQmCC";
}
}
</script>
</body>
or load after window is loaded with window.onload
<head>
<script>
var playing = true;
var flag = false;
window.onload = function () {
if (/Android|iPhone|iPad|Mobile|Mobi|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(navigator.userAgent)) {
playing = false;
} else {
document.getElementById('sound_icon').src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAAuUlEQVRoQ+2YwQ2AIAxFYRwncS3WchLH0YN6IWp/QhtCeJ5rgfd/W0JOg3958P0nDtBbQRRAgUYCWKgRYPPv8yiwlO1QcO1l/YXilefZi6yA18JeeTjAl52w0E3GAoGFsJDRk7FQDcirf3vloYgpYor4IsBlrnaC1b/pQhUxLISFPtqpVUtMYiYxk5hJ/O4Bq3swiaedxMq7aI8Y+S7UY3PKmhxAoRQZgwKRdJXcKKBQioxBgUi6Su4TGV3gMZ8LoyUAAAAASUVORK5CYII=";
}
}
function EvalSound(soundobj) {
var thissound = document.getElementById(soundobj);
if (!playing) {
thissound.play();
playing = true;
document.getElementById('sound_icon').src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAAuUlEQVRoQ+2YwQ2AIAxFYRwncS3WchLH0YN6IWp/QhtCeJ5rgfd/W0JOg3958P0nDtBbQRRAgUYCWKgRYPPv8yiwlO1QcO1l/YXilefZi6yA18JeeTjAl52w0E3GAoGFsJDRk7FQDcirf3vloYgpYor4IsBlrnaC1b/pQhUxLISFPtqpVUtMYiYxk5hJ/O4Bq3swiaedxMq7aI8Y+S7UY3PKmhxAoRQZgwKRdJXcKKBQioxBgUi6Su4TGV3gMZ8LoyUAAAAASUVORK5CYII=";
} else if (playing) {
thissound.pause();
playing = false;
document.getElementById('sound_icon').src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAABdElEQVRoQ+2YuxWCQBBFl0Rb0TJM9NiFdoAVOHSAHWAZZtoFoXagGZHroOghMHA+++G4JCT7mTvv8VjIzMCvbOD1mwQQWsGkQFJA2IFkIWEDxdP/V4EJHI7G3Fc1LM/iNgoWYCswhYNt97WZgcaOdmeYXQV1sKeKAbqdrwiS19vFnl0Jc6IWwHN7ayzayhZoK7z7uVQB3iUjSNWY8caHrZwA9GxVoq0Kl1q4BHjbClPKrl3ZyjlAz1bt89GCqMauN4APiHLsegfQjt1QAGqxGxRAI3ajAJDEbkwArNiNDgCj9oJv8vaU+9NxJBoAPNreUIKyhgVQ3txRAGDx+8aMcs7ZKSgAFn7CjyL41S7flAkC8LJLltcwryh2iQIAiy/QLiXHLkEBOruof0N7sBAtFqmWcgbAjcUoACSxGBRAIxaDAGjGoncA7Vj0BjD4X4vUTrkaz45RVwVR100A1I5pj08KaHeUul5SgNox7fFJAe2OUtd7AO2p3zFrWh4hAAAAAElFTkSuQmCC";
}
}
</script>
</head>
<body>
<a href="javascript:null()" onClick="EvalSound('sound1'); return false; ">
<!-- PRE DEFINED PLAY ICON IS BELOW -->
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAABdElEQVRoQ+2YuxWCQBBFl0Rb0TJM9NiFdoAVOHSAHWAZZtoFoXagGZHroOghMHA+++G4JCT7mTvv8VjIzMCvbOD1mwQQWsGkQFJA2IFkIWEDxdP/V4EJHI7G3Fc1LM/iNgoWYCswhYNt97WZgcaOdmeYXQV1sKeKAbqdrwiS19vFnl0Jc6IWwHN7ayzayhZoK7z7uVQB3iUjSNWY8caHrZwA9GxVoq0Kl1q4BHjbClPKrl3ZyjlAz1bt89GCqMauN4APiHLsegfQjt1QAGqxGxRAI3ajAJDEbkwArNiNDgCj9oJv8vaU+9NxJBoAPNreUIKyhgVQ3txRAGDx+8aMcs7ZKSgAFn7CjyL41S7flAkC8LJLltcwryh2iQIAiy/QLiXHLkEBOruof0N7sBAtFqmWcgbAjcUoACSxGBRAIxaDAGjGoncA7Vj0BjD4X4vUTrkaz45RVwVR100A1I5pj08KaHeUul5SgNox7fFJAe2OUtd7AO2p3zFrWh4hAAAAAElFTkSuQmCC" id="sound_icon" name="Sound" width="" height="" title="Background Music Controls" class="" /></a>
<audio id="sound1" style="display: none; width: 0px; height: 0px;" src="https://audio.clyp.it/3fnnuaiw.mp3?Expires=1488659248&Signature=01NkRScwYO4XaJO46JuNzPRR6cYQfcL5~rJzAu-gIoNoXkiMVZwazwT--amuqYvreLCSRFnFAFUvwR3v9Xaq1iB4~OmKSWqtF9mSm-CUB2Moqtie8wpGIRxTAkDHnfhN0sy45sINjwFP2xyVumld78USPuCBfNU3kgux69YG-yA_&Key-Pair-Id=APKAJ4AMQB3XYIRCZ5PA" controls preload="auto" autobuffer autoplay>
</body>

Change video of video tag on scroll

I have a video tag say
<div class="phone" align="center">
<div class="phone-inner">
<video width="100%" height="100%" autoplay="" loop="" muted id="phonevideo">
<source src="vid/1.mp4" type="video/mp4">
</video>
</div>
</div>
I want to change the video when page scrolls and each time div changes like fueled.com. Say I have six divisions like
<div id="first></div>
<div id="two"></div>
<div id="three"></div>
<div id="four"></div>
<div id="five"></div>
<div id="six"></div>
When div 2 comes into view the video should change and when div 3 or 4 comes into view video should change again to something else. Here is my code which needs to be modified according to it.
$(window).scroll(function() {
var topDivHeight = $("#first").height();
var DivTop = $("#sixth").position().top;
var viewPortSize = $(window).height();
var triggerAt = 450;
var triggerHeight = (topDivHeight - viewPortSize) + triggerAt;
var test1 = (topDivHeight - viewPortSize) + 650;
var count = 0;
var number = jQuery.grep(mainTops, function(n, i) {
if (n < $(window).scrollTop())
{
count++;
}
});
$('.nav ul li a').css("color", "#fff");
$('.nav ul li a#nav'+count ).css("color", "#f60");
if($(window).scrollTop() >= triggerHeight && $(window).scrollTop() < DivTop) {
$('.phone').css('visibility', 'visible').fadeIn();
if($(window).scrollTop() >= test1){
$('#phonevideo').html('<source src="vid/2.mp4" type="video/mp4">'); // tried using this method but its not working here. Some other method needed here.
}
} else {
$('.phone').fadeOut();
}
});
Try this code:
$('#phonevideo').find("source").attr("src", "https://www.w3schools.com/tags/movie.mp4");
$('#phonevideo').get(0).load();
You can change source attribute like $('#phonevideo').find("source").attr("src","videosource")
and after changing source you need to load video $('#phonevideo').get(0).load()
You cannot directly replace the HTML as you do using function .html(), accordingly to the HTML specification
Dynamically modifying a source element and its attribute when the
element is already inserted in a video or audio element will have no
effect.
But what you can try as suggested by the document is to change what is playing, just use the src attribute on the media element directly and use function .load();
A working example below:
var btn = document.getElementById('btn'),
player = document.getElementById('phonevideo'),
source = document.getElementById('src');
btn.addEventListener('click', function(event) {
player.pause();
source.src = 'http://html5demos.com/assets/dizzy.mp4'; // change video
player.load(); // load it
});
<div class="phone" align="center">
<div class="phone-inner">
<video width="100%" height="100%" autoplay="" loop="" muted id="phonevideo">
<source id="src" src="http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4" type="video/mp4">
</video>
</div>
</div>
<button id="btn" type="button">Change Video!</button>
Using jQuery as on your example (not tested):
var player = $('#phonevideo');
player.find("source").attr("src", "http://html5demos.com/assets/dizzy.mp4");
player[0].load();
I've optimized your code. I have added a class to your divs and used the data attribute. Here is a working jsfiddle.
<div class="phone" align="center">
<div class="phone-inner">
<video width="100%" height="100%" autoplay="" loop="" muted id="phonevideo">
<source src="vid/1.mp4" type="video/mp4">
</video>
</div>
</div>
<div id="first" class="view" data-vid-src="vid/1.mp4"></div>
<div id="two" class="view" data-vid-src="vid/2.mp4"></div>
<div id="three" class="view" data-vid-src="vid/3.mp4"></div>
<div id="four" class="view" data-vid-src="vid/4.mp4"></div>
<div id="five" class="view" data-vid-src="vid/5.mp4"></div>
<div id="six" class="view" data-vid-src="vid/6.mp4"></div>
To see some result I have added some css:
.phone {
position: fixed;
height: 200px;
width: 120px;
background: white;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -60px;
}
.view {
height: 500px;
}
#first {
background: red;
}
#two {
background: yellow;
}
#three {
background: green;
}
#four {
background: blue;
}
#five {
background: pink;
}
#six {
background: black;
}
And now the jQuery part.
function getCurrentElement(pos) {
var len = $('.view').length;
var i = 0;
var old_pos;
var ele_pos;
var old_ele;
var return_ele;
$('.view').each(function(){
i++;
offset = $(this).offset();
ele_pos = offset.top;
if(pos == ele_pos) {
return_ele = $(this);
return;
}
else if(ele_pos > pos && old_pos < pos) {
return_ele = old_ele;
return;
}
else if(ele_pos < pos && i == len) {
return_ele = $(this);
return;
}
old_pos = ele_pos;
old_ele = $(this);
});
return return_ele;
}
var old_ele = null;
$(window).scroll(function() {
var cur_pos = $(window).scrollTop();
current_element = getCurrentElement(cur_pos);
if(old_ele != null) {
if(current_element.attr('id') != old_ele.attr('id')) {
$('#phonevideo source').attr('src',current_element.attr('data-vid-src'))
}
}
old_ele = current_element;
});
I hope this code will help you. :)

How to stop one audio player from playing when I click another - javascript

I am creatinga page specifically for an ipad.
I have 12 audio players on a page. They are all working fine but if you click a second player the first one continues to play. I've seen this question asked before but none of the answers are specific to my code.
<script>
function EvalSound(soundobj) {
var thissound=document.getElementById(soundobj);
if (thissound.paused)
thissound.play();
else
thissound.pause();
thissound.currentTime = 0;
}
</script>
The players themselves:
<a href="card3_ipad.php?card=funny" onClick="EvalSound('song1'); return true;"
target="player"><IMG SRC="images/funnytab.gif" BORDER=0 WIDTH=128 HEIGHT=29>
</A>
<audio id="song1" style="display: none; width: 0px; height: 0px;"
src="mp3examples/funnyauto.mp3" controls preload="auto" autobuffer>
then another player is:
<a href="card3_ipad.php?card=country" onClick="EvalSound('song2'); return true;"
target="player"><IMG SRC="images/countrytab.gif" BORDER=0 WIDTH=128 HEIGHT=29>
</A>
<audio id="song2" style="display: none; width: 0px; height: 0px;"
src="mp3examples/countryauto.mp3" controls preload="auto" autobuffer>
Any help would be massively appreciated!
Cheers
Tom
use another variable which hold current active player
<script>
var currentPlayer;
function EvalSound(soundobj) {
var thissound=document.getElementById(soundobj);
if(currentPlayer && currentPlayer != thissound) {
currentPlayer.pause();
}
if (thissound.paused)
thissound.play();
else
thissound.pause();
thissound.currentTime = 0;
currentPlayer = thissound;
}
</script>

Categories

Resources