Detect Audible Sound with JavaScript - javascript

Is there any way to detect whether a certain page is making noise using jscript? Some sort of environmental variable or something that tracks the status of the speakers? I'm attempting to write a script that puts an icon on the Tab Title if that Tab is making sound.

No, this isn't possible.
Lots of plugins can make sound, and they all do it in their own way. There is no catch-all here.
Perhaps on Vista/7 where applications sound usage is actually kept track of, and when using a browser like Chrome that makes a separate process for each page, you might have more luck. It would involve figuring out which processes are playing sound, then figuring out what page each process had loaded. Through JavaScript though? No way.

Scraped from Quora
The majority of sound on the web is
done through Flash. Flash doesn't
inform the browser when it is making
sound. That is to say, if two
different tabs are running Flash, the
browser can't know which is the one
making sound.
The introduction of the HTML5 media
tags could help in this area, but I
suspect an audio indicator that only
worked some of the time (for non-Flash
pages) would be more frustrating than
no audio indicator.
(Pay no attention to the comment below (in the linked Quora question) saying Chrome displays a 'play' icon when sound is played. That's Soundcloud changing the title of its own page, not Google Chrome)

I don't think you can detect whether or not the speakers are making noise in JavaScript, however you may not have to.
Perhaps you could keep track of this yourself, implicitly. So for example, if there is a play button, on click you could start playing the audio and show the icon. Once the user clicks the stop button, you stop the audio and hide the icon.

This can help you, fbc_array is de array noise use fbc_array[value] for get this noise.
example:
window.onload = function() {
var file = document.querySelector('input');
file.onchange = function(e) {
var boton = e.target.files;
var archivo = boton[0];
if (!archivo.type.match(/audio/)) {
alert("Seleciona un audio, por favor.");
} else {
var lector = new FileReader();
lector.readAsDataURL(archivo);
lector.addEventListener("load", initMp3Player, false);
}
}
function initMp3Player(e) {
var result = e.target.result;
var audio = document.querySelector('audio');
audio.src = result;
context = new AudioContext();
analyser = context.createAnalyser();
source = context.createMediaElementSource(audio);
source.connect(analyser);
analyser.connect(context.destination);
frameLooper();
}
function frameLooper() {
window.requestAnimationFrame(frameLooper);
fbc_array = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(fbc_array);
document.querySelector('#o1').style.transform = 'scale(' + fbc_array[1] / 75 + ')';
document.querySelector('#o2').style.transform = 'scale(' + fbc_array[50] / 100 + ')';
document.querySelector('#o3').style.transform = 'scale(' + fbc_array[100] / 200 + ')';
}
}
* {
margin: 0;
padding: 0;
cursor: default;
}
body {
background: #222;
}
input {
position: fixed;
left: 0;
right: 0;
margin: auto;
background: rgb(76, 142, 250);
border: 0;
border-radius: 2px;
box-sizing: border-box;
color: #fff;
cursor: pointer;
font-size: .875em;
padding: 10px 24px;
}
#o1 {
position: fixed;
display: block;
top: 0;
bottom: 0;
left: 0;
right: 0;
height: 100px;
width: 100px;
background: #333;
margin: auto;
border-radius: 50%;
}
#o2 {
position: fixed;
display: block;
top: 0;
bottom: 0;
left: 0;
right: 0;
height: 100px;
width: 100px;
margin: auto;
background: #0074d9;
border-radius: 50%;
}
#o3 {
position: fixed;
display: block;
top: 0;
bottom: 0;
left: 0;
right: 0;
height: 100px;
width: 100px;
margin: auto;
background: #fff;
border-radius: 50%;
}
<input type="file"></input>
<audio autoplay></audio>
<div id="o1"></div>
<div id="o2"></div>
<div id="o3"></div>

Related

Can I use requestAnimationFrame to smooth out scroll behaviour?

