In the following code, my attempts at creating the preparePlaceholder on the the fly
has failed, and the only error is "parent is not defined" from the error console.
I'm modifying this example for use with a JS object literal and could use the
sage wisdom of StackOverflow.
TIA
imageGallery={
// IDs
placeHolderID:'placeholder',
imageNavListID:'imagegallerylist',
// CSS Classes
init:function(){
if(!document.getElementById || !document.createTextNode){return;}
imageGallery.preparePlaceholder();// Call to preparePlacholder
// Prepare Gallery:
imageGallery.navList = document.getElementById(imageGallery.imageNavListID);
if(!imageGallery.navList){return;}
var links = imageGallery.navList.getElementsByTagName('a');
for(var i = 0; i<links.length;i++){
links[i].onclick = function(){
// Call to showPic function:
return imageGallery.showPic(this) ? false : true;
}
}
},
showPic:function(whichpic){
imageGallery.pHolder=document.getElementById(imageGallery.placeHolderID);
if(!imageGallery.pHolder || imageGallery.pHolder.nodeName != "IMG"){return;}
var source = whichpic.getAttribute("href");
imageGallery.pHolder.setAttribute("src",source);
if(document.getElementById("description")){
// var text = whichpic.getAttribute("title");
var text = whichpic.getAttribute("title") ? whichpic.getAttribute("title") : "";
var description = document.getElementById("description");
if(description.firstChild.nodeType == 3){
description.firstChild.nodeValue = text;
}
}
return true;
},
preparePlaceholder:function(){
var placeholder = document.createElement("img");
placeholder.setAttribute("id", "placeholder");
placeholder.setAttribute("src","images/placeholder.gif");
placeholder.setAttribute("alt","My Image Gallery");
// alert(placeholder);
var description = document.createElement("p");
description.setAttribute("id","description");
var desctext = document.createTextNode("Choose an Image");
description.appendChild(desctext);
var gallery = document.getElementById("imageGallery");
imageGallery.insertAfter(placeholder,imageGallery);
imageGallery.insertAfter(description,imageGallery.placeholder);
// alert("Function Called");
},
// Utility Functions
insertAfter:function(newElement,targetElement){
var parent = targetElement.parentNode;
if(parent.lastChild == targetElement){
parent.appendChild(newElement);
} else {
parent.insertBefore(newElement,targetElement.nextSibling);
}
},
addLoadEvent:function(func){
var oldonload = window.onload;
if(typeof window.onload != 'function'){
window.onload = func;
}else{
window.onload = function(){
oldonload();
func();
}
}
}
}
// End Utility Functions
imageGallery.addLoadEvent(imageGallery.init);
// window.onload=imageGallery.init;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="uft-8" />
<title>Image Gallery</title>
<link rel="stylesheet" href="styles/layout.css" type="text/css" media="screen" title="layout" charset="utf-8" />
</head>
<body>
<h1>Snapshots</h1>
<ul id="imagegallerylist">
<!--Links Here-->
</ul>
<script src="scripts/imageGallery.js"></script>
</body>
</html>
Have an example here which doesn't produce errors. I have removed your comments and put in comments where I have changed the code.
JavaScript:
var gallery = document.getElementById("imageGallery");
// Changed from imageGallery to gallery
imageGallery.insertAfter(placeholder, gallery);
// Changed from imageGallery.placeholder to placeholder
imageGallery.insertAfter(description, placeholder);
HTML:
<div id="imageGallery"></div> <!-- Added this div -->
Related
I'm using Visual studio code for programming and I'm testing my codes with live server. But today I'm stuck with an error.
My code is below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=,, initial-scale=1.0">
<title>Test lesson</title>
<script src="/JS/jquery-3.6.1.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/main.css"/>
<script>
$(function(){
$("div").find("*").css({
"color":"red",
"border":"2px solid red",
});
});
</script>
</head>
<body class="ancestors">
<div class="descendants" style="width:500px;">div
<p class="first">P (child)
<span>Span (grandchild)</span>
</p>
<p class="second">P (child)
<span>Span (grandchild)</span>
</p>
</div>
</body>
</html>
So, when i run this code with live server, my browser says :
// <![CDATA[ <-- For SVG support if ('WebSocket' in window) { (function () { function refreshCSS() { var sheets = [].slice.call(document.getElementsByTagName("link")); var head = document.getElementsByTagName("head")[0]; for (var i = 0; i < sheets.length; ++i) { var elem = sheets[i]; var parent = elem.parentElement || head; parent.removeChild(elem); var rel = elem.rel; if (elem.href && typeof rel != "string" || rel.length == 0 || rel.toLowerCase() == "stylesheet") { var url = elem.href.replace(/(&|\?)_cacheOverride=\d+/, ''); elem.href = url + (url.indexOf('?') >= 0 ? '&' : '?') + '_cacheOverride=' + (new Date().valueOf()); } parent.appendChild(elem); } } var protocol = window.location.protocol === 'http:' ? 'ws://' : 'wss://'; var address = protocol + window.location.host + window.location.pathname + '/ws'; var socket = new WebSocket(address); socket.onmessage = function (msg) { if (msg.data == 'reload') window.location.reload(); else if (msg.data == 'refreshcss') refreshCSS(); }; if (sessionStorage && !sessionStorage.getItem('IsThisFirstTime_Log_From_LiveServer')) { console.log('Live reload enabled.'); sessionStorage.setItem('IsThisFirstTime_Log_From_LiveServer', true); } })(); } else { console.error('Upgrade your browser. This Browser is NOT supported WebSocket for Live-Reloading.'); } // ]]>
Can anyone help me please for fix that error?
I have tried all the variations I can find on stackoverflow, but I can still not get the voice to change on SpeechSynthesis
Below is the standalone code that fills a dropdown with all the available voices and allows me to select which voice I want.
Unfortunately this code does not change the voice. Also, before changing the voice. msg.voice is null, even though it has been used to list all the available voices.
Can anyone tell me what is wrong with the code? (console.log(msg.voice); gives a null before being set)
<!doctype html>
<html>
<head>
<SCRIPT>
var msg = new SpeechSynthesisUtterance();
voices = window.speechSynthesis.getVoices();
var numberOfVoices=0;
function Main(){
voiceSelect=document.getElementById("voiceSelect");
setTimeout(getVoicesFunction,2000);
}
function getVoicesFunction(){
msg = new SpeechSynthesisUtterance("hello");
numberOfVoices=0;
speechSynthesis.getVoices().forEach(function(voice) {
var option = document.createElement('option');
option.text = option.value = voice.voiceURI;
voiceSelect.add(option, 0);
numberOfVoices=numberOfVoices+1;
});
voiceSelect.onchange = voiceChange;
}
function voiceChange(){
textToSpeech("this is the old voice");
var selectedOption = this[this.selectedIndex];
selectedVoice = selectedOption.text;
msg = new SpeechSynthesisUtterance();
voices = window.speechSynthesis.getVoices();
msg = new SpeechSynthesisUtterance();
console.log("before change msg.voice");
console.log(msg.voice);
for(i = 0; i < numberOfVoices ; i++) {
if(voices[i].voiceURI === selectedVoice) {
var temp="changing the voice number to "+i;
setTimeout(textToSpeech,2000,temp);
msg.voice = voices[i];
console.log(msg.voice);
var tempVoiceNumber=i;
};
}
setTimeout(textToSpeech,4000,"this is the new voice");
}
function textToSpeech(tspeech){
msg = new SpeechSynthesisUtterance();
msg.text = tspeech;
speechSynthesis.speak(msg);
console.log("speech "+tspeech);
}
</SCRIPT>
</head>
<body onload= "Main()" id= "mainb">
<div id="container">
<select name="Combobox1" size="1" id="voiceSelect">
</select>
</div>
</body>
</html>
IanR, I copied the code and it works for me. I cut out the pitch and rate controls and made the html simpler, but it's basically the same.
If it doesn't work for you are you getting any console errors?
var synth = window.speechSynthesis;
var inputForm = document.querySelector('form');
var inputTxt = document.querySelector('.txt');
var voiceSelect = document.querySelector('select');
/*var pitch = document.querySelector('#pitch');
var pitchValue = document.querySelector('.pitch-value');
var rate = document.querySelector('#rate');
var rateValue = document.querySelector('.rate-value');*/
var voices = [];
function populateVoiceList() {
voices = synth.getVoices();
for (i = 0; i < voices.length; i++) {
var option = document.createElement('option');
option.textContent = voices[i].name + ' (' + voices[i].lang + ')';
if (voices[i].default) {
option.textContent += ' -- DEFAULT';
}
option.setAttribute('data-lang', voices[i].lang);
option.setAttribute('data-name', voices[i].name);
voiceSelect.appendChild(option);
}
}
populateVoiceList();
if (speechSynthesis.onvoiceschanged !== undefined) {
speechSynthesis.onvoiceschanged = populateVoiceList;
}
inputForm.onsubmit = function(event) {
event.preventDefault();
var utterThis = new SpeechSynthesisUtterance(inputTxt.value);
var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name');
for (i = 0; i < voices.length; i++) {
if (voices[i].name === selectedOption) {
utterThis.voice = voices[i];
}
}
//utterThis.pitch = pitch.value;
//utterThis.rate = rate.value;
synth.speak(utterThis);
inputTxt.blur();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>61016951</title>
<script src="61016951.js" defer></script>
</head>
<body>
<div id="div">
<form>
<input type="text" class="txt">
<select></select>
<button type="submit">Play</button>
</form>
</div>
</body>
</html>
Stripping out all the extra bits in your code, here's how you'll need to handle the asynchronous loading on speechSynthesis.getVoices();
if (voiceLoaded()) {
speak();
} else {
speechSynthesis.addEventListener('voiceschanged', speak);
}
function speak() {
const utterance = new SpeechSynthesisUtterance('text');
utterance.voice = getFemaleVoice();
speechSynthesis.speak(utterance);
}
function getFemaleVoice() {
const voiceIndex = 4;
return speechSynthesis.getVoices()[voiceIndex];
}
function voiceLoaded() {
return speechSynthesis.getVoices().length;
}
If the voices array has loaded already then it'll speak the utterance, otherwise this code will add the event listener on the voiceschanged event which will fire once the browser loads the array of voices and then your callback to speak will run.
I am saving the states of a series of checkboxes into localstorage rendering as checked: true or false, and with that data I re-check those checkboxes at a later time. All works for the most part, however a stray checkbox is becoming checked, it's data is reporting false as it should, and as the others do to not be checked, but it's becoming checked.
Sadly, all my attempts including the one answered; kill the functionality, and no checkboxes become re-checked.
/................../
// reset before loading
var clist = document.querySelectorAll('.k-treeview-lines input[type="checkbox"]');
for (var i = 0; i < clist.length; ++i) { clist[i].checked = false;
}
// $saved checkbox states, recheck
const defaultData = {
userAchkData: []
};
const localStorageData = JSON.parse(localStorage.getItem(username));
let userA = localStorageData || defaultData;
let inputs = userA[username].userAchkData;
inputs.forEach(function (input) {
if (input.checked) {
var inputElem = document.getElementById(input.id)
inputElem.click();
}
return false; // attempt
});
}
I have also tried input.stopPropagation()
This is how I'm saving the checkboxes if helpful:
// Save layer funct, $all current checkbox states user localStorage
function layerSaver() {
const defaultData = {
userAchkData: []
};
const localStorageData = JSON.parse(localStorage.getItem(username));
let userA = localStorageData || defaultData;
let inputs = document.querySelectorAll('.k-treeview-lines input[type="checkbox"]');
userA[username].userAchkData = [];
inputs.forEach(function (input) {
userA[username].userAchkData.push({
id: input.id,
checked: input.checked
});
});
localStorage.setItem(username, JSON.stringify(userA));
console.log(JSON.stringify(userA));
}
The propagation happens on the click event, not on the node itself. If you do something like:
inputElem.addEventListener('click', function(e) { e.stopPropagation(); });
It will stop the event bubbling up.
But looking at what you're trying to achieve, maybe using click() is going to make things more difficult for you. Instead of simulating a click, you can programmatically check the boxes like:
inputElem.checked = true;
You are just looping over and unchecking all of your checkboxes when you assign false to their .checked property. It looks like you are looping over an Array of Objects with id properties, which you are using to get your Elements, then just .click()ing them. I see nothing assigning to localStorage. Take a look at this:
//<![CDATA[
/* js/external.js */
let get, post, doc, html, bod, nav, M, I, mobile, S, Q, special, unspecial; // for use on other loads
addEventListener('load', ()=>{
get = (url, success, context)=>{
const x = new XMLHttpRequest;
const c = context || x;
x.open('GET', url);
x.onload = ()=>{
if(success)success.call(c, JSON.parse(x.responseText));
}
x.send();
}
post = function(url, send, success, context){
const x = new XMLHttpRequest;
const c = context || x;
x.open('POST', url);
x.onload = ()=>{
if(success)success.call(c, JSON.parse(x.responseText));
}
if(typeof send === 'object' && send && !(send instanceof Array)){
if(typeof FormData !== 'undefined' && send instanceof FormData){
x.send(send);
}
else{
let s, r = [];
for(let p in send){
s = send[p];
if(typeof s === 'object')s = JSON.stringify(s);
r.push(encodeURIComponent(p)+'='+encodeURIComponent(s));
}
x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); x.send(r.join('&'));
}
}
else{
throw new Error('send argument must be an Object');
}
return x;
}
doc = document; html = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id);
mobile = nav.userAgent.match(/Mobi/i) ? true : false;
S = (selector, within)=>{
var w = within || doc;
return w.querySelector(selector);
}
Q = (selector, within)=>{
var w = within || doc;
return w.querySelectorAll(selector);
}
special = str=>str.replace(/&/g, '&').replace(/'/g, ''').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');
unspecial = str=>str.replace(/&/g, '&').replace(/'/g, "'").replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');
// Put on another page, if you want. - except the end load
let data;
if(localStorage.data){
data = JSON.parse(localStorage.data);
}
else{
data = {friendly:false, loving:true, happy:false, greatful:true, smart:true};
}
for(let i=0,o,q=Q('#checks>input'),l=q.length; i<l; i++){
o = q[i];
o.checked = data[o.id] ? true : false;
o.onclick = function(){
data[this.id] = this.checked; localStorage.data = JSON.stringify(data);
}
}
}); // end load
//]]>
/* css/external.css */
*{
box-sizing:border-box; padding:0; margin:0;
}
html,body{
width:100%; height:100%; background:#ccc;
}
.main{
padding:10px;
}
#checks>*{
float:left;
}
#checks>input{
margin-right:4px; clear:left;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
<title>Title Here</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script src='js/external.js'></script>
</head>
<body>
<div class='main'>
<h2>Check All that Apply</h2>
<div id='checks'>
<input id='friendly' type='checkbox' /><label for='friendly'>friendly</label>
<input id='loving' type='checkbox' /><label for='loving'>loving</label>
<input id='happy' type='checkbox' /><label for='happy'>happy</label>
<input id='greatful' type='checkbox' /><label for='greatful'>greatful</label>
<input id='smart' type='checkbox' /><label for='smart'>smart</label>
</div>
</div>
</body>
</html>
I'm probably being very stupid here...
I have two JavaScript functions that are practically identical except each one refers to a different element.
The idea is to show and hide a toast/notification when the document loads.
For one element (errorexplanationcontainer), it works... For the other (alert), it doesn't...
CODE FOR errorexplanationcontainer (WORKS)
<div id="errorexplanationcontainer" class=""></div>
<script type="text/javascript">
window.onload = function() {
var z = document.getElementById("errorexplanationcontainer")
z.className = "show";
setTimeout(function(){ z.className = z.className.replace("show", ""); }, 3000);
}
</script>
^^ This is copied and pasted from the inspect window within Google Chrome. As you can see, the script ran successfully. We know this because class="" is absent in the source document and has been added by the script (after showing class="show" for 3 seconds).
CODE FOR alert (DOESN'T WORK)
<p id="alert">Invalid Email or password.</p>
<script type="text/javascript">
window.onload = function() {
var y = document.getElementById("alert")
y.className = "show";
setTimeout(function(){ y.className = y.className.replace("show", ""); }, 3000);
}
</script>
^^ No class="" here! The script has not worked...
FULL HTML DOC
<html class="mdl-js"><head>
<title>Dennis' Coffee Hut | CuppaDesk</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/png" href="/assets/favicon-16x16-347e46971826b54de74f354ae410242483f471bb3051a5f948d83af70770dadc.png" sizes="16x16">
<link rel="icon" type="image/png" href="/assets/favicon-32x32-ac516884b2aa2ea870ddfbd0ae383c0dd66ec1a640181174ac7adaba8e7ccd7d.png" sizes="32x32">
<link rel="apple-touch-icon" type="image/x-icon" href="/assets/apple-touch-icon-af3f73bee131a689a15fede0d2d6f7cf9698786524670279ac74cd128ec5dc40.png" sizes="180x180">
<link rel="mask-icon" type="image/x-icon" href="/assets/safari-pinned-tab-4f97411db829aebf4a4796a8f216e788ba4eeddf4d062a0a1efe473ee10fce3b.svg" color="#99cc33">
<link rel="icon" type="image/png" href="/assets/android-chrome-192x192-cb0ced957daf2743c293b898f5e595fcf07fc0842b9d0aeef37c08b8c5f74d42.png" sizes="192x192">
<link rel="manifest" href="/manifest.json">
<meta name="apple-mobile-web-app-title" content="CuppaDesk">
<meta name="application-name" content="CuppaDesk">
<meta name="msapplication-TileColor" content="#99cc33">
<meta name="msapplication-TileImage" content="/assets/mstile-144x144-5de954b6d137b31283af01b9a7645c90440392de2b44ec88949fdba65cca75e7.png">
<meta name="theme-color" content="#99cc33">
<meta name="csrf-param" content="authenticity_token">
<meta name="csrf-token" content="wphb5Z8aebicMl6E2CiCJiNPnQowqP2TVUrXOWclCukQwiX/xrbLf3jBE4YRyyswVMEaPEszTO/7xxl1/iClsw==">
<link rel="stylesheet" media="all" href="/assets/main.self-b06bcba5344c9fc9a5c6491a38f0780f4594d723339bc0543a25138d83fe3de3.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/places.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/scaffolds.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/application.self-f0d704deea029cf000697e2c0181ec173a1b474645466ed843eb5ee7bb215794.css?body=1" data-turbolinks-track="reload">
<script src="/assets/rails-ujs.self-56055fe2ac3f3902deb9d12c17b2d725d432162b48fc443946daf7dfbc96d88a.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/turbolinks.self-1d1fddf91adc38ac2045c51f0a3e05ca97d07d24d15a4dcbf705009106489e69.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/action_cable.self-be3674a79bb9d13d41d259b2c17fad23aef20946dab3603b9d02374ea795005f.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/cable.self-8484513823f404ed0c0f039f75243bfdede7af7919dda65f2e66391252443ce9.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/places.self-877aef30ae1b040ab8a3aba4e3e309a11d7f2612f44dde450b5c157aa5f95c05.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/application.self-eba3cb53a585a0960ade5a8cb94253892706bb20e3f12097a13463b1f12a4528.js?body=1" data-turbolinks-track="reload"></script>
<!-- BEGIN MATERIAL DESIGN LITE -->
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<!-- <link rel="stylesheet" href="/material.min.css"> -->
<script defer="" src="https://code.getmdl.io/1.3.0/material.min.js"></script>
<!-- END MATERIAL DESIGN LITE -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<p id="alert">Invalid Email or password.</p>
<script type="text/javascript">
window.onload = function() {
var y = document.getElementById("alert")
y.className = "show";
setTimeout(function(){ y.className = y.className.replace("show", ""); }, 3000);
}
</script>
<div id="login-container">
<div id="cuppadesk-logo-large"></div>
<div id="card-white">
<h1>Log in</h1>
<div class="dropdown-dots">
<button onclick="dotsDropdown()" class="dropbtn-dots"></button>
<div id="dotsDropdown" class="dropdown-content">
<a href="/users/sign_up">
<div class="dropdown-content-item">Sign up</div>
</a>
<a href="/users/password/new">
<div class="dropdown-content-item">Forgot password</div>
</a>
<a href="/users/confirmation/new">
<div class="dropdown-content-item">Didn't recieve email confirmation</div>
</a>
<a href="/users/unlock/new">
<div class="dropdown-content-item">Didn't receive unlock instructions</div>
</a>
<a href="/users/auth/facebook">
<div class="dropdown-content-item">Log in with
Facebook
</div>
</a>
</div>
</div>
<script>
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function dotsDropdown() {
document.getElementById("dotsDropdown").classList.toggle("show-dots");
}
// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn-dots')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show-dots')) {
openDropdown.classList.remove('show-dots');
}
}
}
}
</script>
<form class="new_user" id="new_user" action="/users/sign_in" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓"><input type="hidden" name="authenticity_token" value="wphb5Z8aebicMl6E2CiCJiNPnQowqP2TVUrXOWclCukQwiX/xrbLf3jBE4YRyyswVMEaPEszTO/7xxl1/iClsw==">
<div id="errorexplanationcontainer" class=""></div>
<script type="text/javascript">
window.onload = function() {
var z = document.getElementById("errorexplanationcontainer")
z.className = "show";
setTimeout(function(){ z.className = z.className.replace("show", ""); }, 3000);
}
</script>
<div class="field-white">
<input autofocus="autofocus" placeholder="Email" type="email" value="" name="user[email]" id="user_email">
</div>
<div class="field-white">
<input autocomplete="off" placeholder="Password" type="password" name="user[password]" id="user_password">
</div>
<div class="checkbox">
<input name="user[remember_me]" type="hidden" value="0"><input class="css-checkbox" type="checkbox" value="1" name="user[remember_me]" id="user_remember_me">
<label class="css-label clr" for="user_remember_me">Remember me</label>
</div>
<script>
// generic tools to help with the custom checkbox
function UTIL() { }
UTIL.prototype.bind_onclick = function(o, f) { // chain object onclick event to preserve prior statements (like jquery bind)
var prev = o.onclick;
if (typeof o.onclick != 'function') o.onclick = f;
else o.onclick = function() { if (prev) { prev(); } f(); };
};
UTIL.prototype.bind_onload = function(f) { // chain window onload event to preserve prior statements (like jquery bind)
var prev = window.onload;
if (typeof window.onload != 'function') window.onload = f;
else window.onload = function() { if (prev) { prev(); } f(); };
};
// generic css class style match functions similar to jquery
UTIL.prototype.trim = function(h) {
return h.replace(/^\s+|\s+$/g,'');
};
UTIL.prototype.sregex = function(n) {
return new RegExp('(?:^|\\s+)' + n + '(?:\\s+|$)');
};
UTIL.prototype.hasClass = function(o, n) {
var r = this.sregex(n);
return r.test(o.className);
};
UTIL.prototype.addClass = function(o, n) {
if (!this.hasClass(o, n))
o.className = this.trim(o.className + ' ' + n);
};
UTIL.prototype.removeClass = function(o, n) {
var r = this.sregex(n);
o.className = o.className.replace(r, '');
o.className = this.trim(o.className);
};
var U = new UTIL();
function getElementsByClassSpecial(node, classname) {
var a = [];
var re = new RegExp('(^| )'+classname+'( |$)');
var els = node.getElementsByTagName("*");
for(var i=0,j=els.length; i<j; i++)
if(re.test(els[i].className))a.push(els[i]);
return a;
}
// specific to customized checkbox
function chk_labels(obj, init) {
var objs = document.getElementsByTagName('LABEL');
for (var i = 0; i < objs.length; i++) {
if (objs[i].htmlFor == obj.id) {
if (!init) { // cycle through each label belonging to checkbox
if (!U.hasClass(objs[i], 'chk')) { // adjust class of label to checked style, set checked
if (obj.type.toLowerCase() == 'radio') {
var radGroup = objs[i].className;
var res = radGroup.split(" ");
var newRes = res[0] + " " + res[1];
var relLabels = getElementsByClassSpecial(document.body,newRes);
for (var r = 0; r < relLabels.length; r++) {
U.removeClass(relLabels[r], 'chk');
U.addClass(relLabels[r], 'clr');
}
U.removeClass(objs[i], 'clr');
U.addClass(objs[i], 'chk');
obj.checked = true;
}
else {
U.removeClass(objs[i], 'clr');
U.addClass(objs[i], 'chk');
obj.checked = true;
}
} else { // adjust class of label to unchecked style, clear checked
U.removeClass(objs[i], 'chk');
U.addClass(objs[i], 'clr');
obj.checked = false;
}
return true;
} else { // initialize on page load
if (obj.checked) { // adjust class of label to checked style
U.removeClass(objs[i], 'clr');
U.addClass(objs[i], 'chk');
} else { // adjust class of label to unchecked style
U.removeClass(objs[i], 'chk');
U.addClass(objs[i], 'clr')
}
}
}
}
}
function chk_events(init) {
var objs = document.getElementsByTagName('INPUT');
if (typeof init == 'undefined') init = false;
else init = init ? true : false;
for(var i = 0; i < objs.length; i++) {
if (objs[i].type.toLowerCase() == 'checkbox' || objs[i].type.toLowerCase() == 'radio' ) {
if (!init) {
U.bind_onclick(objs[i], function() {
chk_labels(this, init); // bind checkbox click event handler
});
}
else chk_labels(objs[i], init); // initialize state of checkbox onload
}
}
}
U.bind_onload(function() { // bind window onload event
chk_events(false); // bind click event handler to all checkboxes
chk_events(true); // initialize
});
</script>
<div class="green-submit">
<input type="submit" name="commit" value="Log in" data-disable-with="Log in">
</div>
</form>
</div>
</div>
</body></html>
Again, I'm probably missing something obvious here... I'm completely new to developing and JavaScript is something I particularly struggle with. I've read through many resources but in my mind, the code still looks correct...
Obviously, I'm wrong... So any help will be greatly appreciated!
Use window.addEventListener instead of overwriting window.onload.
For errorexplanationcontainer,
<div id="errorexplanationcontainer" class=""></div>
<script type="text/javascript">
window.addEventListener("load", function() {
var z = document.getElementById("errorexplanationcontainer");
z.className = "show";
setTimeout(function() {
z.className = z.className.replace("show", "");
}, 3000);
}, false);
</script>
For alert,
<p id="alert">Invalid Email or password.</p>
<script type="text/javascript">
window.addEventListener("load", function() {
var y = document.getElementById("alert")
y.className = "show";
setTimeout(function() {
y.className = y.className.replace("show", "");
}, 3000);
}, false);
</script>
I want to get Audio Length without having to play then pause then play again for getting the audio length/duration?
The function called will be: this.createRangeElement
But for some reason it outputs "NaN", so how would I force the Audio to render?
function get_uai(){ return new uai(); }
function uai(){
var AE = new Audio();
var played = false;
this.src = "";
this.set_src = function(){ AE.src = this.src; AE.load(); }
this.play = function(){
if(played == true){
AE.play();
}else{
AE.src = this.src;
played = true;
AE.play();
}
};
this.pause = function(){
AE.pause();
}
this.stop = function(){
window.aui = undefined;
}
this.createRangeElement = function(){
var min = "0";
AE.load();
var max = AE.duration;
console.log(max);
}
}
// Getting the UAI API
var aud = get_uai();
// Setting the source
aud.src = "http://crossorigin.me/https://s3-us-west-2.amazonaws.com/s.cdpn.io/1715/the_xx_-_intro.mp3";
aud.set_src();
// Creating a range element
aud.createRangeElement();
// Playing the sound
//aud.play()
<html>
<head>
<title>Music Player</title>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
</head>
<body>
<em class="fa fa-pause" onclick="aud.pause();"></em>
<em class="fa fa-play" onclick="aud.play();"></em>
</body>
</html>
You can use oncanplaythrough event to detect if audio duration data is available.
function get_uai() {
return new uai();
}
function uai() {
var AE = new Audio();
var played = false;
this.src = "";
this.set_src = function() {
AE.src = this.src;
AE.load();
}
this.play = function() {
if (played == true) {
AE.play();
} else {
AE.src = this.src;
played = true;
AE.play();
}
};
this.pause = function() {
AE.pause();
}
this.stop = function() {
window.aui = undefined;
}
this.createRangeElement = function() {
var min = "0";
AE.load();
AE.oncanplaythrough = function() {
var max = AE.duration;
console.log(max);
}
}
}
var aud = get_uai();
aud.src = "http://crossorigin.me/https://s3-us-west-2.amazonaws.com/s.cdpn.io/1715/the_xx_-_intro.mp3";
aud.set_src();
aud.createRangeElement();
<html>
<head>
<title>Music Player</title>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
</head>
<body>
<em class="fa fa-pause" onclick="aud.pause();"></em>
<em class="fa fa-play" onclick="aud.play();"></em>
</body>
</html>