Trimmed video doesn't open after downloading - javascript

I made a simple prototype for a webtool that can trim videos (editing start and end times of the video). The issue is: whenever I download the trimmed video, it doesn't open on my machine. I tried different players (VLC, Media Player Classic, Windows media player), even tried to open this in the webtool by uploading it.
After failing to open a file I saw an error saying that there was an error opening the file. I think the error is in the trimming process?
The code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Video Trimmer</title>
<style>
body {
display: flex;
flex-direction: column;
align-items: center;
font-family: sans-serif;
}
input[type="file"] {
padding: 10px;
font-size: 18px;
}
video {
width: 500px;
height: 300px;
background-color: lightgray;
}
input[type="range"] {
width: 500px;
}
button {
padding: 10px 20px;
font-size: 18px;
background-color: lightblue;
color: white;
border: none;
border-radius: 5px;
}
</style>
</head>
<body>
<h1>Video Trimmer</h1>
<input type="file" id="fileInput">
<br>
<br>
<video controls id="videoPlayer"></video>
<br>
<br>
<input type="range" id="trimStart">
<input type="range" id="trimEnd">
<br>
<br>
<button id="downloadButton">Download Trimmed Video</button>
<script>
const fileInput = document.getElementById("fileInput");
const videoPlayer = document.getElementById("videoPlayer");
const trimStart = document.getElementById("trimStart");
const trimEnd = document.getElementById("trimEnd");
const downloadButton = document.getElementById("downloadButton");
let mediaSource = new MediaSource();
fileInput.addEventListener("change", (event) => {
const file = event.target.files[0];
const url = URL.createObjectURL(file);
videoPlayer.src = url;
});
videoPlayer.addEventListener("loadedmetadata", () => {
trimStart.max = videoPlayer.duration;
trimEnd.max = videoPlayer.duration;
trimEnd.value = videoPlayer.duration;
});
trimStart.addEventListener("input", () => {
videoPlayer.currentTime = trimStart.value;
});
trimEnd.addEventListener("input", () => {
videoPlayer.currentTime = trimEnd.value;
});
downloadButton.addEventListener("click", () => {
const file = fileInput.files[0];
const reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function() {
const fileBuffer = reader.result;
const startTime = trimStart.value;
const endTime = trimEnd.value;
const startByte = fileBuffer.byteLength * (startTime / videoPlayer.duration);
const endByte = fileBuffer.byteLength * (endTime / videoPlayer.duration);
const trimmedBuffer = fileBuffer.slice(startByte, endByte);
const trimmedBlob = new Blob([trimmedBuffer], {
type: "video/mp4"
});
const trimmedUrl = URL.createObjectURL(trimmedBlob);
const a = document.createElement("a");
a.style.display = "none";
a.href = trimmedUrl;
a.download = "trimmed-video.mp4";
document.body.appendChild(a);
a.click();
};
});
</script>
</body>
</html>

Related

How to call certain chord buttons instead of all the chord buttons from the chord library?

