How to create and style div on JavaScript [closed] - javascript

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

Related

my createElement(div) is not appearing on my screen, is there something wrong in my javascript code? [duplicate]

Javascript createElement() is not working in Chrome but it works in IE and Firefox fine. Why?
It's working perfectly, use this code:
var catDiv = document.createElement("div");
catDiv.innerHTML = "Test";
document.body.appendChild(catDiv);
Another working example (if you have an element with Id = myTableBody in your HTML)
var appendingTo = document.getElementById("myTableBody");
var tr = document.createElement("tr");
tr.setAttribute("name", "i");
appendingTo.appendChild(tr);
var name = document.createElement("Div" );
will work. And later you can add the attributes like
name.colSpan="2";
document.body.appendChild(name);
Note: don't try to use angular brackets like createElement("<div />").
It will not work in Chrome.
Edit: syntax issue in above code fixed. there should be a dot instead of comma.
Beacause your code is messed up, there's nothing wrong with "createElement":
<html>
<head>
<meta charset = "utf-8">
<title></title>
<script>
window.onload = function () {
for (var i = 0; i < 100; i ++) {
var div = document.createElement ("div");
div.style.border = "1px solid black";
div.style.margin = "20px";
div.style.padding = "10px";
document.body.appendChild (div);
}
}
</script>
<style></style>
</head>
<body></body>
</html>
So I also couldn't get createElement() to work in chrome. After reading Caio's post and testing the code provided I figured out what I was doing wrong.
On w3schools.com the examples they provide always use the tag name in all caps ex. createElement("DIV"), which is the way I was using it and with poor results.
After changing from "DIV" to "div" in my own code it instantly worked.
Thanks Caio.

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 "onclick" attribute on button automatically running [closed]

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 7 years ago.
Improve this question
I'm using a for loop to dynamically name and fill buttons (with text and with code). One thing I had a problem with was dynamically allocating onclick functionality to the buttons, but I seemed to have fixed it with:
document.getElementById(ID_HERE).onclick = FUNCTION();
The problem is when I add this code, the buttons trigger themselves on the load of the webpage instead of the click.
I put the full code below for both the HTML and the Javascript.
JavaScript:
var routes = "";
var elem = "";
var locationid = "50017"
var currentRoute = "the Londinium Way"
function possibleRoutes(){
document.write("<div id='container'>");
document.write("<center><b> Welcome to ");
document.write(currentRoute);
document.write("!<br>")
document.write("Your options are:");
for (i = 0; i<routes.length;i++){
var options = routes[i];
var temp = "button" + i
document.write("<button id='button'></button>");
document.getElementById('button').id = temp;
document.getElementById(temp).innerHTML=routes[i][0];
document.getElementById(temp).onclick = getRoutes(routes[i][1]);
console.log(routes[i]);
console.log(routes[i][1]);
}
document.write("<br><img src='http://192.168.1.151:8000/map.jpg'>");
document.write("</b></center></div>");
}
function getRoutes(locationid) {
var routesURL = 'http://cors.io/?u=http://orbis.stanford.edu/api/sites/' + locationid;
$.ajax({
type: 'GET',
url: routesURL
}).done(function(data) {
console.dir(data);
dataParsed = JSON.parse(data);
currentRoute = dataParsed.prefname;
routes = dataParsed.routes;
console.log(routes);
clearScreen();
});
}
function clearScreen(){
if (document.contains(document.getElementById("container"))){
elem = document.getElementById("container");
elem.remove();
}
possibleRoutes();
}
HTML:
<html>
<head>
<title> Londinium Trail </title>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="http://192.168.1.151:8000/scripts/game.js"> </script>
</head>
<body>
<script>
getRoutes(50017);
</script>
</body>
</html>
JAVASCRIPT
Try to use addEventListener instead :
document.getElementById(ID_HERE).addEventListener("click", myFunction);
JQUERY
If you're using jquery :
$('body').on('click', '#ID_HERE', myFunction);
Take a look at addEventListener vs onclick.
Hope this helps.
The issue is that you are calling the function by using FUNCTION();
Since your code appears to be using JQuery, consider using the .on method to attach a click listening:
$(document).on('click', '#ID_HERE', function(){
function_to_run();
});

Simple Javascript Program Not Working [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 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 ...

Javascript onclick not running [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I want a link, when clicked, to execute a javascript function.
Here is the javascript:
<script type="text/javascript">
function changeStyle() {
var header = document.getElementbyId("header");
var container = document.getElementbyId("container");
header.style.display = "block";
container.style.marginLeft = "auto";
}
</script>
Here is the HTML:
<span>&#9776</span> MENU
Currently, when the link is clicked, nothing happens. How would I make it so that the javascript actually changes the styles when I want it to?
EDIT:
Here is new code:
Javascript:
$('#selector').click(function() {
var header = document.getElementById("header");
var container = document.getElementById("container");
header.style.display = "block";
container.style.marginLeft = "auto";
})
HTML:
<span>&#9776</span> MENU
Use the onclick attribute, not the href :
<span>&#9776</span> MENU
A better idea would be to not use inline javascript
<span>&#9776</span> MENU
<script type="text/javascript">
var a = document.getElementById('menu');
a.onclick = function() {
var header = document.getElementById("header");
var container = document.getElementById("container");
header.style.display = "block";
container.style.marginLeft = "auto";
}
</script>
FIDDLE
Note: the script must be placed after the elements

Categories