I was wondering what's wrong with my program. Am i having a syntax error or am i missing something in my build in array sort?. I'm pretty sure the problem lies within the "for" loop but i cant seem to find it. Some suggestion or help would be great.
<HTML>
<!Foundation Page for building our Javascript programs>
<HEAD>
<TITLE>The Foundation Page </TITLE>
<SCRIPT LANGUAGE = "JavaScript">
function leaderboard()
{
var temp1;
var temp2;
var temp3;
var temp4;
var temp5;
temp1 = 10
temp2 = 20
temp3 = 30
temp4 = 40
temp5 = 50
var leader = new Array(5);
leader[0] = temp1;
leader[1] = temp2;
leader[2] = temp3;
leader[3] = temp4;
leader[4] = temp5;
leader.sort(function(a,b){return b-a});
var myContent = '';
for (var d=0;d<5;d++)
{
myContent += "score: " + leader[d] + "<BR>";
}
document.getElementById("leaderboard").innerHTML = myContent;
}
</SCRIPT>
<HEAD>
<BODY>
<BODY BGCOLOUR = "WHITE">
<H2>The Foundation Page </H2>
<HR>
<SCRIPT LANGUAGE = "Javascript"> leaderboard() </SCRIPT>
</BODY>
</HTML>
You are trying to write the o/p to an element with id leaderboard which is not present in the page. Which is giving an error Uncaught TypeError: Cannot set property 'innerHTML' of null - it is not a syntax error.
So just create an element with the id leaderboard as shown below
<HTML>
<!Foundation Page for building our Javascript programs>
<HEAD>
<TITLE>The Foundation Page </TITLE>
<SCRIPT LANGUAGE = "JavaScript">
function leaderboard()
{
var temp1;
var temp2;
var temp3;
var temp4;
var temp5;
temp1 = 10
temp2 = 20
temp3 = 30
temp4 = 40
temp5 = 50
var leader = new Array(5);
leader[0] = temp1;
leader[1] = temp2;
leader[2] = temp3;
leader[3] = temp4;
leader[4] = temp5;
leader.sort(function(a,b){return b-a});
var myContent = '';
for (var d=0;d<5;d++)
{
myContent += "score: " + leader[d] + "<BR>";
}
document.getElementById("leaderboard").innerHTML = myContent;
}
</SCRIPT>
<HEAD>
<BODY>
<BODY BGCOLOUR = "WHITE">
<H2>The Foundation Page </H2>
<HR>
<div id="leaderboard"></div>
<SCRIPT LANGUAGE = "Javascript"> leaderboard() </SCRIPT>
</BODY>
</HTML>
Demo: Fiddle
Related
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 can't find the problem with this code and I've been having way too much trouble with it tonight, can anyone help me out?
<html>
<script type="text/javascript">
var image = new Array ();
image[0] = "header1.png";
image[1] = "header2.png";
image[2] = "header3.png";
image[3] = "header4.png";
var size = image.length
var x = Math.floor(size*Math.random())
var backgroundImageFile = image[x];
var backgroundImageUrl = "url('" + backgroundImageFile + "')";
$('#header-image').css('background-image', 'backgroundImageUrl');
function op()
{
document.getElementById('header-image').innerHTML=backgroundImageUrl;
}
</script>
<body onload="op();">
<img src="backgroundImageFile">
</body>
</html>
You may try for this:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var image = new Array ();
image[0] = "https://www.w3schools.com/angular/pic_angular.jpg";
image[1] = "https://www.w3schools.com/images/colorpicker.gif";
image[2] = "https://www.w3schools.com/angular/pic_angular.jpg";
image[3] = "https://www.gstatic.com/images/branding/googlelogo/2x/googlelogo_dark_color_84x28dp.png";
var size = image.length
var x = Math.floor(size*Math.random());
var backgroundImageFile = image[x];
$('#imageId')[0].setAttribute('src',backgroundImageFile);
});
</script>
</head>
<body>
//displays circle with dimensions
image here:
<img src="backgroundImageFile" id="imageId">
</body>
</html>
Please find the solution: I think you are looking for same.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<script type="text/javascript">
var image = new Array ();
image[0] = "header1.png";
image[1] = "header2.png";
image[2] = "header3.png";
image[3] = "header4.png";
var size = image.length
var x = Math.floor(size*Math.random())
var backgroundImageFile = image[x];
var backgroundImageUrl = "url('" + backgroundImageFile + "')";
$('#header-image').css('background-image', 'backgroundImageUrl');
function op()
{
document.getElementById('header-image').innerHTML=backgroundImageUrl;
}
</script>
<body onload="op();">
<img src="backgroundImageFile">
<div id="header-image"></div>
</body>
</html>
I'm working on a project where I need to manipulate time speed forward and backward. This module seems like what I need but I can't get it working:
https://github.com/mattbradley/warpjs/blob/master/README.md
Any help appreciated
<html>
<head>
</head>
<body>
<script src="jquery.min.js"></script>
<script src="warp.js"></script>
<div id="container"></div>
<span id="info"></span><br>
<span id="time"></span>
<span id="time2"></span>
<script>
setInterval(function() {
var now = new Date;
now = Date.warp.clock(true);
//now = Date.warp.speed(2); // DOESNT WORK?
var dateD = [now.getMonth() + 1,now.getDate(),now.getFullYear()];
var dateE = [now.getHours(),now.getMinutes(),now.getSeconds()];
var MDY = dateD.join("/");
var HMS = dateE.join(":");
time.innerHTML = (MDY);
time2.innerHTML = (HMS);
}, 20);
</script>
</body>
</html>
The wrap is a static method, it doesn't return any value(undefined is returned)
setInterval(function() {
Date.warp.speed(3);
var now = new Date;
var dateD = [now.getMonth() + 1, now.getDate(), now.getFullYear()];
var dateE = [now.getHours(), now.getMinutes(), now.getSeconds()];
var MDY = dateD.join("/");
var HMS = dateE.join(":");
time.innerHTML = (MDY);
time2.innerHTML = (HMS);
}, 1000);
Demo: Fiddle
I included the javascript links above the <head>
I'm wondering about doing this in like one line.
I try this in a basic .html file and nothing shows up, no alert.
I'm probably missing something trivial.
Wait, probably just have to put the dollar signs haha
<!DOCTYPE HTML>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script language="JavaScript" type="text/javascript"></script>
<head>
<style>
</style>
</head>
<body>
<script>
function compute(){
var h = 1595;
var k = 77;
var r = 309;
var rSquared = Math.pow(r,2);
var x = 686;
var group = x - h;
var groupSquared = Math.pow(group,2);
var toBeSquareRoot = rSquared - groupSquared;
var y_neg = 77 + Math.sqrt(toBeSquareRoot);
var y_pos = 77 - Math.sqrt(toBeSquareRoot);
alert(y_pos);
alert(y_neg);
alert(hey);
}
compute();
</script>
</body>
Just a few syntax errors. Ditch the single quotes on the alerts. Also, you were missing the Math. before the pow() method call.
<script>
function compute(){
var h = 1595;
var k = 77;
var r = 309;
var rSquared = Math.pow(r,2);
var x = 686;
var group = x - h;
var groupSquared = Math.pow(group,2);
var toBeSquareRoot = rSquared - groupSquared;
var y_neg = 77 + Math.sqrt(toBeSquareRoot);
var y_pos = 77 - Math.sqrt(toBeSquareRoot);
alert(y_pos);
alert(y_neg);
alert('hey');
}
compute();
</script>
Your code is returning NaN. This is probably due to a negative number being passed into the .sqrt() method. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sqrt
I am new to JavaScript, and I'm trying to make a web page where if I have the same open and closing hours for 5 days a week, it will output them on the same line. For example, the hours for Monday - Friday are the same in my example so it would print out:
Monday - Friday: 6:00AM - 2:00PM
Saturday 8:00AM - 1:00PM
Sunday Closed (Without the hyphen)
When I run this in my browser, I get a blank page. Here is my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<script>
var MondayOpen = "6:00AM - ";
var MondayClose = "2:00PM";
var TuesdayOpen = "6:00AM - ";
var TuesdayClose = "2:00PM";
var WednesdayOpen = "6:00AM - ";
var WednesdayClose = "2:00PM";
var ThursdayOpen = "6:00AM - ";
var ThursdayClose = "2:00PM";
var FridayOpen = "6:00AM - ";
var FridayClose = "2:00PM";
var SaturdayOpen = "8:00AM - ";
var SaturdayClose = "1:00PM";
var SundayOpen = "Closed";
var SundayClose = "";
var dateArray = new Array(MondayOpen, MondayClose, TuesdayOpen, TuesdayClose, WednesdayOpen, WednesdayClose, ThursdayOpen, ThursdayClose,FridayOpen, FridayClose, SaturdayOpen, SaturdayClose, SundayOpen, SundayClose);
function outputDate(){
for(int i = 0; i<dateArray.length; i++){
var current;
//Puts Open and Close time into 1 string
dateArray[i] + dateArray[i+1] = current;
//Compare the two strings
if(current.substring(0,15) == current.substring(0,15) +2)
}
$("#hours").html(<b> current <b/>);
}
var getHours = document.getElementById('hours').innterHTML = current;
}
</script>
<div id= "hours" style="font-size:10px; color:#fff;">
</div>
What am I missing here? Any help would be appreciated.
There are several mistakes here. Just to name a few:
You put int instead of var here:
for(var i = 0; i<dateArray.length; i++){
You put String instead of var here:
var curr;
You're assigning a variable to an expression? Did you mean to do it the other way around?
//Puts Open and Close time into 1 string
curr = dateArray[i] + dateArray[i+1];
You have a closing brace after your if statement...
//Compare the two strings
if(current.substring(0,15) == current.substring(0,15) +2)
{
You type innterHTML instead of innerHTML and try to do multiple assignments:
var getHours = current;
document.getElementById('hours').innerHTML = current;
You forget to enclose this in quotes:
$("#hours").html("<b> current <b/>");
EVEN after fixing all these syntax errors I get a blank page. Consider rewriting it from scratch.
In Javascript you don't need to declare String theString = "This is a string".
Just write var stringName = "This is my string."
You might want to take a step back and master JavaScript and HTML. There are many free resources available. Just to be brief, why not try Code Academy or W3 schools. That being said, here's enough of a fix to display your variables.
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
</head>
<body>
<div id="hours"></div>
</body>
<script type="text/javascript">
var MondayOpen = "6:00AM - ";
var MondayClose = "2:00PM";
var TuesdayOpen = "6:00AM - ";
var TuesdayClose = "2:00PM";
var WednesdayOpen = "6:00AM - ";
var WednesdayClose = "2:00PM";
var ThursdayOpen = "6:00AM - ";
var ThursdayClose = "2:00PM";
var FridayOpen = "6:00AM - ";
var FridayClose = "2:00PM";
var SaturdayOpen = "8:00AM - ";
var SaturdayClose = "1:00PM";
var SundayOpen = "Closed";
var SundayClose = "";
var dateArray = new Array(MondayOpen, MondayClose, TuesdayOpen, TuesdayClose, WednesdayOpen, WednesdayClose, ThursdayOpen, ThursdayClose,FridayOpen, FridayClose, SaturdayOpen, SaturdayClose, SundayOpen, SundayClose);
function outputDate(){
var printOutResults;
for(i = 0; i<dateArray.length; i++) {
var current;
//Puts Open and Close time into 1 string
current = dateArray[i] + dateArray[i+1];
printOutResults += current;
//Compare the two
if(current.substring(0,15) == current.substring(0,15) +2){
$("#hours").html(current);
}
}
$("#hours").html(printOutResults);
}
outputDate();
</script>