Javascript "cannot read style property of null". Nothing is working [duplicate] - javascript

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 1 year ago.
I have tried many other solutions on this problem but none of them are working. I checked my code from other questions I found and it seems to be perfectly fine.
I want the javascript to move the div called "snake" in what direction it is moving. But it keeps saying that snake is "null". Code:
Html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Snake</title>
<style>
#main {
height: 100px;
width: 100px;
border: 1px solid black;
}
#snake {
position: absolute;
top: 20px;
left: 20px;
width: 10px;
height: 10px;
background: black;
}
</style>
<script src="script.js"></script>
</head>
<body>
<div id="main">
<div id="snake"></div>
</div>
</body>
</html>
Javascript:
let movePos = null;
let isMoving = false;
let snake = document.getElementById("snake");
function main() {
document.addEventListener("keypress", function(event) {
if (event.key == "w") {
movePos = "up";
} else if (event.key == "s") {
movePos = "down";
} else if (event.key == "a") {
movePos = "left";
} else if (event.key == "d") {
movePos = "right";
}
if (!isMoving) {
askToMove();
}
});
}
function askToMove() {
if (movePos != null) {
isMoving = true;
setInterval(move, 1000);
}
}
function move() {
if (movePos == "up") {
snake.style.top = 100;
}
}
main();

You've made the javascript run before the "snake" element is defined. Just replace your current HTML code with this.
<!DOCTYPE html>
<html lang="en">
<body> <!-- Body shifted up -->
<div id="main">
<div id="snake"></div>
</div>
</body>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Snake</title>
<style>
#main {
height: 100px;
width: 100px;
border: 1px solid black;
}
#snake {
position: absolute;
top: 20px;
left: 20px;
width: 10px;
height: 10px;
background: black;
}
</style>
<script src="script.js"></script>
</head>
<!-- No Body Here -->
</html>
All I did was shift the body section up. I have had this same problem before and I fixed it with this.

Related

Why the transform translate is not working?

I am using this code to simply move a small element(ball here), but the transform translate is only working once, even when the setInterval() function is continuously working?
This is the html file --
<!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">
<link rel="stylesheet" href="MoveTheBall.css">
<title>Move the ball</title>
</head>
<body>
<div class="ball"></div>
<script src="MoveTheBall.js"></script>
</body>
</html>
and CSS file--
.ball{
height: 5rem;
width: 5rem;
background-color: salmon;
border-radius: 50%;
position: relative;
top: 35vw;
left: 45vw;
}
and the JavaScript file--
var ball = document.querySelector('.ball');
document.addEventListener('keypress' , function(event) {
console.log('key', event.key);
if(event.key === 'w') {
moveUp();
}
});
function moveUp() {
let ballRect;
let interval = setInterval(function() {
ballRect = ball.getBoundingClientRect();
if(ballRect.top > 0) {
ball.style.transform = 'translateY(-10px)';
} else {
clearInterval(interval);
}
}, 300);
}
Here I was expecting to move the ball up until it reaches to the top of the screen after pressing w key. But the ball is only moving only once.
function moveUp() {
let ballRect;
let interval = setInterval(function() {
ballRect = ball.getBoundingClientRect();
if(ballRect.top > 0) {
let currentTop = parseFloat(getComputedStyle(ball).getPropertyValue('top'));
ball.style.transform = `translateY(${currentTop - 10}px)`;
} else {
clearInterval(interval);
}
}, 300);
}

How can I rotate only single target element jQuery?

