Simple Javascript Program Not Working [closed] - javascript

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 ...

Related

Uncaught ReferenceError: html is not defined [closed]

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 days ago.
This post was edited and submitted for review 2 days ago.
Improve this question
I am just using Javascript here, to make a login page that using captcha. But it throw an error when I tried to produce it. It was saying that html is not defined, I already tried to check the code, but still could not figure it out what went wrong here.
here is the Javascript code that I think the problem is:
(function () {
const fonts =['cursive', 'sans-serif', 'serif', 'monospace'];
let captchaValue = "";
function generateCaptcha(){
let value = btoa(Math.random()*100000000);
value = value.substr(0,5+Math.random()*5);
captchaValue= value;
}
function setCaptcha() {
captchaValue.split("").map((char)=> {
const rotate = -20 + Math.trunc(Math.random()*30);
const font = Math.trunc(Math.random()*fonts.length);
return `<span
style="
transform:rotate(${rotate}deg);
font-family: ${fonts[font]};
"
>
${char}
</span>`;
}).join("");
document.querySelector(".login-form .captcha .preview").innerHTML = html;
}
function initCaptcha(){
document.querySelector(".login-form .captcha .captcha-refresh").addEventListener('click', function(){
generateCaptcha();
setCaptcha();
});
generateCaptcha();
setCaptcha();
}
initCaptcha();
})();
Please helping me to solve this problem, since I am a beginner so I really got no idea when I am getting this error.
Your problem seems to be in this line of code:
document.querySelector(".login-form .captcha .preview").innerHTML = html;
you are setting the innerHTML of the ".preview" element to html which you didn't define anywhere in your code.
I'm not sure of what you want to set it to, but this is merely a guess, you can change the setCaptcha to the following:
function setCaptcha() {
let html = captchaValue.split("").map((char)=> {
const rotate = -20 + Math.trunc(Math.random()*30);
const font = Math.trunc(Math.random()*fonts.length);
return `<span
style="
transform:rotate(${rotate}deg);
font-family: ${fonts[font]};
"
>
${char}
</span>`;
}).join("");
document.querySelector(".login-form .captcha .preview").innerHTML = html;
}

pay calculator but nothing happens [closed]

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");

javascript and html traffic light not working [closed]

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>

Can a javascript file call a function defined in the main html file? [closed]

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
I can't seem to get this to work. I am including a javascript file with functions in it, but one of the functions in the file I want to be defined inside the main HTML file, not the javascript file. This isn't working however.
Here's what I want:
//testFile.js
$(function() {
$(window).scroll(function() {
var Scroll = $(window).scrollTop();
var Width = $(window).width();
var Height = $(window).height();
var Offset;
doParallax();
});
function Parallax(Obj, /*OffX, OffY,*/ ModifierX, ModifierY, Wait) {
var ScrollT = $(window).scrollTop();
var ScrollL = $(window).scrollLeft();
var OffsetY = ScrollT - $(Obj).data("InitialTopOffset");
var OffsetX = ScrollL - $(Obj).data("InitialLeftOffset");
var SpeedX = OffsetX*ModifierX + XOff;
var SpeedY = OffsetY*ModifierY + YOff;
if (Wait) {
if (ScrollT >= $(Obj).data("InitialTopOffset")) {
$(Obj).stop(true, false).css( "background-position", (ScrollL+SpeedX) + "px " + (-OffsetY-SpeedY) + "px", 50, "linear");
}
}
else {
$(Obj).stop(true, false).css( "background-position", (ScrollL+SpeedX) + "px " + (-OffsetY-SpeedY) + "px", 50, "linear");
}
}
});
//
//main HTML file
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function doParallax() {
XOff = ( $(window).width() - ( $(window).width()*0.9 ) ) / 2;
Parallax(".parallax3", 0, -0.55, true);
}
</script>
<script src="testFile.js"></script>
</head>
<body>
...
</body>
</html>
I haven't been able to find anything from doing google searches or from searching on Stack Exchange. But assuming that it isn't working means that I can't do this, but is there a way to achieve the desired result?
EDIT: Actual code examples
This is invalid:
<script src="testFile.js">
function somethingElse() {
alert("Called");
}
</script>
A script tag either references a script or contains a script. Not both. Separate them into their own tags:
<script src="testFile.js"></script>
<script>
function somethingElse() {
alert("Called");
}
</script>
(Of course, this is ignoring the fact that the contrived example never calls doSomething(), but I assume that's just an oversight in the example.)
Note also that there may be a scope issue depending on when you call this function. If doSomething() is invoked before somethingElse() is in scope, that could be a problem. You may be able to hoist it to the top of the current scope by defining it like this though:
var somethingElse = function() {
alert("Called");
}
Not sure if that's even an issue here though, since the code in the question doesn't actually invoke any functions.
Edit: Since the question has drastically changed...
In a comment above you mention the problem:
The console is actually now saying that Parallax() is not defined.
This is because that function exists only within the scope of the function you're using in the document.ready handler. To simplify:
$(function () {
// anything created here only exists here
});
// so you can't call it here
If you have functions which need to be invoked outside that scope, define them outside of that scope:
$(function () {
// perform document ready handler actions here
});
var Parallax = function() {
//...
}
var doParallax = function() {
//...
}

How to create and style div on JavaScript [closed]

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";

Categories