I have a small scroll effect which simulate that a logo will disappear if a lower div will scroll over it.
Currently I'm checking if two divs are intersecting. If this is true, then the height of the div of the logo will decrease with the scroll position of the div beneath.
Unfortunately, my demo is not foolproof and some fragments of the logo are still visible.
Is there a way to do this jank-free? Maybe with requestAnimationFrame?
function elementsOverlap(el1, el2) {
const domRect1 = el1.getBoundingClientRect();
const domRect2 = el2.getBoundingClientRect();
return !(
domRect1.top > domRect2.bottom ||
domRect1.right < domRect2.left ||
domRect1.bottom < domRect2.top ||
domRect1.left > domRect2.right
);
}
const el1 = document.querySelector(".logo");
const el2 = document.querySelector(".clickblocks");
let scrollPositionEl2;
let heightDifference;
const logoHeight = el1.offsetHeight;
document.addEventListener("DOMContentLoaded", () => {
var scrollDirectionDown;
scrollDirectionDown = true;
window.addEventListener("scroll", () => {
if (this.oldScroll > this.scrollY) {
scrollDirectionDown = false;
} else {
scrollDirectionDown = true;
}
this.oldScroll = this.scrollY;
// test
if (scrollDirectionDown) {
if (elementsOverlap(el1, el2) === true) {
scrollPositionEl2 = el2.getBoundingClientRect().top;
heightDifference = logoHeight - scrollPositionEl2 + 100;
//console.log(logoHeight - heightDifference);
el1.style.height = `${logoHeight - heightDifference}px`;
}
} else {
//scrolling up
scrollPositionEl2 = el2.getBoundingClientRect().top - 100;
el1.style.height = `${scrollPositionEl2}px`;
//console.log(logoHeight);
}
});
});
#import url("https://fonts.googleapis.com/css2?family=Inter:wght#900&display=swap");
.wrapper {
max-width: 100vw;
margin: 0 auto;
background-image: url("https://picsum.photos/1920/1080");
background-size: cover;
background-attachment: fixed;
height: 1200px;
position: relative;
&::after {
content: "";
position: absolute;
background: rgba(0, 0, 0, 0.3);
width: 100%;
height: 100%;
inset: 0;
}
}
body {
margin: 0;
}
main {
width: 100%;
height: 100vh;
position: relative;
z-index: 1;
}
.clickblocks {
width: 100%;
height: 200px;
display: grid;
grid-template-columns: repeat(12, (minmax(0, 1fr)));
}
.clickblock {
transition: all ease-in-out 0.2s;
backdrop-filter: blur(0px);
border: 1px solid #fff;
height: 100%;
grid-column: span 6 / span 6;
font-size: 54px;
font-weight: 700;
padding: 24px;
font-family: "Inter", sans-serif;
color: white;
text-transform: uppercase;
&:hover {
backdrop-filter: blur(10px);
}
}
.logo {
background: url("https://svgshare.com/i/ivR.svg");
width: 100%;
background-repeat: no-repeat;
background-position: top;
position: fixed;
top: 100px;
}
.logo-wrapper {
position: relative;
}
<div class="wrapper">
<main>
<div class="logo-wrapper" style="height: 390px">
<div class="logo" style="height: 300px">
</div>
</div>
<div class="clickblocks">
<div class="clickblock">
Some Content
</div>
</div>
</main>
</div>
Few things here to optimize your performance.
getBoundingClientRect() is a rather expensive calculation. If there are NO other options it's fine.
The Intersection Observer API is a lot more performant, and you can set the root element on the API. Then observe the element that is moving. This should be able to telly you if their are colliding.
Whenever you do scroll based logic, you should really try and throttle the logic so that the scroll any fires ever 16.6ms. That will reduce the number of times the calculations are made, and speed things up on the FE.
Learn how to use Google Chrome's performance tab. It can be overwhelming at first, but it gives you the ability to drill into the exact piece of code that's slowing your site down.
Learn about JS's event loop, and what's really going on under the hood. This video by Jake Archibald really help me understand it.
Hope this helped, sorry that I didn't give you an actual solution.

