Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I work for my father's landscaping business and I want to make a very simple calculator for how much I am owed for the work I have provided. I have something made up for this purpose but I honestly don't know what I have done wrong, can someone help me fix it, I'm sure its something really simple that I Just cant find.
<!DOCTYPE html>
<html>
<head>
<!-- ALL OF THE INFO GOES HERE -->
<script>
var xy = 3; //put in number of yards here
var xb = 1; //put in number of times bluffs done here
var xn = 2; //put in number of times newbern done here
var y = 5;
var b = 25;
var n = 15;
var pay = y * xy + b * xb + n * xn;
getElementById("Display").innerHTML = pay;
</script>
<!-- ALL OF THE INFO GOES HERE -->
<title> Pay calculater </title>
<body>
<p id="Display"></p>
</body>
</html>
Your code had 2 issues:
"NullReference: reference not found" If you place the <script></script> tag in the <head>...</head> you need a eventListener to check if the DOM is loaded. You can do this with a eventListener like load, DOMContentLoaded.
"Typo" You forgot document. when calling document.getElementById("Display")
<!DOCTYPE html>
<html>
<head>
<!-- ALL OF THE INFO GOES HERE -->
<title> Pay calculater </title>
<script>
const setup = () => {
let xy = 3; //put in number of yards here
let xb = 1; //put in number of times bluffs done here
let xn = 2; //put in number of times newbern done here
let y = 5;
let b = 25;
let n = 15;
const pay = y * xy + b * xb + n * xn;
document.getElementById("Display").innerHTML = pay;
}
window.addEventListener('load', setup);
</script>
</head>
<!-- ALL OF THE INFO GOES HERE -->
<body>
<p id="Display"></p>
</body>
</html>
Your script is running before the entire page is loaded. When it runs, there is no "Display" element to update. You need to update that after it exists. Your browser console will have good error messages as to what's going wrong.
Prefix the getElementById with document. since it is a method on the document object.
document.getElementById("Display");
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
for this task i have to get 3 photos and make a button to cycle through the photos new i need to make it so that i can use photos from my file
.Every little helps :D
<!DOCTYPE html>
<html>
<body>
<img id="light" src="Red.png">
<script>
var list= ['Green.png', 'Yellow.png', 'Red.png'];
var i = 0;
function lightsCycle() {
i = i + 1;
i = i % list.length;
var light = document.getElementById("light").src = list[i];
}
</script>
<button type = "button" onclick="lightsCycle()">Next Light</button>
</body>
</html>
UPDATE: I have modified my code to attempt one of the answers given here, but I am still having trouble:
<!DOCTYPE html>
<html>
<body>
<img id="light" src="Red.png">
<script>
var list= ['https://cdn2.iconfinder.com/data/icons/crystalproject/crystal_project_256x256/apps/daemons.png',
'https://img.clipartfox.com/837fed127e3383c2a61cf08f76a65081_pics-for-stop-light-yellow-clipart-traffic-light-yellow_641-880.png',
'http://previews.123rf.com/images/blojfo/blojfo1003/blojfo100300021/6559248-Traffic-light-with-red-light-Stock-Photo.jpg'];
var i = 0;
function lightsCycle() {
i = (i < list.length - 1) ? ++i : 0;
document.getElementById("light").src = list[i];
}
</script>
<img id="light" src="https://cdn2.iconfinder.com/data/icons/crystalproject/crystal_project_256x256/apps/daemons.png">
<button type = "button" onclick="lightsCycle()">Next Light</button>
</body>
</html>
In your function, you are incrementing i and then immediately throwing that value away on the next line where you are setting i to the modulo of i and the length of your array. That line is not needed.
You also need to check to see if i is at the highest index number that the array supports and, if so, reset it to 0.
Next, the line:
var light = document.getElementById("light").src = list[i];
unnecessarily declares a variable called light since you never use it anywhere.
Lastly, don't use HTML attributes to hook up event handlers (onclick, onmouseover, etc.) as they:
create spaghetti code (HTML and JavaScript mixed on the same line) that is difficult to read and maintain.
create globally scoped wrapper functions around your attribute's value that alter the this binding and can cause your function to not work correctly.
don't follow W3C standards for event handling.
// Put the correct relative paths to your images back into the array. Here, I'm substituting
// online images so that you can see the code working properly.
var list= ['https://cdn2.iconfinder.com/data/icons/crystalproject/crystal_project_256x256/apps/daemons.png',
'https://img.clipartfox.com/837fed127e3383c2a61cf08f76a65081_pics-for-stop-light-yellow-clipart-traffic-light-yellow_641-880.png',
'http://previews.123rf.com/images/blojfo/blojfo1003/blojfo100300021/6559248-Traffic-light-with-red-light-Stock-Photo.jpg'];
var i = 0;
// Only scan the document one time to get a reference to the image element.
// It's a waste of resources to do it every time the button is clicked
var img = document.getElementById("light");
var btn = document.getElementById("btn")
// Don't use HTML attributes to hook up event handlers (onclick, onmouseover, etc.)
btn.addEventListener("click", lightsCycle);
function lightsCycle() {
// If i is less than the max index, increment it, otherwise set it to zero
i = (i < list.length - 1) ? ++i : 0;
// Set the source of the image element to the next array value
img.src = list[i];
}
img { width:50px; }
<img id="light" src="https://cdn2.iconfinder.com/data/icons/crystalproject/crystal_project_256x256/apps/daemons.png">
<button type="button" id="btn">Next Light</button>
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
So the red traffic light shows up and then when the next light button is pressed the light doesn't change and I can't for the life of me figure out why. I would appreciate any help. Here's the code:
<!DOCTYPE html>
<html>
<body>
<img id="thestartlight" src="file:\\\C:\Users\Sony\Desktop\Amul's USB\IT\it test\traffic-light-red.jpg">
<button type="button" onclick="nextLightClick()">Next Light</button>
<script>
var list = [
"file:\\\C:\Users\Sony\Desktop\Amul's USB\IT\it test\traffic-light-red.jpg.html"
"file:\\\C:\Users\Sony\Desktop\Amul's USB\IT\it test\traffic-light-amber.jpg",
"file:\\\C:\Users\Sony\Desktop\Amul's USB\IT\it test\traffic-light-green.jpg",
"file:\\\C:\Users\Sony\Desktop\Amul's USB\IT\it test\traffic-light-red.jpg"
];
var index = 0;
var lightsLen = lights.length;
function nextLightClick() {
index++;
if (index == lightsLen)
index = 0;
var image = document.getElementById('thestartlight');
image.src = lights[index];
}
</script>
</body>
</html>
There are 3 problems.
1) it's list have to be lights
2) better put images to images/lights/ folder in relative to Your code folder.
3) html file cannot be shown in image tag
Here is the fix:
var lights = [
"images/lights/amber.jpg",
"images/lights/green.jpg",
"images/lights/red.jpg"
];
var index = 0;
var lightsLen = lights.length;
It's a typo..
var list = [ ...
should be
var lights [ ...
You named your array list, but you are seeking the images from lights.
You also need to remove the .html file from the array.
var image = document.getElementById('thestartlight');
var lights = [
"http://archive.nassaucountyny.gov/agencies/TPVA/Images/RedLight-2_145x193.jpg",
"http://www.clker.com/cliparts/2/1/1/6/N/W/amber-traffic-light.svg",
"http://www.clker.com/cliparts/6/e/9/d/11949849761176136192traffic_light_green_dan__01.svg"
];
var index = 0;
var lightsLen = lights.length;
function nextLightClick() {
index++;
if (index == lightsLen){
index = 0;
}
image.src = lights[index];
}
img {width:50px;}
<img id="thestartlight" src="http://archive.nassaucountyny.gov/agencies/TPVA/Images/RedLight-2_145x193.jpg">
<button type="button" onclick="nextLightClick()">Next Light</button>
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am a newbie at JavaScript. So, I was trying to solve an exercise - announcing movie showtimes. I have already checked what's wrong with it, but i found nothing. When I open the index.html file nothing happens. Here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Cinema</title>
<script src="cinema.js"></script>
</head>
<body>
</body>
</html>
cinema.js
var movie1={
name: "Star Wars: Force Awakens",
showtimes: ["3:00pm","7:00pm","11:00pm"],
genre: "Cult Classic",
rating: 2
};
var movie2={
name: "Doctor Strange",
showtimes: ["5:00pm","9:00pm"],
genre: "Action",
rating: 5
};
window.onload = function (){
var nextShowing=getNextShowing(movie1);
alert(nextShowing);
nextShowing=getNextShowing(movie2);
alert(nextShowing);
}
function getNextShowing(movie){
var now=new Date().getTime();
for(var i=0;i<movie.showtimes.length;i++){
var showtime = getTimeFromString(movie.showtimes[i]);
if((showtime-now)>0) {
return "Next showing of "+movie.name+" is "+movie.showtimes[i];
}
}
return null;
}
function getTimeFromString(timeString){
var theTime = new Date();
var time = timeString.match(/(\d+)(?::(\d\d))?\s*(p?) /);
theTime.setHours( parselnt(time[1]) +(time[3] ? 12 : 0) );
theTime.setMinutes( parseInt(time[2])|| 0 );
return theTime.getTime();
}
Where might be a problem?
UPD:
function getNextShowing(movie){
var now=new Date().getTime();
for(var i=0;i<movie.showtimes.length;i++){
var showtime = getTimeFromString(movie.showtimes[i]);
if((showtime-now)>0) {
return "Next showing of "+movie.name+" is "+movie.showtimes[i];
}
}
return null;
}
function getTimeFromString(timeString){
var theTime = new Date();
var time = timeString.match(/(\d+)(?::(\d\d))?\s*(p?) /);
theTime.setHours( parseInt(time[1])+(time[3] ?12 : 0) );
theTime.setMinutes(parseInt(time[2])|| 0 );
return theTime.getTime();
}
still nothing happens
parseInt function name was not correct. Please replace parselnt with parseInt
Match pattern was not correct. Here is the updated one
var time = timeString.match(/(\d+)(?::)(\d+)(am|pm)/);
You have an error in your spelling of parseInt (you have it written as parselnt).
As you continue to learn Javascript, one of your first ports of call for debugging should be to open your browser's developer tools/console.
For example, in Google Chrome you can do this by pressing Ctrl + Shift + i.
The console should provide detail on any runtime errors that your javascript encounters, which will be your first step to diagnosing your issues.
I can see a typo here theTime.setHours( parselnt(time[1]) +(time[3] ? 12 : 0) ); It should be parseInt.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I am attempting to use the onclick on the button to call the function complete which should create a div with the below mentioned attributes. However, when I tried to run it, I saw no output display. I have tried a bunch of things but am currently unsure. Any help would be much appreciated
<!DOCTYPE html>
<html>
<button id ="button1" type="button" onclick="complete()">Run</button>
<script>
function complete(){
var x= Math.floor(Math.random()*501)
var y=Math.floor(Math.random()*501)
var divx = document.createElement("div");
divx.style.position = "fixed";
divx.style.bottom = (150+x).toString();
divx.style.right = (900+y).toString();
divx.style.background="green";
divx.style.width = "10px";
divx.style.height = "10px";
divx.style.border = "1px solid #000";
document.body.appendChild(div);
}
</script>
</html>
document.body.appendChild(div); should be document.body.appendChild(divx); Because div is undefined
<!DOCTYPE html>
<html>
<body>
<button id="button1" type="button" onclick="complete()">Run</button>
<script>
function complete() {
var x = Math.floor(Math.random() * 501)
var y = Math.floor(Math.random() * 501)
var divx = document.createElement("div");
divx.style.position = "fixed";
divx.style.bottom = (150 + x).toString();
divx.style.right = (900 + y).toString();
divx.style.background = "green";
divx.style.width = "10px";
divx.style.height = "10px";
divx.style.border = "1px solid #000";
document.body.appendChild(divx);
}
</script>
</body>
</html>
The error :
document.body.appendChild(div); should be document.body.appendChild(divx);
Suggestion :
While not incorrect, you shouldn't use onclick="complete()" in your HTML. It's much better to attach an event listener using addEventListener("click", complete, false) in your JS code instead.
Improved code :
function complete(){
var x= Math.floor(Math.random()*501)
var y=Math.floor(Math.random()*501)
var divx = document.createElement("div");
divx.style.position = "fixed";
divx.style.bottom = (150+x).toString();
divx.style.right = (900+y).toString();
divx.style.background="green";
divx.style.width = "10px";
divx.style.height = "10px";
divx.style.border = "1px solid #000";
document.body.appendChild(divx);
}
document.getElementById('button1').addEventListener("click", complete, false);
<button id ="button1" type="button">Run</button>
(see also this Fiddle)
Your code works fine, you're missing just to add x after div in :
document.body.appendChild(div);
Should be :
document.body.appendChild(divx);
Because variable div is not defined, also you should put your code inside <body> tag for the valid HTML code.
Hope this helps.
<!DOCTYPE html>
<html>
<body>
<button id ="button1" type="button" onclick="complete()">Run</button>
<script>
function complete(){
var x= Math.floor(Math.random()*501)
var y=Math.floor(Math.random()*501)
var divx = document.createElement("div");
divx.style.position = "fixed";
divx.style.bottom = (150+x).toString();
divx.style.right = (900+y).toString();
divx.style.background="green";
divx.style.width = "10px";
divx.style.height = "10px";
divx.style.border = "1px solid #000";
document.body.appendChild(divx);
}
</script>
</body>
</html>
Your line document.body.appendChild(div); uses an undefined variable div, you named your div xdiv instead, so use that as parameter.
Remember that most browsers support a console, usually accessible through F12, which shows error messages triggered by JavaScript. In your case it shows:
test.html:16 Uncaught ReferenceError: div is not defined
It's a great idea to check that error log when something misbehaves, often it tells exactly what's wrong including the line number.
You also have to append the unit as a string when setting the two offsets (bottom and right), probably px. For example:
divx.style.bottom = (150+x).toString() + "px";
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
So I'm new to JavaScript and I just wrote a simple program; however, I'm not sure why it isn't working. I have shown both the HTML and the Javascript code below.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<h1>Rectangular Prism Calculator</h1>
<h2 id="hLength">Length: N/A</h2>
<h2 id="hWidth">Width: N/A</h2>
<h2 id="hDepth">Depth: N/A</h2>
<h2 id="hSurfaceArea">Surface Area: N/A</h2>
<h2 id="hVolume">Volume: N/A</h2>
<script src="main.js"></script>
</body>
</html>
JavaScript:
var length;
var width;
var depth;
length = 20;
width = 10;
depth = 15;
// Write length to document
var wLength = document.getElementbyId('hLength');
wLength.textContent = "Length: " + length;
// Write width to document
var wWidth = document.getElementbyId('hWidth');
wWidth.textContent = "Width: " + width;
// Write depth to document
var wDepth = document.getElementbyId('hDepth');
wDepth.textContent = "Depth: " + depth;
// Calculate surface area
var calculateSurfaceArea = function(l, w, d) {
var surfaceArea = 2*l*d + 2*l*w + 2*w*d;
return surfaceArea;
}
// Write surface area to document
var wSurfaceArea = document.getElementById('hSurfaceArea');
wSurfaceArea.textContent = "Surface Area: " + calculateSurfaceArea(length, width, depth);
// Calculate volume
var calculateVolume = function(l, w, d) {
var volume = l*w*d;
return volume;
}
// Write volume to document
var wVolume = document.getElementById('hVolume');
wVolume.textContent = "Volume: " + calculateVolume(length, width, depth);
Just to verify, I have made sure that the name of the HTML document is 'index.html' and the JavaScript document is named 'main.js'
Many Thanks,
Malleekk
You have a typo in your code:
getElementbyId
should be:
getElementById
Working Demo of your corrected code
You should learn how to debug your Javascript code. Get along with Firebug in Firefox / Developer Tools in Chrome.
Javascript is case sensitive and usually the names of functions has camel case style, so this is wrong:
... document.getElementbyId ...
Replace with
... document.getElementById ...