I'm try to rotate an element but when choosing another element it's all rotate at the same time.
So I need to know how to rotate an element and it would be nice if you guys have a similar system. Because I want to learn more about this kind of system. Which is very necessary and important to me to study and work.
$(document).ready(function() {
var container = document.querySelector(".container");
var rotate = document.createElement("div");
rotate.className = "rotate";
//create Element
$("#add").click(function() {
container.appendChild(addElement());
addEvent();
});
const addElement = () => {
var element = document.createElement("div");
element.className = "resizable";
return element;
}
//add event
function addEvent() {
$(".resizable").click(function(e) {
if (e.currentTarget === this) {
$(this).append(rotate);
$(this).resizable({
handles: 'ne, se, sw, nw'
});
$(this).draggable().rotatable({
handle: $('.rotate')
});
}
});
}
});
.resizable {
width: 100px;
height: 100px;
border: 1px solid #000;
position: relative;
user-select: none;
z-index: 0;
}
.rotate {
width: 10px;
height: 10px;
border: 1px solid #000;
border-radius: 50%;
position: absolute;
top: -30px;
left: calc(50% - 5px);
cursor: move;
}
<!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>jquery</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery.ui.rotatable/1.0.1/jquery.ui.rotatable.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<button class="add" id="add">add</button> //for add element
<button class="save" id="save">save</button> //for save size and position
<div class="container"></div>
</body>
</html>
Thanks everyone in advance for helping me.

If and Else sentences, on first click

Hi I made this simple animation, when you click on the animate button, the function does not work the first time but it works the second time, how can it be? And what is the solution?
const fadeInOut = () => {
const divElement = document.getElementById('demo');
if (divElement.style.opacity == 0) {
divElement.style.opacity = 1;
} else {
divElement.style.opacity = 0;
}
};
#demo {
width: 300px;
height: 300px;
background: burlywood;
opacity: 1;
display: block;
transition: all 1s;
}
<!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>
<script src="function.js" defer></script>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="demo"></div>
<button onclick="fadeInOut()">Animate</button>
</body>
</html>
It is because .style checks for an inline style, not the one you set in an external CSS file. You can go around this by setting an initial inline style to your element:
const fadeInOut = () => {
const divElement = document.getElementById('demo');
if (divElement.style.opacity == 0) {
divElement.style.opacity = 1;
} else {
divElement.style.opacity = 0;
}
};
#demo {
width: 300px;
height: 300px;
background: burlywood;
display: block;
transition: all 1s;
}
<div id="demo" style="opacity: 1"></div>
<button onclick="fadeInOut()">Animate</button>

progress bar for loading animation of webpage

I want to make a loading animation for my webpage which will take 8-10 sec to load using JavaScript or Ajax(Which I don't know)
The loading animation is a progress bar
Which I want to stop for every 1 sec for increment of 10% eg( https://codepen.io/gustitammam/pen/RRXGdj )
Bootstrap is not welcomed and I don't want text and percentage on it
HTML
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="D:\PORTFOLIO\master.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js" integrity="sha512-n/4gHW3atM3QqRcbCn6ewmpxcLAHGaDjpEBu4xZd47N0W2oQ+6q7oc3PXstrJYXcbNU1OHdQ1T7pAP+gi5Yu8g==" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.6.1/jquery.js" integrity="sha512-qsjFwnCEe/k1YLJDkiRqDgKb+Eq+35xdoeptV7qfI7P6G/kajIF0R6d/9SiOxSkU/aNmHzuipOEYaTUHCJUIeQ==" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/javascript.util/0.12.12/javascript.util.min.js" integrity="sha512-oHBLR38hkpOtf4dW75gdfO7VhEKg2fsitvHZYHZjObc4BPKou2PGenyxA5ZJ8CCqWytBx5wpiSqwVEBy84b7tw==" crossorigin="anonymous"></script>
</head>
<body>
<div id="myprogress">
<div id="mybar">
<span id="incvalue">1%</span>
</div>
</div>
<br> <button onclick="move()">ClickMe</button>
<script>
const move = () => {
var elem = document.getElementById("mybar");
var width = 1;
var id = setInterval(frame, 10)
function frame(){
if(width >= 100){
clearInterval(id);
}else{
width++;
elem.style.width = width + "%";
document.getElementById("incvalue").innerHTML = width + "%";
}
}
}
</script>
</body>
</html>
CSS
html{
scroll-behavior: smooth;
}
body{
background: #181818;
color: #f4eee8;
}
#myprogress{
width: 45%;
background: #181818;
margin: auto;
}
#mybar{
width: 1%;
background: white;
color: white;
text-align: center;
}
In the example you cited, you can just comment out the JS lines where the following fields are set:
.attr and .text
Regarding your desire to omit Bootstrap, however, you are not asking a simple technical question but proposing that somebody write a whole program fragment for you, which is generally not the intended purpose of Stack overflow.
Actually I didn't do it but I don't know his Stack ID so #0_0#1045(From Discord)
HTML
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="D:\PORTFOLIO\master.css">
</head>
<body>
<h3>Dynamic Progress Bar</h3>
<p>Running progress bar from 0% to 100% in 10 seconds</p>
<div class="progress">
<div class="current-progress">
</div>
</div>
</div>
<script src="master.js"></script>
</body>
</html>
CSS
html{
scroll-behavior: smooth;
}
body{
background: #181818;
color: #f4eee8;
height: 100vh;
width: 100vw;
}
.progress {
position: relative;
margin-top: 20px;
height: 20px;
width: 700px;
background-color: #181818;
}
.current-progress {
height: 100%;
width: 0%;
background-color: white;
text-align: center;
transition: all 0.3s;
}
JS
let progressValue = 0;
const progressBar = document.querySelector(".current-progress");
progressBar.style.width = `${progressValue}%`;
const timer = setInterval(() => {
if (progressValue < 100) {
progressValue += 10;
progressBar.style.width = `${progressValue}%`;
}
if (progressValue === 100) {
clearInterval(timer);
}
}, 1000);
Finally Solved!!!