I have been able to build a chord library that plays the chord and also says the chord name. I'm now trying to build upon the chord library. How can I have only a limited amount of chord buttons be displayed on the UI instead of all of the chords that are being populated?
The top portion of the code (that is below) is displaying the four buttons but not playing the chord sounds or saying the chord names.
The other code after is showing all the chord buttons and playing the chord sounds and chord names.
We're trying to combine the two portions of code from below so that they play the chord names and sounds for the four chords above.
//In order to run in terminal insert the following code to activate localhost: npx parcel src/index.html
import { chordType, transpose, note } from '#tonaljs/tonal';
import { chord } from '#tonaljs/chord';
import { entries } from '#tonaljs/chord-dictionary';
import { Howler, howl } from 'howler';
const buttons = document.querySelector(".buttons");
const arrayOfChordNames = ["Major", "Minor", "Augmented", "Diminished"];
arrayOfChordNames.forEach((chord) => {
let buttonElement = createElement("button", chord);
buttons.appendChild(buttonElement);
});
function createElement(element, content) {
let newElement = document.createElement(element);
newElement.textContent = content;
return newElement;
}
// code above is displaying the four buttons but not playing the chord sound and chord name
//code below is showing all the chord buttons and playing the chord sound and chord names
// we're trying combine the chord from below so that it plays the audio from the chord names and sounds for the four chords above
const sound = new Howl({
src: ['assets/pianosprite.mp3'],
onload() {
console.log('Sound file has been loaded. Do something here!');
soundEngine.init();
},
onloaderror(e, msg) {
console.log('Error', e, msg);
}
});
const startNotes = ['C', 'C#', 'Db', 'D', 'D#', 'Eb', 'E', 'F', 'F#', 'Gb', 'G', 'G#', 'Ab', 'A', 'A#', 'Bb', 'B'];
const startNoteSelector = document.querySelector('#start-note');
const octaveSelector = document.querySelector('#octave');
const buttons = document.querySelector('.buttons');
const intervalsInChord = document.querySelector('.intervals-in-chord');
const notesInChord = document.querySelector('.notes-in-chord');
let selectedStartNote = 'C';
let selectedOctave = '1';
const app = {
init() {
this.setupStartNotes();
this.setupOctaves();
this.setupButtons();
this.setupEventListeners();
},
setupStartNotes() {
startNotes.forEach(noteName => {
let noteNameOption = this.createElement('option', noteName);
startNoteSelector.appendChild(noteNameOption);
});
},
setupOctaves() {
for (let i = 1; i <= 6; i++) {
let octaveNumber = this.createElement('option', i);
octaveSelector.appendChild(octaveNumber);
}
},
setupButtons() {
const chordNames = entries().map(entry => {
return entry.aliases[0];
});
chordNames.forEach(chordName => {
let chordButton = this.createElement('button', chordName);
buttons.appendChild(chordButton);
});
},
setupEventListeners() {
startNoteSelector.addEventListener('change', () => {
selectedStartNote = startNoteSelector.value;
});
octaveSelector.addEventListener('change', () => {
selectedOctave = octaveSelector.value;
});
buttons.addEventListener('click', (event) => {
if (event.target.classList.contains('buttons')) {
return;
}
selectedChord = event.target.innerText;
this.displayAndPlayChord(selectedChord, event);
});
},
displayAndPlayChord(selectedChord, event) {
let chordIntervals = chord(selectedChord).intervals;
intervalsInChord.innerText = chordIntervals.join(' - ');
const startNoteWithOctave = selectedStartNote + selectedOctave;
let chordNotes = chordIntervals.map(val => {
return transpose(startNoteWithOctave, val);
});
notesInChord.innerText = chordNotes.join(' - ');
soundEngine.play(chordNotes, event);
},
createElement(elementName, content) {
let element = document.createElement(elementName);
element.innerHTML = content;
return element;
}
}
const soundEngine = {
init() {
const lengthOfNote = 2400;
let timeIndex = 0;
for (let i = 24; i <= 96; i++) {
sound['_sprite'][i] = [timeIndex, lengthOfNote];
timeIndex += lengthOfNote;
}
},
play(soundSequence, event) {
const buttons =
document.querySelector(".buttons");
const chordNameTable = {
"M": "Major",
"m": "Minor",
"dim": "diminished",
"aug": "Augmented"
}
buttons.addEventListener("click", (event) => {
})
function textToSpeech(message, chord) {
const speech = new SpeechSynthesisUtterance();
speech.lang = "en-US";
speech.text = message;
speech.volume = 1;
speech.rate = 1;
speech.pitch = 1;
window.speechSynthesis.speak(speech);
// When speaking has finished
speech.onend = function() {
playChord(chord);
}
}
function playChord(chord) {
// Wait a second (1000 miliseconds) before playing the chord
setTimeout(() => {
const chordMidiNumbers = soundSequence.map(noteName => {
return note(noteName).midi;
});
sound.volume(0.05);
chordMidiNumbers.forEach(noteMidiNumber => {
sound.play(noteMidiNumber.toString());
});
console.log("Chord to be played", chord);
}, 500);
}
const sayThis = chordNameTable[event.target.textContent];
textToSpeech(sayThis, event.target.textContent);
}
}
app.init();
const allChordNames = entries()
chordEntries.map(entry => {
return entry.aliases[0];
})
console.log(Array.isArray (allChordNames));
body {
font-family: Lato, Sans-serif;
color: #fff;
background: #000000
}
.controls{
display: flex;
justify-content: center;
}
.controls select {
margin: 0 10px;
}
.chord-notes {
display: flex;
flex-direction: column;
align-items: center;
font-size: 1.5em;
}
.chord-notes p {
margin: 10px 0;
}
/*width makes the page more condensed towards the left*/
.buttons {
display: flex;
flex-wrap: wrap;
width: 60%;
}
/*min-width divides columns into 3 instead of 4, max-width creates a set size for the button*/
.buttons button{
flex-grow: 1;
min-width: 20%;
max-width: 20%;
height: 50px;
font-size: 1em;
background: #7200CC;
border: none;
color: #fff;
margin: 10px;
}
<!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>Chord Dictionary</title>
<link rel="stylesheet" href="styles.css">
<head>
<style>
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
}
li {
float: left;
}
li a {
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
li a:hover {
background-color: #A400DD;
}
</style>
</head>
</head>
<ul>
<li><a class="active" href="/home">Home</a></li>
<li>Lessons</li>
<li>Practice</li>
<li>Test</li>
<li>Demo</li>
<li>Triads</li>
<li>Sign Up</li>
<li>Login</li>
</ul>
</head>
<body>
<h1>This is the Triads page!</h1>
<div class="controls">
<label for="start-note">Start note:</label>
<select name="start note" id="start-note">
</select>
<label for="octave">Octave: </label>
<select name="Octave" id="octave">
</select>
<label for="Loops">Loops: </label>
<select id="Loops">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="loop">loop</option>
</select>
</div>
<div class="chord-notes">
<p class="notes-in-chord">C3 - D3 - E3 - F#3 - A3</p>
<p class="intervals-in-chord">P1 - M3 - P5 - M7</p>
</div>
<div class="buttons">
</div>
<script type="module" src="triads.js"></script>
</body>
</html>

Javascript Unable to access global object inside a function in an onclick event

We have the usual example code where everything works.
(myFunction gets triggered on an onclick event.)
"use strict";
console.clear();
const obj = {
name: "falana",
count: 0
};
function myFunction() {
obj.count++;
console.log(obj.count);
console.log(obj.name);
console.log(obj);
}
---Output---
1
"falana"
// [object Object]
{
"name": "falana",
"count": 1
}
From this example, we can access a global object obj inside another function (in this case, myFunction) without any ReferenceError.
I was trying to create a single page Twitter clone (only DOM manipulation) and kept getting this error.
Uncaught ReferenceError: Cannot access 'userData' before initialization at postMessage
---Javascript that's causing error---
window.onload = function() {
console.clear();
}
const userData = {
username: 'Chinmay Ghule',
userhandle: generateUserhandle(this.username),
userPostCount: 0
};
function generateUserhandle(userData) {
const usernameArr = userData.username.split(" ");
usernameArr.forEach(element => {
element.toLowerCase();
});
return "#" + usernameArr.join("");
}
// posts message entered in #message-text to
// message-output-container.
function postMessage() {
console.log(userData);
// get message from #message-text.
const message = document.getElementById('message-text').value;
console.log(`message: ${message}`);
// check for length.
console.log(`message length: ${message.length}`);
if (message.length === 0) {
return;
}
// create new div.
const card = document.createElement('div');
const userInfo = document.createElement('div');
const userMessage = document.createElement('div');
const usernameSpan = document.createElement('span');
const userhandleSpan = document.createElement('span');
const beforeTimeDotSpan = document.createElement('span');
const timeSpan = document.createElement('span');
usernameSpan.classList.add('username');
userhandleSpan.classList.add('userhandle');
beforeTimeDotSpan.classList.add('before-time-dot');
timeSpan.classList.add('time');
userInfo.appendChild(usernameSpan);
userInfo.appendChild(userhandleSpan);
userInfo.appendChild(beforeTimeDotSpan);
userInfo.appendChild(timeSpan);
console.log(`userInfo : ${userInfo}`);
userInfo.classList.add('user-info');
userMessage.classList.add('output-message');
card.appendChild(userInfo);
card.appendChild(userMessage);
console.log(`card : ${card}`);
card.classList.add('output-message');
userMessage.innerText = message;
// check for number of posts.
if (userData.userPostCount === 0) {
let noMessageDiv = document.getElementById("no-message-display");
noMessageDiv.remove();
}
// append new div.
const messageOutputContainer = document.getElementById('message-output-container');
messageOutputContainer.appendChild(card);
// increment userPostCount.
userData.userPostCount++;
}
Why am i getting this ReferenceError in this case, while it didn't in our first example code?
Your code had quite some issues...
The biggest change here was getting rid of generateUserhandle entirely and making it with a getter.
get userhandle() {
return this.username.toLowerCase()
},
Working demo
window.onload = function() {
console.clear();
}
const userData = {
username: 'Chinmay Ghule',
get userhandle() {
return this.username.toLowerCase()
},
userPostCount: 0
};
// posts message entered in #message-text to
// message-output-container.
function postMessage() {
console.log(userData);
// get message from #message-text.
const message = document.getElementById('message-text').value;
console.log(`message: ${message}`);
// check for length.
console.log(`message length: ${message.length}`);
if (message.length === 0) {
return;
}
// create new div.
const card = document.createElement('div');
const userInfo = document.createElement('div');
const userMessage = document.createElement('div');
const usernameSpan = document.createElement('span');
const userhandleSpan = document.createElement('span');
const beforeTimeDotSpan = document.createElement('span');
const timeSpan = document.createElement('span');
usernameSpan.classList.add('username');
userhandleSpan.classList.add('userhandle');
beforeTimeDotSpan.classList.add('before-time-dot');
timeSpan.classList.add('time');
userInfo.appendChild(usernameSpan);
userInfo.appendChild(userhandleSpan);
userInfo.appendChild(beforeTimeDotSpan);
userInfo.appendChild(timeSpan);
console.log(`userInfo : ${userInfo}`);
userInfo.classList.add('user-info');
userMessage.classList.add('output-message');
card.appendChild(userInfo);
card.appendChild(userMessage);
console.log(`card : ${card}`);
card.classList.add('output-message');
userMessage.innerText = message;
// check for number of posts.
if (userData.userPostCount === 0) {
let noMessageDiv = document.getElementById("no-message-display");
noMessageDiv.remove();
}
// append new div.
const messageOutputContainer = document.getElementById('message-output-container');
messageOutputContainer.appendChild(card);
// increment userPostCount.
userData.userPostCount++;
}
*,
*::before,
*::after {
box-sizing: border-box;
}
body {
margin: 0px;
padding: 0px;
font-family: Arial, Helvetica, sans-serif;
}
#container {
/*background-color: lightskyblue;*/
margin: 2.5rem 25%;
}
#user-info {
/*background-color: orange;*/
padding-bottom: 0.5rem;
}
.username {
font-weight: bold;
}
.userhandle,
.before-time-dot,
.time {
opacity: 0.75;
}
#message-text {
width: 100%;
margin-bottom: 0.5rem;
font-size: 18px;
padding: 0.5rem;
resize: none;
border-radius: 0.5rem;
outline: 1px solid lightgray;
}
#message-button {
float: right;
padding: 0.375rem 1.5rem;
font-weight: bold;
font-size: 18px;
border-radius: 1rem;
}
#message-button:hover {
background-color: lightgray;
}
#message-input-container {
background-color: lightskyblue;
padding: 1rem;
border-radius: 0.5rem;
}
#message-input-container::after {
content: "";
clear: both;
display: table;
}
#message-output-container {
/*background-color: lightskyblue;*/
margin-top: 30px;
border-top: 3px solid black;
}
#no-message-display {
text-align: center;
padding: 0.5rem;
}
.output-message {
padding: 0.5rem;
font-size: 18px;
border-bottom: 1px solid lightgray;
}
<div id="container">
<div id="message-input-container">
<textarea id="message-text" rows="5" placeholder="Type your message here..." contenteditable="" value=""></textarea>
<input id="message-button" type="button" value="Post" onclick="postMessage();" />
</div>
<div id="message-output-container">
<div id="no-message-display">
<span>No messages yet!</span>
</div>
</div>
</div>

