how to get style values with js - javascript

so i have a simple html file which consists of a div; and a css file which has a simple styling for the mentioned div:
html :
<html>
<head>
<title>Simple Movement</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style.css"/>
<script src="index.js"></script>
</head>
<body>
<div id="square"></div>
</body>
</html>
css:
body {
margin: 0;
}
#square {
width: 100px;
height: 100px;
border: 1px solid #095057;
background-color: #20979e;
position: absolute;
left: 200px;
top: 200px;
}
in my js file i do a simple log as follows:
console.log(document.getElementById('square').style.top)
but i receive an error:
Uncaught TypeError: Cannot read properties of null (reading 'style')
at index.js:1
i have no idea why it says style is null.do you?

i have no idea why it says style is null.do you?
It doesnt.
It says document.getElementById('square') returns null so youre reading the property style on null which results in the error.
That happens because your script is loaded (and executed) in the head. At this point the element with the ID "square" isnt existent in the DOM yet.
Move your script to below your element (see snippet) or mark it with async defer like this: <script src="index.js" async defer></script> to make it load and execute after DOM parsing is done.
Also accessing style will only show inline styles from the style attribute so that wont get you values from your stylesheet file (or inline stylesheets).
Use computedStyleMap() (see https://developer.mozilla.org/en-US/docs/Web/API/Element/computedStyleMap) to get the actual computed styles including all stylesheets.
body {
margin: 0;
}
#square {
width: 100px;
height: 100px;
border: 1px solid #095057;
background-color: #20979e;
position: absolute;
left: 200px;
top: 200px;
}
<html>
<head>
<title>Simple Movement</title>
<meta charset="UTF-8">
</head>
<body>
<div id="square"></div>
<script>
console.log(document.getElementById('square').computedStyleMap().get('top').value);
</script>
</body>
</html>

Related

External javascript file not working in HTML file

I'm trying to change the property of a div from a javascript file but it's not working, it's working if I put it inside body but I want to work it from external js file for some project.
HTML file
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Calendar</title>
<link rel="stylesheet" href="css/styles.css">
<script src="javascript/cal.js"></script>
</head>
<body>
<div id="container">
<div id="calendar-view">
</div>
<div id="events-view">
</div>
</div>
</body>
</html>
CSS file
*{
box-sizing: border-box;
}
#calendar-view{
float: left;
width: 70%;
background-color: blue;
height: 200px;
}
#events-view{
float: left;
width: 30%;
height: 200px;
background-color: red;
}
#container::after{
content: "";
clear: both;
display: table;
}
Javascript file
function startUp(){
document.getElementById("calendar-view").style.display = "none";
}
startUp();
I'm trying to change the property of a div from a javascript file but it's not working, it's working if I put it inside body but I want to work it from external js file for some project.
When you import your JS file at <header> your JS loads and then your body.
When you import your JS file after <body> your body loads and then your JS.
The first solution is to put your JS file after the second one is to put the function call inside the window onload event listener
you have to put the <script src="javascript/cal.js"></script> at the end of the </body> tag.
You cannot get element from the DOM before the browser get it through the HTML.

html css and js not working