How can a span id that div classes are applied to be looped?

I'm new to coding, and I'm trying to learn the basics. I wanted to practice what I learned by making flashcards (nothing complicated like saving it, importing it, or exporting it). So far, I made a table that the user can edit. I know how to gather data from the table, but I don't know how to make a CSS flashcard appear every time the user adds a card to the table. I am aware that the code will not work since I put the CSS in JavaScript since this code is just meant to show what I am trying to do. Also, if I am taking a completely wrong approach, please let me know. Thank you! Please excuse the poor variable naming, I was just testing some things.
<script>
function getFlashcardValue() {
for (var repeat = 0; repeat < 200; repeat++) {
var Table = document.getElementById('flashcardsTable');
var column1 = 0;
var column2 = 1;
var numberOfFlashcards = 2;
for (var row = 0; row < numberOfFlashcards; row++) {
var Cells = Table.rows.item(1).cells;
var Question1 = Cells.item(column1).innerHTML;
var Cells1 = Table.rows.item(1).cells;
var Answer1 = Cells.item(column2).innerHTML;
document.getElementById("myFlashcardQuestion" + row).innerHTML = Question1;
document.getElementById("myFlashcardAnswer" + row).innerHTML = Answer1;
<div class="flip-card">
<div class="flip-card-inner">
<div class="flip-card-front">
<span id="myFlashcardQuestion1"></span>
</div>
<div class="flip-card-back">
<span id="myFlashcardAnswer1"></span>
</div>
</div>
</div>
}
}
}
</script>
<p style = "font-size: 25px">Hover over the flashcard to flip it!</p>
<style>
.flip-card {
background-color: transparent;
width: 350px;
height: 175px;
margin: auto;
padding: 5px 5px;
perspective: 1000px;
}
.flip-card-inner {
position: relative;
background-color: lightblue;
width: 100%;
height: 100%;
text-align: center;
transition: transform 0.6s;
transform-style: preserve-3d;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
}
.flip-card:hover .flip-card-inner {
transform: rotateY(180deg);
}
.flip-card-front, .flip-card-back {
position: absolute;
width: 100%;
height: 100%;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
}
.flip-card-front {
background-color: lightblue;
width: 350px;
height: 175px;
color: black;
font-size: 35px;
text-alignment: center;
}
.flip-card-back {
background-color: red;
color: white;
font-size: 35px;
text-alignment: center;
transform: rotateY(180deg);
}
</style>
So first of all you can create a code snippet in stackoverflows editor (see below), or use jsfiddle and post a shared-link.
It depends on which action the user has to do after he enters the data.
If it is, for example, a button click, then it is possible to call a function that shows the user's input in the flashcard. Now if you want that for every single Q&A you have to create Elements in the for loop and edit them there. Here a little example.
var allCards = document.getElementById("allCards");
for (var i = 1; i <= 5; i++) { //i used 5, you should use length of data
var question = document.createElement("div");
question.textContent = "Question " + i;
question.classList.add("flip-card");
allCards.appendChild(question);
}
.flip-card {
background-color: lightblue;
width: 350px;
height: 175px;
margin: 10px auto;
padding: 5px 5px;
font-size: 35px;
text-align: center;
}
<div id="allCards"></div>
Edit:
As promised, here is an example of how you can set up the flip cards.
https://jsfiddle.net/ybu59hfp/1/
Your concern should now be resolved. If you have any further questions, feel free to write to me in the chat or read a little about JavaScript on the Internet.

How can I style the <audio> tag with javascript?