Get localStorage value on page load

I've searched the internet but I can't seem to find anything that works for me.
Here is the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Heating System Control</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
strLED1 = "";
strLED2 = "";
strText1 = "";
strText2 = "";
var LED1_state = 0;
var LED2_state = 0;
function GetArduinoIO()
{
nocache = "&nocache=" + Math.random() * 1000000;
var request = new XMLHttpRequest();
request.onreadystatechange = function()
{
if (this.readyState == 4) {
if (this.status == 200) {
if (this.responseXML != null)
{
// XML file received - contains analog values, switch values and LED states
document.getElementById("input1").innerHTML =
this.responseXML.getElementsByTagName('analog')[0].childNodes[0].nodeValue;
document.getElementById("input2").innerHTML =
this.responseXML.getElementsByTagName('analog')[1].childNodes[0].nodeValue;
// LED 1
if (this.responseXML.getElementsByTagName('LED')[0].childNodes[0].nodeValue === "on") {
document.getElementById("LED1").innerHTML = "ON";
document.getElementById("LED1").style.backgroundColor = "green";
document.getElementById("LED1").style.color = "white";
LED1_state = 1;
}
else {
document.getElementById("LED1").innerHTML = "OFF";
document.getElementById("LED1").style.backgroundColor = "red";
document.getElementById("LED1").style.color = "white";
LED1_state = 0;
}
// LED 2
if (this.responseXML.getElementsByTagName('LED')[1].childNodes[0].nodeValue === "on") {
document.getElementById("LED2").innerHTML = "ON";
document.getElementById("LED2").style.backgroundColor = "green";
document.getElementById("LED2").style.color = "white";
LED2_state = 1;
}
else {
document.getElementById("LED2").innerHTML = "OFF";
document.getElementById("LED2").style.backgroundColor = "red";
document.getElementById("LED2").style.color = "white";
LED2_state = 0;
}
}
}
}
}
// send HTTP GET request with LEDs to switch on/off if any
request.open("GET", "ajax_inputs" + strLED1 + strLED2 + nocache, true);
request.send(null);
setTimeout('GetArduinoIO()', 1000);
strLED1 = "";
strLED2 = "";
}
function GetButton1()
{
if (LED1_state === 1)
{
LED1_state = 0;
strLED1 = "&LED1=0";
}
else
{
LED1_state = 1;
strLED1 = "&LED1=1";
}
}
function GetButton2()
{
if (LED2_state === 1)
{
LED2_state = 0;
strLED2 = "&LED2=0";
}
else
{
LED2_state = 1;
strLED2 = "&LED2=1";
}
}
function SendText1()
{
nocache = "&nocache=" + Math.random() * 1000000;
var request = new XMLHttpRequest();
strText2 = "&txt2=" + document.getElementById("txt_form1").form_text1.value + "&end2=end";
request.open("GET", "ajax_inputs" + strText2 + nocache, true);
request.send(null);
}
function SendText2()
{
nocache = "&nocache=" + Math.random() * 1000000;
var request = new XMLHttpRequest();
strText1 = "&txt1=" + document.getElementById("txt_form2").form_text2.value + "&end1=end";
request.open("GET", "ajax_inputs" + strText1 + nocache, true);
request.send(null);
}
function clsTxt1()
{
setTimeout(
function clearTxt()
{
document.getElementById("txt_form1").form_text1.value = "";
}, 500)
}
function clsTxt2()
{
setTimeout(
function clearTxt()
{
document.getElementById("txt_form2").form_text2.value = "";
}, 500)
}
function Threshold1()
{
var thr1 = document.getElementById("txt_form1").form_text1.value;
document.getElementById("thresh1").innerHTML = thr1;
}
function Threshold2()
{
var thr2 = document.getElementById("txt_form2").form_text2.value;
document.getElementById("thresh2").innerHTML = thr2;
}
</script>
<style>
.IO_box
{
float: left;
margin: 0 20px 20px 0;
border: 1px solid black;
padding: 0 5px 0 5px;
width: 100px;
height: 196px;
text-align: center;
}
h1
{
font-family: Helvetica;
font-size: 120%;
color: blue;
margin: 5px 0 10px 0;
text-align: center;
}
h2
{
font-family: Helvetica;
font-size: 85%;
color: black;
margin: 10px 0 5px 0;
text-align: center;
}
p, form
{
font-family: Helvetica;
font-size: 80%;
color: #252525;
text-align: center;
}
button
{
font-family: Helvetica;
font-size: 80%;
max-width: 100px;
width: 90px;
height: 25px;
margin: 0 auto;
text-align: center;
border: none;
}
input
{
font-family: Helvetica;
font-size: 80%;
max-width: 100px;
width: 90px;
height: 25px;
margin: 0 auto;
text-align: center;
border: none;
}
.small_text
{
font-family: Helvetica;
font-size: 70%;
color: #737373;
text-align: center;
}
textarea
{
resize: none;
max-width: 90px;
margin-bottom: 1px;
text-align: center;
}
</style>
</head>
<body onload="GetArduinoIO(); Threshold1()">
<h1>Heating System Control</h1>
<div class="IO_box">
<h2>Room One</h2>
<p>Temp1 is: <span id="input1">...</span></p>
<button type="button" id="LED1" onclick="GetButton1()" color="white" backgroundColor="red" style="border: none;">OFF</button><br /><br />
<form id="txt_form1" name="frmText">
<textarea name="form_text1" rows="1" cols="10"></textarea>
</form>
<input type="submit" value="Set Temp" onclick="SendText1(); clsTxt1(); Threshold1();" style ="background-color:#5F9EA0" />
<p>Threshold: <span id="thresh1">...</span></p>
</div>
<div class="IO_box">
<h2>Room Two</h2>
<p>Temp2 is: <span id="input2">...</span></p>
<button type="button" id="LED2" onclick="GetButton2()" color="white" backgroundColor="red" style="border: none;">OFF</button><br /><br />
<form id="txt_form2" name="frmText">
<textarea name="form_text2" rows="1" cols="10"></textarea>
</form>
<input type="submit" value="Set Temp" onclick="SendText2(); clsTxt2(); Threshold2();" style ="background-color:#5F9EA0" />
<p>Threshold: <span id="thresh2">...</span></p>
</div>
</body>
</html>
So my question is, How can I keep the value inserted in the text area even after I reload the page (from the "Threshold1()" function)? I found a few examples with "localStorage" and JQuery, but I have no idea how to call the saved value when I reload the page.
Any help would be appreciated.
Thanks in advance,
Stefan.
Local Storage Explained
The localStorage object likes to store strings, so how would one store large objects, let's say some complex data structure? - Simple, JavaScript has a neat function built in, look up JSON.stringify(object). So all you would need to do is something like below to store some complex object is something like the code I've provided below. Then to retrieve an object from the localStorage you'll want to use JSON.parse(object);.
To look into localStorage, I strongly suggest you take a look at the likes of MDN and if you want to look into the JSON.parse and JSON.stringify functions, you can also find them both here:
JSON.parse() link
JSON.stringify() link
// vanilla js version of $(document).ready(function(){/*code here*/});
window.ready = function(fnc) {
if (typeof fnc != "function") {
return console.error("You need to pass a function as a param.");
}
try { // try time out for some old IE bugs
setTimeout(function () {
document.addEventListener("DOMContentLoaded", fnc());
}, 10)
} catch (e) {
try { // sometimes timeout won't work
document.addEventListener("DOMContentLoaded", fnc());
} catch (ex) {
console.log(ex);
}
}
};
// shorter than $(document).ready();
ready(function() {
var object = {
name: "Jack",
age: 30,
location: "U.S.A.",
get_pay: function() {
console.log("test");
}
},
test;
console.log(object);
var obj_string = JSON.stringify(object);
// run a test
var run_test = function() {
// output the stored object
test = localStorage.getItem("test");
console.log(test);
// to make js turn it into an object again
test = JSON.parse(localStorage.getItem("test"));
console.log(test);
};
// demo of trying to store an actual object
try {
localStorage.setItem("test", object);
run_test();
} catch (e) {
console.log(e);
}
// demo of trying to store the string
try {
localStorage.setItem("test", obj_string);
run_test();
} catch (e) {
console.log(e);
}
});
You can use this JSFiddle : http://jsfiddle.net/xpvt214o/45115/
here we are using Cookie concept and jquery.cookie.js to accomplish what you are trying to do.
to properly check the fiddle you need to press "Run" every time, you can open the same fiddle in 2 tabs write something in the first fiddle then just press run in the 2nd fiddle tab the value should automatically update, here the
$(function(){}); replicates your pageload
My question isn't exactly answered, but I completely avoided storing info on a device. Now I'm just reading the value straight from the arduino and it works. But thanks to everyone that provided some help.