This is my code:
<!doctype html>
<html lang="en-US">
<head>
<title>Welcome - Home</title>
<link type="text/css" rel="stylesheet" href="Home.css">
<link rel="icon" href="KLOGO.png" type="image/png"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<script src="Home.js"></script>
</head>
<body class="menu">
<header>
Toggle
<nav class="menu-side">
This is a side menu
</nav>
</header>
<p> sioeufh iufha dgrkljbgril unfvuabervluiyboyubn serlibglisuhsefiuh oaisuf aieufh aosih asioeufh iufha dgrkljbgril unfvuabervluiyboyubn serlibglisu</p>
<p>oierua yugafapiwugText and more tejiaslirfuh aiufh oaiuefhioaushf aisbhfailsubfaufha dgrkljbgril unfvuabervluiyboyubn serlibglisuh oaiusg foiygasdefoiawg pghuioyf gaiwuebfyaweoilru gfa s7ierfygasrgoooa8iweygfra iiiastygf a8we8</p>
</body>
</html>
The css:
.menu-side{
background: #333;
border-right: 1px solid #000;
color: #fff;
position: fixed;
top: 0;
left: -231px;
width: 210px;
height: 100%;
padding: 10px;
}
.menu{
overflow-x:hidden;
position: relative;
left: 0px;
}
.menu-open {
left: 231px;
}
And the jquery:
(function () {
var body = $('body');
$('.menu-toggle').bind('click', function () {
body.toggleClass('menu-open');
return false;
});
})();
I'm using the Brackets program to write my code, but when I go to the live view after I saved everything and i press "toggle" the page wont move and I looked over everything and Im 98% sure its correct.
Put <script src="Home.js"></script> before the </body> tag.
I made another class
.menu-side-open{
left:0px;
}
and JQuery
(function () {
var body = $('body');
$('.menu-toggle').bind('click', function () {
body.toggleClass('menu-open');
$('.menu-side').toggleClass('menu-side-open');
return false;
});
})();
Also added
.menu, .menu-side{
transition: 300ms;
}
for a nice slide :)
JSFiddle demo
You need to include jQuery if you want to use it.
Add this line
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
In your html's head or before you use jQuery!
e.g.
<head>
<title>Welcome - Home</title>
<link type="text/css" rel="stylesheet" href="Home.css">
<link rel="icon" href="KLOGO.png" type="image/png"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<script src="Home.js"></script>
Change this:
body.toggleClass('menu-open');
to this:
$('.menu-side').toggleClass('menu-open');
And change the .menu-open css class to this:
.menu-open {
top:10%;
left: 0px;
}
Here is the JSFiddle demo
Its the .menu-side that is hidden on the left. Therefore you should be applying the menu-open class to .menu-side and not the body tag.
Your CSS was setting the left of .menu-side to 231px, setting it back to 0px is enough to make the menu appear back into view. And when the menu appeared, it covered the 'Toggle' link, therefore I also added top:10% to the .menu-open class CSS.
I think it is related to a missing file from the computer. I have the same issue with my computer and it does not really matter wether you put the CSS and JS into the HTML page. The result will be the same. When you open the page in the browser, you won`t see any changes, and if I press F12 it says: Failed to load resource: net::ERR_FILE_NOT_FOUND or dll file not found or something like that

id.styles is showing nothing

I'm not sure if I'm going to completely crazy or if there's something wrong with my computer.
I have a simple piece of JavaScript below but when I console log the style object it is completely empty. This is despite the fact the the element in question clearly has styles attached to it.
<!doctype html>
<html>
<head>
<style>
#para{
width: 100px;
height: 100px;
position: absolute;
left: 200px;
top: 10px;
border: 1px solid red;
}
</style>
</head>
<body>
<div id="para" class="paraDiv">This is the div</div>
<script>
window.onload = function(){
var d = document.getElementById('para');
console.dir(d);
console.log(d.style.top);
}
</script>
</body>
</html>
The style property only gets information about styles applied inline via an element's style attribute. It doesn't contain any information about styles inherited from other elements or declared in style sheets.
Instead, you want window.getComputedStyle, which will give you the information you're looking for.
console.log(getComputedStyle(para).top);

Modify CSS selector :after with JavaScript

How do I access or modify pseudo-selectors like :after and :hover of CSS of an element through JavaScript (please no jQuery).
Example
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Progress bar example</title>
<style type="text/css">
.progressbar
{
position: relative;
width: 100px;
height: 10px;
background-color: red;
}
.progressbar:after
{
content: "";
position: absolute;
width: 25%;
height: 100%;
background-color: blue;
}
</style>
</head>
<body>
<div id="progressbar" class="progressbar" onclick="this.style.width='90%';"></div>
</body>
</html>
Like you see I want to use somethink like a progress bar, so I can't simply exchange/add/remove a second class to an element. I would like to access the the width property of the progressbar:after (with the :after selector) class directly through JS. But how?
You could give this a try:
EDITED
//create new style element
var style = document.createElement("style");
//append the style
document.head.appendChild(style);
//take the stylesheet object
sheet = style.sheet
//add the rule to your stylesheet -- changed this line to .insertRule
sheet.insertRule('.progressbar::after { width: 50% }', 0);
Updated fiddle

How to get size of div based on class?

I have the following HTML file that currently has nothing in it except some div class objects that are specified by CSS styles. If I open this web page and inspect the elements in Chrome they are the sizes that I want them to be. What I am wondering is if I can access those sizes via javascript.
HTML File:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>TEST</title>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<style type="text/css">
.camp_cont {
float: left;
width: 45%;
height: 50%;
position: relative;
}
.camp_cont_select {
float: left;
width: 45%;
height: 50%;
position: relative;
fill: #800;
}
.sub_camp_cont {
float: left;
width: 15%;
height: 50%;
position: relative;
margin: 10px 25px;
fill: #800;
}
</style>
</head>
<body>
<div class="camp_cont", id="cpa_perf"></div>
<div class="camp_cont", id="ctr_perf"></div>
<div class="sub_camp_cont", id="as_perf"></div>
<div class="sub_camp_cont", id="f_perf"></div>
<div class="sub_camp_cont", id="rh_perf"></div>
<div class="sub_camp_cont", id="rm_perf"></div>
<div class="sub_camp_cont", id="rl_perf"></div>
<div class="sub_camp_cont", id="ul_perf"></div>
<div class="sub_camp_cont", id="rt_perf"></div>
</body>
</html>
I am wondering if I can do something like the following:
x = $("#cpa_perf").width()
Again, when I inspect cpa_perf in Chrome it says its width is 515px. That's what I'm trying to get at
jQuery Width works just fine for this:
x = $("#cpa_perf").width();
alert(x);
JS Fiddle: http://jsfiddle.net/9abcf9d3/
You can use jQuery pretty easily to modify attributes of elements..
$('.classname').css(property, value);
I'm not certain if you are trying to use jQuery or pure javascript.
You're original attempt to get the width of the element should work as long as you're using a jQuery library.
Otherwise, if you just want the width of the element with pure javascript, you can use something like this:
var x = document.getElementById('cpa_perf').offsetWidth;
If you are including a jQuery library then the following should work:
var x = $("#cpa_perf").width()
Additional Note: Make sure that the script isn't called before the DOM element is written to the page as well. For example:
$(document).ready(function (){
var x = $("#cpa_perf").width();
console.log(x);
}) ;

Categories