How do I create elements on the screen using javascript? - javascript

I'm trying to create my own version of Snake, the arcade game, as a learning exercise. I've tried several versions of this function and had no success. What am I doing wrong?
This code is meant to create the snake at the beginning of the game, preferrably on page-load.
body {
position: relative;
display: flex;
justify-items: center;
align-items: center;
margin: 0;
background: rgb(150, 223, 255);
}
#game-board {
width: 100vw;
height: 100vh;
border: 5px solid darkgrey;
box-sizing: border-box;
}
button {
position: absolute;
}
.snake-block {
position: absolute;
width: 1vw;
height: 1vh;
background: purple;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Snake</title>
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<div id="game-board">
<button>Start</button>
</div>
<script>
const babySnake = 1;
function createSnake(babySnake) {
while babySnake <= 3 || babySnake = false {
document.createElement("div");
div.setAttribute('class', 'snake-block');
snake-block.style.backgroundColor('salmon');
}
}
createSnake()
</script>
</body>
</html>

There are a few changes you need to make. You need to keep in mind that you need to store references to elements somewhere (hint: in a variable).
So when you're doing:
document.createElement("div");
The new div that's being created a) has no parent to be attached to, it's just floating and b) you have no way to reference it.
So you need to do this:
var child = document.createElement("div");
child.setAttribute('class', 'snake-block');
Also this line doesn't actually refer to anything as nowhere else is 'snake-block' referred to. You can do what you're after, you can read more about that here:
snake-block.style.backgroundColor('salmon');
Here's a more or less working jsbin.

The condition in your while loop should be enclosed in parenthesis: while (condition)
Your "snake block" should be declared as a variable and assigned a value, like so: let snakeBlock = document.createElement("div"); - just calling createElement will do nothing if you'll not assign it to a variable.
Dashes and similar characters are not allowed to be used as a variable name. Otherwise, they'll be interpreted as a mathematical operation. snake-block should be named as snakeBlock instead.
I included a variable pointing to the game board element and made it so that your snake blocks will be appended.
The parameter babySnake in your createSnake function isn't necessary unless you plan on passing something as an argument.
The following should work:
const babySnake = 1;
function createSnake() {
let gameBoard = document.getElementById("game-board");
while (babySnake <= 3) {
let snakeBlock = document.createElement("div");
snakeBlock.setAttribute('class', 'snake-block');
snakeBlock.style.backgroundColor = 'salmon';
gameBoard.appendChild(snakeBlock);
babySnake++;
}
}
createSnake();

Related

script.js:3 Uncaught TypeError: Cannot set properties of null (setting 'innerHTML') why am i getting this again and again