Javascript file download with Joomla

I am coding in Joomla in which I have self synchronized three audio tracks i.e when one of them starts on the web page the other stop and below is the JS code for the same;
<script type="text/javascript">
function _(id) {
return document.getElementById(id);
}
//function Download(url) {
//document.getElementById('my_iframe').src = url;
//};
function audioApp() {
var audio = new Audio();
var audio_folder = "/images/audios/how-to-meditate/relaxation/";
var audio_ext = ".mp3";
var audio_index = 1;
var is_playing = false;
var playingtrack;
var trackbox = _("trackbox");
var tracks = {
"track1": ["Relaxation in the Forest", "relaxation-in-the-forest"],
"track2": ["Relaxation of the Muscles", "relaxation-of-the-muscles"],
"track3": ["Relaxation with the Breath", "relaxation-with-the-breath"]
};
for (var track in tracks) {
var tb = document.createElement("div");
var pb = document.createElement("button");
//var dn = document.createElement("button");
var tn = document.createElement("div");
tb.className = "trackbar";
pb.className = "playbutton";
//dn.className = "download";
tn.className = "trackname";
tn.innerHTML = tracks[track][0];
pb.id = tracks[track][1];
tb.appendChild(pb);
pb.addEventListener("click", switchTrack);
tb.appendChild(tn);
trackbox.appendChild(tb);
audio_index++;
}
audio.addEventListener("ended", function() {
_(playingtrack).style.background = "url(images/icons/play.JPG)";
playingtrack = "";
is_playing = false;
});
function switchTrack(event) {
if (is_playing) {
if (playingtrack != event.target.id) {
is_playing = true;
_(playingtrack).style.background = "url(images/icons/play.JPG)";
event.target.style.background = "url(images/icons/pause.JPG)";
audio.src = audio_folder + event.target.id + audio_ext;
audio.play();
} else {
audio.pause();
is_playing = false;
event.target.style.background = "url(images/icons/play.JPG)";
}
} else {
is_playing = true;
event.target.style.background = "url(images/icons/pause.JPG)";
if (playingtrack != event.target.id) {
audio.src = audio_folder + event.target.id + audio_ext;
}
audio.play();
}
playingtrack = event.target.id;
}
}
window.addEventListener("load", audioApp);
</script>
Below is the Styling;
<style scoped="scoped" type="text/css">
.trackbar {
background: #FFF;
height: 50px;
font-family: "Arial";
}
.trackbar:nth-child(even) {
background: #FFF;
}
.playbutton {
opacity: .8;
display: block;
float: left;
width: 40px;
height: 40px;
margin: 0px 50px 0px 50px;
background: url(images/icons/play.JPG) no-repeat;
border: none;
cursor: pointer;
outline: none;
}
.playbutton:hover {
opacity: 1;
}
.trackname {
float: left;
color: #000;
margin: 12px 400px 0px 14px;
font-size: 20px;
}
And the html code is;
<div id="trackbox"> </div>
Having achieved this I want to place a download icon besides every mp3 which allows me to download the track, I have the link to download the file and it is placed in the media (Content) of Joomla and also I want a icon to be placed which will trigger the download onClick.
Is there a JS script code available with which I can implement the same.
This is what solved the issue;
<input alt="Submit" src="images/icons/download.jpg" type="image" onclick="document.getElementById('anything').click()" />