I'm setting up a custom audio player for my website, but I can't get it to work, how do I style the tag?
Hello all, first question I'll be asking on this website because this issue is driving me nuts. So I've been trying to make this custom audio player for my website but I'm a complete noob when it comes to javascript, but I managed to fumble my way to create an audio playlist for the default tag, however after many, MANY attempts, after looking up some tutorials, I can't seem to get this same code I have to work when I create a custom audio player as most of the tutorials I've seen only deal with a single music track.
Here's the code I'm using at the moment
HTML5:
<div id="playerbg">
<style>
#playlist{
list-style: none;
}
#playlist li a{
color: black;
text decoration:none;
}
#playlist .current-song a{
color: blue;
}
</style>
<audio src="" controls id="audioPlayer">
</audio>
<ul id="playlist">
<li class="current-song">01. Supersonic</li>
<li>02. Supersonic (Instrumental)</li>
</ul>
<script src="https://code.jquery.com/jquery-2.2.0.js">
</script>
<script src="/audioPlayer.js">
</script>
<script>
audioPlayer()
</script>
</div><!-- playerbg ends here -->
Javascript:
function audioPlayer(){
var currentSong = 0;
$("#audioPlayer")[0].src = $("#playlist li a")[0];
$("#playlist li a").click(function(e){
e.preventDefault();
$("#audioPlayer")[0].src = this;
$("#audioPlayer")[0].play();
$("#playlist li").removeClass("current-song");
currentSong = $(this).parent().index();
$(this).parent().addClass("current-song");
});
$("#audioPlayer")[0].addEventListener("ended", function(){
currentSong++;
if(currentSong == $("#playlist li a").length)
currentSong = 0;
$("#playlist li").removeClass("current-song");
$("#playlist li:eq("+currentSong+")").addClass("current-song");
$("#audioPlayer")[0].src = $("#playlist li a")[currentSong].href;
$("#audioPlayer")[0].play();
});
}
Here's the current player:
https://imgur.com/BTAYBrk
Here's what I roughly hope to achieve (with the playlist from the first image intact):
https://imgur.com/e7Xyt3N
You can not style the audio tag directly.
As I saw your code, I have it clear that you know it already. But the issue is that you need to code the JavaScript part to make it work.
Understanding JavaScript for audio tag.
When you have an HTML audio tag like this:
<audio src="your_audio.mp3"></audio>
You can reference it in your code like this:
let audio = document.querySelector("audio");
And with this, in your audio variable, you can access pretty much to every control in the audio tag. Some of them and that I think you may need are:
Methods:
play() To play the loaded audio.
pause() To pause the loaded audio.
Properties:
currentTime The time value (between 0 and 1) of the playing media.
volume The actual volume of the audio. (Value between 0 and 1)
duration The duration of the audio.
Using event listeners.
One of the most common uses of JavaScript is exactly that, event listeners. This helps your application with handling what happens on the browser (button clicks, mouse move, window resize, etc), so this will be a lot useful to create your own player and handle this events to update the real audio tag.
Based on your example of this player:
You can see a working example of a player with a similar style of your desire. Hope it helps.
Player:
var audio = document.querySelector("audio"),
playButton = document.querySelector("#audio-play"),
progress = document.querySelector("#audio-playbar"),
volumeRange = document.querySelector("#volume-range");
const play = () =>{
if(audio.paused){
console.log("play");
playButton.classList.add("paused");
audio.play();
}else{
console.log("pause");
playButton.classList.remove("paused");
audio.pause();
}
};
const bwd = () =>{
console.log("bwd");
audio.currentTime = 0;
};
const fwd = () =>{
console.log("fwd");
audio.currentTime += 5;
};
volumeRange.addEventListener("change",(event)=>{
audio.volume = event.target.value / 100;
});
audio.addEventListener("timeupdate",(e)=>{
progress.value = (e.target.currentTime / e.target.duration) * 100;
if(e.target.currentTime/e.target.duration === 1){
play();
audio.currentTime = 0;
}
});
document.querySelector("#audio-mute").addEventListener("mouseenter",(event)=>{
document.querySelector("#volume-control")
.style = "display: block;";
});
document.querySelector("#volume-control").addEventListener("mouseleave",(event)=>{
document.querySelector("#volume-control")
.style = "display: none;";
});
playButton.addEventListener("click",play);
document.querySelector("#audio-fwd")
.addEventListener("click",fwd);
document.querySelector("#audio-bwd")
.addEventListener("click",bwd);
#audio-player{
background: #005bab;
width: 300px;
height: 40px;
border-radius: 15px;
position: relative;
}
#audio-player::after{
content: "";
background: url('https://i.imgur.com/aDz7QOn.png') no-repeat;
display: block;
position: absolute;
width: 100vw;
height: 100vh;
margin-top: -8px;
margin-left: 270px;
}
#audio-play{
width: 20px;
height: 20px;
background: url('https://i.imgur.com/pOdMApr.png') no-repeat;
background-size: cover;
position: absolute;
margin: 10px;
margin-left: 15px;
cursor: pointer !important;
}
#audio-bwd{
width: 25px;
height: 15px;
background: url('https://i.imgur.com/z4j9Qp9.png') no-repeat;
background-size: cover;
position: absolute;
margin: 12px;
margin-left: 45px;
cursor: pointer !important;
}
#audio-fwd{
width: 25px;
height: 15px;
background: url('https://i.imgur.com/E7X60LH.png') no-repeat;
background-size: cover;
position: absolute;
margin: 12px;
margin-left: 75px;
cursor: pointer !important;
}
#progress{
position: absolute;
margin: 8px;
margin-left: 105px;
}
#audio-playbar{
border-radius: 0;
background: black;
height: 10px;
}
progress[value]::-webkit-progress-bar {
background-color: #000;
border-radius: 0;
}
progress[value]::-webkit-progress-value{
background: #c0c0c0;
}
.paused{
background: url('https://i.imgur.com/EwMhtwR.png') no-repeat !important;
background-size: cover;
}
#audio-mute{
width: 26px;
height: 26px;
position: absolute;
margin: 11px;
z-index: 11;
margin-left: 278px;
background: url('https://i.imgur.com/g3W1tUI.png') no-repeat;
}
#volume-control{
position: absolute;
margin-left: 230px;
display: none;
z-index: 12;
}
<audio src="http://developer.mozilla.org/#api/deki/files/2926/=AudioTest_(1).ogg">
Your browser does not support the <code>audio</code> element.
</audio>
<div id="audio-player">
<div id="controls">
<span id="audio-play"></span>
<span id="audio-bwd"></span>
<span id="audio-fwd"></span>
</div>
<div id="progress">
<progress id="audio-playbar" max="100" value="60"></progress>
</div>
<div id="mute">
<span id="audio-mute"></span>
<span id="volume-control">
<input id="volume-range" type="range" min="0" max="100">
</span>
</div>
</div>