* {
margin: 0;
padding: 0;
}
body {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
background-color: #111;
}
body .clock {
font-family: Orbitron;
color: white;
font-size: 100px;
display: flex;
flex-direction: column;
align-items: flex-end;
}
.clock .am-pm {
font-size: 25px;
font-family: sans-serif;
}
.clock .day {
font-size: 20px;
font-family: sans-serif;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link href='https://fonts.googleapis.com/css?family=Orbitron&text=0123456789:AMP' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="clock">
<div class="time">
<span class="hour">00</span>
<span>:</span>
<span class="min">00</span>
<span>:</span>
<span class="sec">00</span>
<span>am</span>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
i dont know why despite placing the script tag at bottom i am getting this error
here is the js
const Time = () => {
let hrs = new Date().getHours()
document.getElementById("hour").innerHTML = hrs;
let min = new Date().getMinutes();
document.getElementById("min").innerHTML = min;
let sec = new Date().getSeconds();
document.getElementById("sec").innerHTML = sec;
}
Time();
i am making a digital clock and dont know why this isnt working i did all the js and html and css no syntax error no other kind of error its just keeps popping up just a pain in a**
this is a valid question, so I hope that I'm able to help you out here. The first thing I see is that in your header you do not have a link to your css file. That's okay, it's easy to forget. I would add a line of code in your html file that looks like this:
<link rel="stylesheet" href="YOUR-CSS-FILE-NAME.css" />
Secondly, as other people have pointed out, instead of writing class="hour" you should write id="hour". That way the function .getElementById() can find the element by the id. Otherwise the function will return a null value, which is what is giving you the error.
Lastly, if you follow the steps above you will see that your digital clock appears frozen. This is because in your javascript file you only call the Time() function once. What you probably want is for Time() to be called every second. One way you might want to do this is to add this to your js file:
window.setInterval(function () {
Time()
}, 1000)
This ensures that your function will be called every 1000ms ie once every second.
Goodluck and keep coding! There are some excellent careers out there for you if you keep working at it. Just know it's normal to write bugs, get stuck, and ask for help.

Make an element falling down to the page using html ,css, js

I want to make the grid element to fall down to the page . I used setInterval to repeat the proces (the bottom will decrease so the grid will descend ) . I think I didn't create move() function correctly.I just want to know how can I set the function correctly .
!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel= "stylesheet" href ="style.css"></link>
</head>
<body>
<div class="grid"></div>
<script src="javascript.js" ></script>
</body>
</html>
.grid {
background-color:blue;
height: 20px;
width :100px;
left:600px;
top:150px;
position : absolute;
}
var grid =document.querySelector('.grid');
function move () {
grid.style.bottom-=4;
grid.style.bottom=grid.bottom +'px';
}
move();
setInterval(move,30);
If you would still like to implement your approach to realize this movement, here is some feedback.
Bottom value is String, not numerical (e.g. 300px vs 300)
If you want to manipulate the bottom value of an element, you have to parse the numerical value first, then change it, and then append a 'px' (or whatever unit you're using).
// grid.style.bottom-=4; // subtraction on strings is not allowed
// instead, use:
const currentBottom = parseInt(grid.style.bottom, 10)
grid.style.bottom = (currentBottom - 4) + 'px'
document.getElementById(...).style misses styles from <style> blocks and stylesheets
If you want to get all current styles of a DOM element, you should use window.getComputedStyle. As described in the docs:
getComputedStyle is read-only, and should be used to inspect the element's style — including those set by a element or an external stylesheet
In the snippet below, you can see and compare the values grid.style.bottom and window.getComputedStyle(grid). At first, the first version is empty, but the second has the expected value from the stylesheet.
Alternatively, you could directly apply the style in-line with the HTML element. Then you could use .style as well for accessing the correct value from the beginning.
<div class="grid" style="bottom: 100px"></div>
Check out the fixed version of the snippet below with a delay of 3 seconds for better understanding.
var grid = document.querySelector('.grid');
function move() {
const style = grid.style.bottom
const computedStyle = window.getComputedStyle(grid)
console.log('bottom', style)
console.log('bottom from computed style', computedStyle.bottom)
// grid.style.bottom -= 4;
// grid.style.bottom = grid.bottom + 'px';
const newBottom = parseInt(computedStyle.bottom, 10) - 4; // parseInt only reads the numeric value from the bottom string
grid.style.bottom = newBottom + 'px';
}
move();
setInterval(move, 3000);
.grid {
background-color: blue;
height: 20px;
width: 100px;
left: 100px;
bottom: 200px;
position: absolute;
}
<div class="grid"></div>
I would recommend you to use a CSS animation for that, you don't need JavaScript for that.
.grid {
background-color: blue;
height: 20px;
width: 100px;
left: 100px;
position: absolute;
animation: move 1.5s forwards;
}
#keyframes move {
from {
bottom: 200px;
}
to {
bottom: 0;
}
}
<body>
<div class="grid"></div>
</body>

moving an element in JS

I'm learning javascript and trying to make a simple exercise : I have a text box and want control it with keyboard.
My HTML is the following (for now, I'm just trying 1 direction)
const myBox = document.querySelector("h1");
document.addEventListener('keydown', function (event){
if (event.keyCode == '38'){
myBox.style.top -= 5;
console.log("test if it works");
}
});
and my HTML is
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title>Tuto</title>
<style>
h1 {
width: 200px;
height: 40px;
border: 5px solid #BADA55;
color: #A28;
margin: 0;
text-align: center;
}
</style>
</head>
<body>
<div><h1>My text</h1></div>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
My check test with console log works. So event listener does.
But my box doesn't move. How can I solve it and why my use of .style.top is incorrect ?
Thank you
Positions property like "top", "bottom", "left" and "right" will not work unless your element has the property "position" as "absolute" or "relative".
In that case, what you want is to add "position: relative" to your h1 style on css.
If you want to understand more about that, this can give you a headstart https://www.w3schools.com/css/css_positioning.asp :D
To move an element by changing it's top value, the element can't have a static position (the default). You'll need to change the position to absolute, relative, fixed, etc....
Get the current top, left, etc... using Element#getBoundingClientRect, which will give you the correct initial value, and save you the need to parse a string. Since top needs to have a unit (px, em, etc..), add px to the changed top.
const myBox = document.querySelector("h1");
document.addEventListener('keydown', function(event) {
if (event.keyCode == '38') {
myBox.style.top = myBox.getBoundingClientRect().top - 5 + 'px'; // parse the string to number, subtract 5, and add 'px'
console.log(myBox.style.top);
}
});
h1 {
position: absolute;
top: 0;
left: 0;
width: 200px;
height: 40px;
border: 5px solid #BADA55;
color: #A28;
margin: 0;
text-align: center;
}
<div>
<h1>My text</h1>
</div>
1- you have to use let not const, because you want to change it and it is not fix;
let myBox = document.querySelector("h1");
2- you have to set your element as absolute position. because top property work not in static position
position:absolute;
3- you have to convert value of top position to number and then do something
myBox.style.top = parseFloat(myBox.style.top || 0) - 5 + 'px';
see my code : https://codepen.io/miladfm/pen/dRNLvw

the ID is taking over my class when im using Javascript

I've been sitting with this problem for like 2 hours. What I'm trying to make is a website where you push a button and it changes color. I know this can be done with CSS, but I'm not interested in that.
The main problem is that when I push the button, nothing happens.. However, if I remove the ' #sug from the css' everything works perfectly... So what I want to do, is to make the layout very basic at the beginning, so there's nothing to it, except like the black background, and when I push the buttons it should switch..
Also, I know you can implement onclick in the button tag, but that's not what I'm going for either. I want to know WHY this happens and how I can resolve this problem.
Here's my javascript, CSS and HTML code:
window.onload = setUp;
function setUp() {
document.getElementById("normal").onclick = setNormalStyle;
document.getElementById("crazy").onclick = setCoolStyle;
document.getElementById("insane").onclick = setInsaneStyle;
}
function setNormalStyle() {
var messageBox = document.getElementById("sug");
messageBox.className = "normal";
}
function setCoolStyle() {
var savingTheSecondVar = document.getElementById("sug");
savingTheSecondVar.className = "cool";
}
function setInsaneStyle() {
var savingTheThirdVar = document.getElementById("sug");
savingTheThirdVar.className = "insane";
}
#sug {
background-color: black;
}
.normal {
height: 500px;
background-color: blue;
color: white;
padding: 30px;
margin: auto;
width: 500px;
}
.insane {
height: 500px;
background-color: green;
padding: 30px;
margin: auto;
width: 500px;
color: white;
}
.cool {
height: 500px;
background-color: red;
padding: 30px;
margin: auto;
width: 500px;
color: white;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link type="text/css" rel="stylesheet" href="Struktur.css" />
<script type="text/javascript" src="struktur.js"></script>
<title>My first Javascript project</title>
</head>
<body>
<div id="sug" class="cool insane normal">
<header>
<h1> Welcome to this Javascript site! </h1>
</header>
<section>
<p>
text
</p>
</section>
<button type="button" id="normal">First style</button>
<button type="button" id="crazy">Second style</button>
<button type="button" id="insane">Third style</button>
</div>
</body>
</html>
The problem is your CSS.
#sug{
background-color: black;
}
Overrides the background-color of your classes because it is a more specific selector (i.e. an id selector).
change the rest of your classes in the css to include the id like
#sug.normal, #sug.insane, #sug.cool etc.
Here is a nice article on CSS specificity to help you understand more: https://css-tricks.com/specifics-on-css-specificity/
That's because an id has preference over a class. You will need to specify it like this:
#sug.cool { background: red; }
etc.
You are not removing the background-color provided by the #sug id in CSS onClick() events of the buttons.
Id has more preference over classes
It is a good habit to use below code as classes has spaces between them and it can be used if you want to add more than one class.
messageBox.className += " " + "normal";

my overlay is not being centered using css

<head>
<title>Overlay test</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<style type="text/css">
#overlay {
position: absolute;
background-color: #ccffcc;
display: none;
height: 200px;
margin: 0 auto;
width: 200px;
}
</style>
<script type="text/javascript">
//<![CDATA[
function hide() {
document.getElementById("overlay").style.display = "none";
}
function show() {
document.getElementById("overlay").style.display = "block";
}
//]]>
</script>
so when the user clicks it runs show() which places the css box on top. However i want it to be centered in the browser. I've set the margin: 0 auto; which should be doing the trick shouldnt it?
I'm just trying to create an overlay function without using jquery because it seems to be incompatible with my schools cms templates.
Thanks
Margin: 0 auto won't work on position absolute elements, they exist in their own little world, outside of normal flow. So in order to pull this off, you need to do an extra step. The CSS dead centre technique will work here.
Try setting the top and left attributes on your overlay.
Use % to set top and left position. Set css attribute top:10%; Left 40%;

Categories