Get increment value from input area in a for-loop

I have done this working fiddle:
HTML
<div id="container">
<div id="input_container">
<label for="increment_t">Set t-increment value (default 0.1):</label>
<input id="increment_t" type="number" min="0" max="1" step="0.1" value="0.1" />
</div>
<br />
<div id="generator_container">
<a id="downloadlink" download="outfile.txt">Download</a>
<button id="create_link">Export output</button>
</div>
</div>
CSS
#container {
position: absolute;
display: block;
left: 0;
top: 0;
padding: 10px 10px; /* (top-bottom) (left-right) */
z-index: 1;
}
#input_container {
display: block;
float: left;
margin-bottom: 10px;
}
#increment_t {
max-width: 50px;
}
#generator_container {
display: block;
float: right;
}
#downloadlink {
display: none;
margin-right: 10px;
}
#create_link {
float: right;
}
JavaScript
(function () {
var t_values;
var t_values_list = [];
for ( var t=0; t<=1; t+=0.1 ){
t_values = t.toFixed(1);
t_values_list.push(t_values);
}
var textFile = null;
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
var create_link = document.getElementById('create_link');
create_link.addEventListener('click', function () {
alert(t_values_list);
var link = document.getElementById('downloadlink');
link.href = makeTextFile(t_values_list.join('\n'));
link.style.display = 'inline-block';
}, false);
})();
but I want to set the increment value for the "t" variable (i.e. 0.1, in the for-loop) taking it from the input area. I tried in this way:
JavaScript
(function () {
var t_values;
var t_values_list = [];
alert(document.getElementById("increment_t").value); // test to get the t value, to use it in the following loop for
for ( var t=0, increment_t=document.getElementById("increment_t").value; t<=1; t+=increment_t ){
t_values = t.toFixed(1);
t_values_list.push(t_values);
}
var textFile = null;
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
var create_link = document.getElementById('create_link');
create_link.addEventListener('click', function () {
alert(t_values_list);
var link = document.getElementById('downloadlink');
link.href = makeTextFile(t_values_list.join('\n'));
link.style.display = 'inline-block';
}, false);
})();
but It doesn't work. Thanks for your help
If you getting numbers from somewhere else in javascript...always parse them. parseInt(..., 10) or in your example: parseFloat

Categories