Why is this Jsfiddle not working: tracking.js face detection example

I'm trying to get a JSFiddle example of http://trackingjs.com/examples/face_tag_friends.html working but the hover effect is not working as the website shows. Here's my JSFiddle:
https://jsfiddle.net/lolptdr/25yqfyjo/6/
I had to use a proxy on raw.githubusercontent.com and changed it to raw.githack.com for the external scripts referenced in the HTML to bypass the MIME type complaint. No other console errors so what else is wrong?
What else can I check to get the same effect as shown on trackingjs.com's website?
window.onload = function() {
var img = document.getElementById('img');
var tracker = new tracking.ObjectTracker('face');
tracking.track(img, tracker);
tracker.on('track', function(event) {
event.data.forEach(function(rect) {
plotRectangle(rect.x, rect.y, rect.width, rect.height);
});
});
var friends = ['Thomas Middleditch', 'Martin Starr', 'Zach Woods'];
var plotRectangle = function(x, y, w, h) {
var rect = document.createElement('div');
var arrow = document.createElement('div');
var input = document.createElement('input');
input.value = friends.pop();
rect.onclick = function name() {
input.select();
};
arrow.classList.add('arrow');
rect.classList.add('rect');
rect.appendChild(input);
rect.appendChild(arrow);
document.getElementById('photo').appendChild(rect);
rect.style.width = w + 'px';
rect.style.height = h + 'px';
rect.style.left = (img.offsetLeft + x) + 'px';
rect.style.top = (img.offsetTop + y) + 'px';
};
};
* {
margin: 0;
padding: 0;
font-family: Helvetica, Arial, sans-serif;
}
.demo-title {
position: absolute;
width: 100%;
background: #2e2f33;
z-index: 2;
padding: .7em 0;
}
.demo-title a {
color: #fff;
border-bottom: 1px dotted #a64ceb;
text-decoration: none;
}
.demo-title p {
color: #fff;
text-align: center;
text-transform: lowercase;
font-size: 15px;
}
.demo-frame {
background: url(frame.png) no-repeat;
width: 854px;
height: 658px;
position: fixed;
top: 50%;
left: 50%;
margin: -329px 0 0 -429px;
padding: 95px 20px 45px 34px;
overflow: hidden;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
box-sizing: border-box;
}
.demo-container {
width: 100%;
height: 530px;
position: relative;
background: #eee;
overflow: hidden;
border-bottom-right-radius: 10px;
border-bottom-left-radius: 10px;
}
.dg.ac {
z-index: 100 !important;
top: 50px !important;
}
/* example's CSS */
#photo:hover .rect {
opacity: .75;
transition: opacity .75s ease-out;
}
.rect:hover * {
opacity: 1;
}
.rect {
border-radius: 2px;
border: 3px solid white;
box-shadow: 0 16px 28px 0 rgba(0, 0, 0, 0.3);
cursor: pointer;
left: -1000px;
opacity: 0;
position: absolute;
top: -1000px;
}
.arrow {
border-bottom: 10px solid white;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
height: 0;
width: 0;
position: absolute;
left: 50%;
margin-left: -5px;
bottom: -12px;
opacity: 0;
}
input {
border: 0px;
bottom: -42px;
color: #a64ceb;
font-size: 15px;
height: 30px;
left: 50%;
margin-left: -90px;
opacity: 0;
outline: none;
position: absolute;
text-align: center;
width: 180px;
transition: opacity .35s ease-out;
}
#img {
position: absolute;
top: 50%;
left: 50%;
margin: -173px 0 0 -300px;
}
<script src="https://raw.githack.com/eduardolundgren/tracking.js/master/build/tracking.js"></script>
<script src="https://raw.githack.com/eduardolundgren/tracking.js/master/build/data/face.js"></script>
<div class="demo-title">
<p>tracking.js - hover image to see all faces detected</p>
</div>
<div class="demo-frame">
<div class="demo-container"> <span id="photo"><img id="img" src="https://raw.githubusercontent.com/eduardolundgren/tracking.js/master/examples/assets/faces.jpg" /></span>
</div>
</div>
All the above answers address why this is failing very well, but here's a working example of tracker.js in jsfiddle using a flickr image:
http://jsfiddle.net/rambutan2000/v5v49bax/
Flickr seems to have Access-Control-Allow-Origin set correctly in the header. I've had limited success using a proxy (crossorigin.me).
Thi is a simplified version of this example:
https://trackingjs.com/examples/face_hello_world.html
First I had to get valid URLs to the Tracker includes, I used this service:
http://rawgit.com. Look in the "External Resources" in jsfiddle.
I based this off an example which uses a XMLHttpRequest to retrieve the image data as a buffer, then load this into an img element. This negates SOME CORS issues on the img element as it was sourced from code not a URL. The rest is ripped straight from the Tracker example referenced above.
JS:
// use http://rawgit.com/ to get js urls from github
// use https://crossorigin.me/ to get around CORS for image reference
function _arrayBufferToBase64(buffer) {
var binary = ''
var bytes = new Uint8Array(buffer)
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i])
}
return window.btoa(binary);
}
window.plot = function(x, y, w, h) {
var $rect = $("<div></div>");
$rect.addClass("rect");
$rect.offset({ top: y, left: x });
$rect.width(w).height(h);
$("#demo-container").append($rect);
};
var imgURL = 'https://c1.staticflickr.com/4/3943/15715482121_d7120a6e0b_z.jpg'; // Works!
//var imgURL = 'https://placeimg.com/640/480/people'; // Does not work
//var imgURL = 'https://crossorigin.me/https://placeimg.com/640/480/people'; // Works!
var oReq = new XMLHttpRequest();
oReq.open("GET", imgURL, true);
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent) {
var arrayBuffer = oReq.response; // Note: not oReq.responseText
if (arrayBuffer) {
var x = imgURL.split('.');
var ext = x[x.length - 1];
var b64img = _arrayBufferToBase64(arrayBuffer);
$("#img").attr('src', 'data:image/' + ext + ';base64,' + b64img).appendTo($('body'));
var img = document.getElementById('img');
var tracker = new tracking.ObjectTracker(['face']);
tracker.setStepSize(1.7);
tracking.track('#img', tracker);
tracker.on('track', function(event) {
event.data.forEach(function(rect) {
console.log(rect);
window.plot(rect.x, rect.y, rect.width, rect.height);
});
});
}
};
oReq.send(null);
HTML:
<div id="demo-container">
<img id="img" src="" />
</div>
CSS:
.rect {
position:absolute;
border-style: solid;
border-width: 2px;
border-color: blue;
}
#demo-container {
position:absolute;
}
This is a quick answer, but hopefully it'll help you understand what's going on. It's failing because the code is trying to load this resource: http://trackingjs.com/bower/tracking.js/examples/assets/frame.png
You can see that it's loaded on the original page: http://trackingjs.com/examples/face_tag_friends.html and you can see that your JSFiddle attempts to load it as well (although with a different host, the same relative path). When the browser attempts to GET https://fiddle.jshell.net/25yqfyjo/7/show/frame.png, a 404 happens because the file doesn't exist and this halts execution.
Look at your Developer Tools while running the JSFiddle. My guess is, that this other script you load (https://raw.githack.com/eduardolundgren/tracking.js/master/build/data/face.js), which appears to be binary data (rendering the picture) shouldn't be included. Instead, walk through the base documentation for http://trackingjs.com/ and understand how to use face detection on your own photo. Presumably, it'll be easier and work.
Cross Origin:
i have updated your code to use DOMContentLoaded and manually firing the event so you can see the problem: https://jsfiddle.net/25yqfyjo/11/
So i'm forcing the event with
// Create the event
var event = new CustomEvent("DOMContentLoaded", { "detail": "Content Loaded trigger" });
// Dispatch/Trigger/Fire the event
document.dispatchEvent(event);
And you can see in the console the error:
Uncaught SecurityError: Failed to execute 'getImageData' on
'CanvasRenderingContext2D': The canvas has been tainted by
cross-origin
data.tracking.trackCanvasInternal_ #
tracking.js:196(anonymous function) #
tracking.js:221img.onload #
tracking.js:472
This is caused by the fact your loading an image from another URL into the canvas that is being used by your code (even though you can't see it the var tracker = new tracking.ObjectTracker('face'); will be using a canvas) i think for purposes of JS Fiddle you could change the Image to Base64 encoded and that would correct the problem.
You will need more actions :
First open developer tool F12 (chrome) goto tab console switch frame to :
Now you can track your code . I found your js code looks like your use of
window.onload is little critical in any way .(tag breaks) . You have more times in code onload event.
Every time when you call window.onload = SOMETHING you are override this function . window.onload is function with just one time execution . Simply on load document . This is not JQ .
Also you have :
GET https://fiddle.jshell.net/lolptdr/25yqfyjo/6/show/frame.png 404 (Not Found)
This is namespace { } for js ,
if you have error like this .
{
exeOK()
IamError() ; BREAKS HERE
IneverLoaded()
}
This can be also your solution :
Check in debugger did you load js code to the end.

Responsive YouTube Modal & Playing Video on Mobile

When a user clicks on an image thumbnail it triggers an opaque modal background and YouTube video player sits on top of this.
1) How would I go about making this iFrame fluid responsive when the viewport is scaled down?
2) Even assuming we can get #1 working, how would I go about getting these YouTube videos to open in the default native player on iPhone/Android rather than the scaled down modal window which I'm hoping to accomplish in #1.
Currently the modal background and YouTube modal work perfectly on Desktop, but things begin to go South around 900px and down as the browser window is scaled in. Currently on iPhone/Android the videos don't play at all, not really sure what happens.
HTML
<section class="modal-wrapper valign">
<section class="youtube-modal">
<button class="close-youtube-modal"></button>
<iframe src="http://www.youtube.com/v/OnAHIH4p5Vg?version=3&enablejsapi=1&autoplay=1" frameborder="0" allowfullscreen="allowfullscreen" class="youTubeIframe" width="854" height="480"></iframe>
</section>
CSS
section.modal-wrapper {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 10000;
text-align: center;
background: rgba(0, 0, 0, .55);
}
section.youtube-modal {
display: none;
width: 854px;
position: relative;
z-index: 1000;
background-color: transparent;
}
button.close-youtube-modal {
position: absolute;
top: 0px;
left: 0px;
width: 25px;
height: 26px;
background: url(../images/close-youtube.png) no-repeat;
cursor: pointer;
outline: none;
border: none;
}
section.youtube-modal iframe {
margin-top: 35px;
}
JS
function youTubeModal() {
var thumbnail = document.querySelectorAll('.thumbnail-container ul li'),
modalWrapper = document.querySelector('.modal-wrapper'),
youTubeModal = document.querySelector('.modal-wrapper .youtube-modal'),
youTubeIframe = document.querySelector('.youTubeIframe'),
closeVideo = document.querySelector('.close-youtube-modal'),
staticVideoContainer = document.querySelector('.staticVideoContainer'),
videoWidth = 854,
videoHeight = 480;
for (var i=0;i<thumbnail.length;i++) {
thumbnail[i].addEventListener('click', function (e) {
var data = e.target.getAttribute('data-videoid');
modalWrapper.style.display = 'block';
youTubeModal.style.display = 'inline-block';
youTubeIframe.setAttribute('src', 'http://www.youtube.com/v/' + data + '?version=3&enablejsapi=1&autoplay=1');
youTubeIframe.setAttribute('width', videoWidth);
youTubeIframe.setAttribute('height', videoHeight);
}, false);
}
staticVideoContainer.addEventListener('click', function(e) {
var data = staticVideoContainer.getAttribute('data-videoid');
modalWrapper.style.display = 'block';
youTubeModal.style.display = 'inline-block';
youTubeIframe.setAttribute('src', 'http://www.youtube.com/v/' + data + '?version=3&enablejsapi=1&autoplay=1');
youTubeIframe.setAttribute('width', videoWidth);
youTubeIframe.setAttribute('height', videoHeight);
}, false);
closeVideo.addEventListener('click', function () {
youTubeModal.style.display = 'none';
modalWrapper.style.display = 'none';
youTubeIframe.setAttribute('src', '');
}, false);
}
for responsiveness, follow this solution:
.iframe-parent {
float: none;
clear: both;
width: 100%;
position: relative;
padding-bottom: 56.25%;
padding-top: 25px;
height: 0;
}
.iframe-parent iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
added 'iframe-parent' class to the parent div of the iframe tag

Categories

Resources