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>
Related
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();
I have created an iframe (lets call it a div to simplify things), that has a transform: scale property that I'm calling with javascript.This scales the div, but however, it also shifts the div upwards. I would like the top to stay in the same place.
Background info (from answers suggestions): I want to create something that looks like google docs. I have created an iframe that will transform when an input box value is change (like google docs). I want the top to remain in the same place (like google docs).
1) I have tried in javascript to implement document.getElementById("textareathingy").style.transform = "translateY(1000px)"; document.getElementById("textareathingy").style.transform = "scale(" + percentage + ")"; I tried to put the translate both before and after the scale, but both methods do not work, and the div continues to go upwards when I put translate first, and the div does not zoom in when I put scale first.
2) I have tried to put position: absolute; to counteract it going up, but that doesn't help either, and it gets rid of my scrolling feature on the div. So in answers please don't use position: absolute.
3) I have tried using the zoom feature, but that doesn't zoom in on the contents of the div, so that also doesn't work.
For some reason, there is no error messages in any of my attempts.
Here is also my css for the div:
#textareathingy{
width: 820px;
margin: 20px auto;
height: 1000px;
border: none;
display: block;
padding: 75px;
background-color: white;
box-shadow: 0 0 5px 0 rgba(0,0,0,0.2);
}
Here are two pictures from google docs that represents what I want.
Notice how they both have the same "top" position, but it is zoomed in.
Use the transform-origin CSS property to set the point in the element that the transform should originate from. Set this to top so that the scale extends downward from the top point.
img { border:1px solid black;}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>CSS Transforms</title>
<style>
img {
/* Single Transformations: */
transform-origin: top;
}
/* Triggering a transformation: */
img:hover {
transform: scale(1.5, 1.5);
}
</style>
</head>
<body>
<img class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uryjz8HQV7hCHmVgn4bEUv08Z6jvSluqY8brlHP6SkxZOe6A7+PlGZm7w8f73wz1jGvc9vNusCluh2+EMP9smNHYP8G1o574qwKPu45mZd4qvuMyH5h6rE+rcOA32bK5ciOhp5OR3ZE9NvDypHjivgf2eUiCDNUxugAAAAASUVORK5CYII=">
</body>
</html>
To trigger this from JavaScript, just access the transformOrigin property as you would any other:
let img = document.querySelector("img");
img.style.transformOrigin = "top"; // Set the origin
img.addEventListener("mouseover", function(){
this.classList.add("scale");
});
img.addEventListener("mouseover", function(){
this.classList.remove("scale");
});
.scale {
transform:scale(1.5,1.5);
}
img { border:1px solid black; }
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>CSS Transforms</title>
<style>
img {
/* Single Transformations: */
transform-origin: center;
}
/* Triggering a transformation: */
img:hover {
transform: scale(1.5, 1.5);
}
</style>
</head>
<body>
<img class="car" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAS8AAACmCAMAAAC8yPlOAAAAt1BMVEX////e3+AFM2EAMF8AHlYAJ1y6w87r7vIADE8AL18dPmjc3d4ALF0AIlgAKlwAKFvl5eUAIFcAG1UAF1MAFFLp6uoAEVH5+fnw8fHFzNZyg5tQY4E2U3cANmTR1dm+xtHd4ujb4OauuMWRn7HKz9QoSG+ZpLJidpGGlamxu8hugZl6jKJWbInQ2OC8wcjJztNGXHwhRGwAAE47WX2XorCjrbkzTHBVaIUPPmteb4mNl6evtb+Bj6FtBcyeAAAVp0lEQVR4nO1da3uquhKukkhREghY8QKKUkRFLS6L1bb//3edXECtolWrtvs8vOfDWRu5TCYzk7klfXjIkSNHjhw5cuTIkSNHjhw5cuTIkSNHjhw5cuTIkSNHjhw5cuTIkSNHjhw5cuTIkSNHjhw5cuTIkSNHjhw5cuTIkSNHjhw5cuTIkePakN3uc6nTaDy3210KdxI2ZIa6ZVm/TdufQr077AfzsgKBQQAwGAAghEAENawqUrHoOOVyeTbzF7Y9j1pv43EQjJrh5+Dd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sKTWvkvejPeGwfuVRh8SE1bExX5hhyS9EorUYjUreX4veII8J4O8Jk9uSce7c66PIW8PldDstbKliE/td4cLl1T9HVufYsBrgRJZxJvWL3bA8kC0Fyr3Zhf1/TBPaEmQvHnT53al0n75+LSTA+oVLatD2vqC+k/w9VUZ3+olZ3Ij0HqfMuoYeQtDkKc5v3D+nGwTEdWrkKhOuexoJE3yo1nbqj9RZBxDWNnFvok5gu+e5gfEU9StjqKtyWN/b9KBKXmSMb53FkDAQ+sU0vZf5sDk8zwm3AR6e2SoGdRJsHjfv8nGVOmJ9zZSkjS4k0WSoNrMWjV/AXpjvN5fvM4HosSn1pkM3vgvw1I+sU9tKYH+MvBhWiOQFBXC2eCPcItBn4ZlmJyaxv+ylBbFWz4GH4hO+XYTZj0VsrRM11/6o8gBBoDSfPQ6vfwY/JtA16deMGenwjqLVTN+ziSvUni6Ab/0TH5xmigR7Uryjz8HQV7hCHmVgn4bEUv08Z6jvSluqY8brlHP6SkxZOe6A7+PlGZm7w8f73wz1jGvc9vNusCluh2+EMP9smNHYP8G1o574qwKPu45mZd4qvuMyH5h6rE+rcOA32bK5ciOhp5OR3ZE9NvDypHjivgf2eUiCDNUxugAAAAASUVORK5CYII=">
</body>
</html>
This question already has answers here:
How to retrieve the display property of a DOM element?
(4 answers)
Closed 3 years ago.
i need to increment the value top attribute of a div. for some reason it doesn't work.
i tried to use obj.style.top and increase the value but it doesn't work.
let sqr = document.getElementById("sqr")
let val = parseInt(sqr.style.top)
sqr.style.top = (val + 100) + "px";
body {
width: 100vw;
height: 100vh;
position: relative;
}
#sqr {
height: 30px;
width: 30px;
background-color: blue;
position: absolute;
top: 100px;
left: 100px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<link rel="stylesheet" href="index2.css" />
</head>
<body>
<div id="sqr"></div>
<script src="index2.js"></script>
</body>
</html>
I just want the square move up about 100 px.
thanks.
Use
sqr.style.top= (sqr.offsetTop + 100) + "px";
style.top returns the top value set in style attribute on the html tag.
The .style DOM property returns a CSS Style Declaration object containing the styles that have been set on the object through the HTML style attribute. Since your div doesn't have any inline styles applied to it, that technique won't return anything.
Instead, use getComputedStyle(), which returns the computed value of any/all styles, regardless of how/where they were set (inline, JavaScript, stylesheet).
Also (FYI):
As a best practice, you should always specify the optional second argument for parseInt() (the radix) to ensure you don't accidentally get a value you didn't expect.
let sqr = document.getElementById("sqr")
let val = parseInt(getComputedStyle(sqr).top, 10);
sqr.style.top= (val + 100) + "px";
body{
width:100vw;
height:100vh;
position: relative;
}
#sqr{
height: 30px;
width:30px;
background-color: blue;
position:absolute;
top:100px;
left:100px;
}
<div id = "sqr"></div>
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
<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%;