Overwrite styles of class using JS so change can be visible on all element with that class

someone who use JS it could be very simple.
Need to overwrite styles of one class if page is loaded in Safari browser. I think I have it all, just this line of code is problem.
This command doesnt talk to all elements with same class but it should:
document.getElementsByClassName('.background').className += " safari";
This is what I have. Mistake is in that javascript function.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
* {
margin: 0;
padding: 0;
}
div {
margin: 10px;
background: inherit;
width: 550px;
height: 450px;
}
.background {
background: rgba(255, 20, 0, 0.3);
filter: blur(10px);
}
.safari {
background: red!important;
-webkit-backdrop-filter: blur(10px)!important;
}
</style>
</head>
<body>
<div class='background'></div>
<div></div>
<div class='background'></div>
<div></div>
<div></div>
<script type="text/javascript">
if (navigator.userAgent.indexOf('Safari') != -1 &&
navigator.userAgent.indexOf('Chrome') == -1) {
document.getElementsByClassName('background').className += " safari";
}
</script>
</body>
</html>
WHAT I TRIED
1javascript
Have also tried using same code above changing class "background" to ID "background", than in javascript part of code i changed getElementsByClassName to getElementByID - that worked but it changed only first element with that ID. Rest of elements with that ID were ignored.
2conditional comment
I have tried avoiding JS and use conditional comment following link below - both browsers use webkit so I guess this is no way.
Is there any equivalent to IE conditional comment for chrome and safari?
Thanks for help.
You need to loop through all of the elements that have that class
var bgelements = document.getElementsByClassName('background');
for(var i = 0; i < bgelements.length; i++) {
bgelements[i].className += " safari";
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
*{
margin: 0;
padding: 0;
}
div{
margin: 10px;
background: inherit;
width: 550px;
height: 450px;
}
.background{
background: rgba(255,20,0,0.3);
filter: blur(10px);
}
.safari{
background: red!important;
-webkit-backdrop-filter: blur(10px)!important;
}
</style>
</head>
<body>
<div class='background'></div>
<div></div>
<div class='background'></div>
<div></div>
<div></div>
<script type="text/javascript">
if (navigator.userAgent.indexOf('Safari') != -1 &&
navigator.userAgent.indexOf('Chrome') == -1) {
var bgelements = document.getElementsByClassName('background');
for(var i = 0; i < bgelements.length; i++) {
bgelements[i].className += " safari";
}
}
</script>
</body>
</html>

Categories

Resources