How to manipulate div style with javascript? - javascript

<!DOCTYPE html>
<html>
<head>
<title>
</title>
<style>
div
{
width:5em;
height:5em;
background-color:yellow;
}
</style>
</head>
<body>
<div id="div">
</div>
<script>
window.onload = function() {
var x;
x = document.getElementByID("div");
x.style.width = '9em' ;
x.style.backgroundColor = "green";
};
</script>
</body>
</html>
What im doing wrong ? I want to change div properties like width or background color with javascript but it's not working.

change getElementByID to getElementById
<!DOCTYPE html>
<html>
<head>
<title>
</title>
<style>
div
{
width:5em;
height:5em;
background-color:yellow;
}
</style>
</head>
<body>
<div id="div">
</div>
<script>
window.onload = function() {
var x;
x = document.getElementById("div");
x.style.width = '9em' ;
x.style.backgroundColor = "green";
};
</script>
</body>
</html>

You're using getElementByID. The correct method is getElementById.
Your script should look something like this:
window.onload = function() {
var x;
x = document.getElementById("div");
x.style.width = '9em';
x.style.backgroundColor = "green";
};

JavaScript Syntax Error ! Here is the update...........
<!DOCTYPE html>
<html>
<head>
<title>
</title>
<style>
/* div {
width: 5em;
height: 5em;
background-color: yellow;
} */
</style>
</head>
<body>
<div id="div">
</div>
<script>
var x = document.getElementById("div");
x.style.width = "9em";
x.style.height = "9em";
x.style.display = "block";
x.style.backgroundColor = "green";
</script>
</body>
</html>

Change getElementByID to getElementById.
window.onload = function() {
var x;
x = document.getElementById("div");
x.style.width = '9em';
x.style.backgroundColor = "green";
};
If you want to search by the tag name, you can directly use getElementsByTagName("div") instead of assigning an id of the value div. But bear in my mind that it will return all div elements; i.e. a collection of elements.

Related

Hide body until it finishes loading

I created this code so my page would be hidden until it finishes loading. But my code doesn't work as I expected. I expected this to hide the BODY until the OnLoad event was triggered.
However, instead, it just stays hidden.
Any help would be appreciated, if there is maybe another, better method of hiding the BODY until it finishes loading, or what's wrong with this one.
Here's what I've tried so far:
function unveil() {
var thebod = document.getElementById("testbody");
thebod.STYLE = "display: block;"
}
<HTML>
<HEAD>
<TITLE>HELLO</TITLE>
</HEAD>
<BODY ID="testbody" ONLOAD="unveil();" STYLE="display: none;">
<div align="CENTER">
HELLO WORLD!
</div>
</BODY>
</HTML>
The DOMContentLoaded event of the window object can do this. But, don't hide the body, hide a wrapper instead. And, when you set the style, make sure to set the style of a CSS property, not the style object itself.
window.addEventListener("DOMContentLoaded", function(){
document.getElementById("wrapper").style.display = "block";
});
#wrapper { text-align:center; background:#e0e0e0; display:none;}
<HTML>
<HEAD>
<TITLE>HELLO</TITLE>
</HEAD>
<BODY>
<div id="wrapper">
HELLO WORLD!
<!-- The following is only added to create a delay in the
parsing of the document -->
<script>
for(var i = 0; i < 100000000; ++i){ var x = i / 3.14; }
</script>
</div>
</BODY>
</HTML>
You're not setting the elements 'style' correctly:
You can either do:
element.style.display = "block";
Or
element.setAttribute('style', "display: block");
Here is a working example:
function unveil() {
var thebod = document.getElementById("testbody");
thebod.style.display = "block";
}
<HTML>
<HEAD>
<TITLE>HELLO</TITLE>
</HEAD>
<BODY ID="testbody" ONLOAD="unveil();" STYLE="display: none;">
<div align="CENTER">
HELLO WORLD!
</div>
</BODY>
</HTML>
Your issue is here:
thebod.STYLE = "display: block;"
which should read:
thebod.style.display = 'block';
Here is the complete approach (using unobtrusive javascript):
var body = document.getElementsByTagName('body')[0];
function unveil() {
body.style.display = 'block';
}
window.addEventListener('load', unveil, false);
body {
display: none;
}
div {
text-align: center;
}
<div>HELLO WORLD!</div>
<HTML>
<HEAD>
<TITLE>HELLO</TITLE>
</HEAD>
<BODY ID="testbody" onload="testbody.style.display = '';" style="display: none;">
<div align="CENTER">
HELLO WORLD!
</div>
</BODY>
</HTML>

javascript img onclick reference error to function

I keep on getting ReferenceError: toggleExpand is not defined in console on firefox when I click the img
I am trying to get the image to enlarging, floating in center screen on click, no jquery, pure javascript, html, css.
HTML
<body>
<script type="text/javascript">
function toggleExpand(id){
var doc = document.getElementById(id);
doc.style.z-index = "1";
doc.style.width = "512px";
doc.style.align = "center";
}
</script>
<img id="img1" onclick="toggleExpand('img1');" src="I:\Images\image.jpg" alt="image" style="width:128px; height:auto; cursor:pointer; z-index:0"/>
</body>
This is my code used this can used this
<html>
<head>
<script>
function toggle(){
var doc = document.getElementById("divSection");
doc.style.z-index = "1";
doc.style.width = "512px";
doc.style.align = "center";
}
</script>
</head>
<body>
<p>Click the button to trigger a function.</p>
<p class="button" onclick="toggle()">Show/hide</p>
</body>
</html>
First of, a property cannot contain a -
so change it to CamelCase zIndex or wrap in brackets ["z-index"]
also, strange no-one mentioned, no need to pass the ID! You already have the this reference to the clicked referring HTMLIMGElement,
so yes, use simply onclick="toggleExpand(this);" without the ID
Also I see you named your function TOGGLE... so let's toggle!
img[onclick]{vertical-align:top; cursor:pointer; }
<script>
function toggleExpand(el){
var io = el.tog ^= 1; // Store the toggle state
el.style.zIndex = io ? 1 : 0;
el.style.width = (io ? 256 : 128) +"px";
}
</script>
<img onclick="toggleExpand(this);" src="https://www.gravatar.com/avatar/6edc0ac8cd9f3e790389f3284eaaf9e9?s=32&d=identicon&r=PG" alt="image" style="width:128px; height:auto; z-index:0"/>
<img onclick="toggleExpand(this);" src="https://i.stack.imgur.com/1ZIkv.jpg?s=48&g=1" alt="image" style="width:128px; height:auto; z-index:0"/>
jsBin playground
change doc.style.z-index to doc.style['z-index'] and check
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<body>
<script type="text/javascript">
function toggleExpand(id) {
var doc = document.getElementById(id);
doc.style['z-index'] = "1";
doc.style.width = "512px";
doc.style.align = "center";
}
</script>
<img id="img1" onclick="toggleExpand('img1');" src="https://upload.wikimedia.org/wikipedia/commons/thumb/0/08/Alexanderplatz_Stadtmodell_1.jpg/1920px-Alexanderplatz_Stadtmodell_1.jpg" alt="image" style="width:128px; height:auto; cursor:pointer; z-index:0"
/>
</body>
</body>
</html>
Why you are passing your id as a function argument! why not use something like this-
<body>
<img id="img1" onclick="toggleExpand();" src="I:\Images\image.jpg" alt="image" style="width:128px; height:auto; cursor:pointer; z-index:0"/>
<script type="text/javascript">
function toggleExpand(){
var doc = document.getElementById('img1');
doc.style.z-index = "1";
doc.style.width = "512px";
doc.style.align = "center";
}
</script>
</body>
It is better to do in this way.
var doc = document.getElementById(id)
doc.addEventListener('click',toggleExpand);

Change background color if width is bigger

I want to change the background color if width is bigger than 100.
This is my code but it doesn't work.
Thanks for any help!
<html>
<head>
<style type="text/css">
div#mydiv {
width: 200px;
height: 100px;
background-color: red;
}
</style>
<script language="JavaScript">
function () {
var mydiv = document.getElementById("mydiv");
var curr_width = parseInt(mydiv.style.width);
if (curr_width > 100) {
mydiv.style.BackgroundColor = "blue";
}
}
</script>
</head>
<body>
<div id="mydiv" style=""></div>
</body>
</html>
Change
parseInt(mydiv.style.width);
mydiv.style.BackgroundColor = "blue";
To
mydiv.offsetWidth
mydiv.style.backgroundColor = "blue";
use
var curr_width = mydiv.offsetWidth;
instead
var curr_width = parseInt(mydiv.style.width);
Change:
var curr_width = parseInt(mydiv.style.width);
mydiv.style.BackgroundColor = "blue";
to:
var curr_width = mydiv.offsetWidth;
mydiv.style.backgroundColor = "blue";
I have set up a fiddle here.
Also notice I took it out of the function because it looked like it wasn't being called anywhere. You should also move the script out of the head to the bottom of the body tag or use window.onload.
UPDATE
Another fiddle with everything together
I assume this is a duplicate question.
Anyway, your intialization of curr_width need not include parseInt.
parseInt is for converting a value to integer type and here you doesnt require it.
Your code can be re-written as
<html>
<head>
<style type="text/css">
div#mydiv {
width: 200px;
height: 100px;
background-color: red;
}
</style>
<script language="JavaScript">
function () {
var mydiv = document.getElementById("mydiv");
var curr_width = mydiv.offsetWidth;
if (curr_width > 100) {
mydiv.style.BackgroundColor = "blue";
}
}
</script>
</head>
<body>
<div id="mydiv" style=""></div>
</body>
</html>
Assuming your function to be called onload. Here's the code:
<html>
<head>
<style type="text/css">
#mydiv {
width: 200px;
height: 100px;
background-color: red;
}
</style>
<script language="JavaScript">
function load(){
var mydiv = parseInt(document.getElementById("mydiv").offsetWidth);
if (mydiv > 100) {
document.getElementById("mydiv").style.backgroundColor = "blue";
}
}
</script>
</head>
<body onload="load();">
<div id="mydiv" style=""></div>
</body>
</html>
Changes:
Use offsetWidth to get the width of the div.
Use backgroundColor instead of BackgroundColor.
To get a proper computed width, you need to use the (not enough used) method getBoundingClientRect() https://developer.mozilla.org/en-US/docs/Web/API/element.getBoundingClientRect
Latest browsers have .width property, otherwise you just need to take right - left to get it.
Some comments:
- language="JavaScript" is useless. Like type="text/javascript". It's the default behavior. Seriously.
- you need to execute your code after the div has been created. So using onload or just by calling the code after in the html (like in my example)
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#mydiv {
width: 200px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<div id="mydiv"></div>
<script>
/* run the code after the creation of #mydiv */
var mydiv = document.getElementById("mydiv");
var clientRect = mydiv.getBoundingClientRect()
var curr_width = clientRect.width || (clientRect.right - clientRect.left);
if (curr_width > 100) {
mydiv.style.backgroundColor = "blue";
}
</script>
</body>
</html>
Here is a working example http://jsbin.com/xapet/1/edit
Warning: to do this properly it's recommended that you execute this code each time the browser is resized.
Maybe you can take a look to the "element queries" thing, that will be a nice workaround according to media queries limitations.
https://encrypted.google.com/search?hl=en&q=element%20queries%20css

If statement in a for loop being ignored

I have a for loop which has an if statement nested inside of it, but the loop is ignoring the statement and continuing to run. Any ideas why this could be? Many thanks.
JavaScript:
var sheet = document.styleSheets[0];
var cssVal = '';
function changeColor() {
for (i = 0; i < sheet.cssRules.length; i++) {
cssVal = sheet.cssRules[i];
console.log(cssVal); // Successfully outputs #box to the console.
if (cssVal == "#box") { // Does nothing, continues iterating.
console.log("If has run.");
cssVal.style.backgroundColor="blue";
break;
}
}
}
changeColor();
CSS:
#charset "utf-8";
#box {
width:20px;
height:20px;
}
#car {
width:20px;
height:20px;
}
HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Boxes</title>
<link href="Boxes.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="box"></div>
<div id="car"></div>
<script type="text/javascript" src="Boxes.js"></script>
</body>
</html>
Obviously it isn't going inside the if, that's because cssVal is not a string, it's a CSSStyleRule object. You should do this instead:
cssVal = sheet.cssRules[i];
Then in your if:
if (cssVal.selectorText == '#box')
And then, to change the color:
cssVal.style.backgroundColor = "blue";

error in javascript toggle class

I have this code for toggling class using pure JavaScript that I found online and it is not working when I am using it in an offline website
my code is -
<!DOCTYPE html>
<html>
<head>
<script>
function classToggle() {
this.classList.toggle('class1');
this.classList.toggle('class2');
}
document.querySelector('#div').addEventListener('click', classToggle);
</script>
<style type="text/css">
.class1 {
color: #f00;
}
.class2 {
color: #00f;
}
</style>
</head>
<body>
<div id="div" class="class1">click here</div>
</body>
</html>
any help would be appreciated
Move the script below the div you are looking for in the source code.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.class1 {
color: #f00;
}
.class2 {
color: #00f;
}
</style>
</head>
<body>
<div id="div" class="class1">click here</div>
<script>
function classToggle() {
this.classList.toggle('class1');
this.classList.toggle('class2');
}
document.querySelector('#div').addEventListener('click', classToggle);
</script>
</body>
</html>
You cannot manipulate the dom before it is ready.
So either load the script that adds the handler at the end of the body tag, or use the DOMContentLoaded event.
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
});
Try adding the event handler after the div has rendered - for example in the onload event
Live Demo
<!DOCTYPE html>
<html>
<head>
<script>
function classToggle() {
if (!this.classList) return; // no support
this.classList.toggle('class1');
this.classList.toggle('class2');
}
window.onload=function() {
document.getElementById('div').onclick=classToggle;
}
</script>
<style type="text/css">
.class1 {
color: #f00;
}
.class2 {
color: #00f;
}
</style>
</head>
<body>
<div id="div" class="class1">click here</div>
</body>
</html>
codepen demo
//vanilla js -- toggle active class
// el = object containing the elements to toggle active class and the parent element
var el = {
one: document.getElementById('one'),
two: document.getElementById('two'),
three: document.getElementById('three'),
hold: document.getElementById('hold')
};
// func = object containing the logic
var func = {
toggleActive: function(ele) {
ele = event.target;
var hold = el.hold.children;
var huh = el.hold.children.length;
var hasActive = ele.classList.contains('active');
for (i = 0; i < huh; i++) {
if (hold[i].classList.contains('active')) {
hold[i].classList.remove('active');
}
}
if (!hasActive) {
ele.classList.add('active');
}
}
};
//add listeners when the window loads
window.onload = function() {
var holdLen = el.hold.children.length;
for (i = 0; i < holdLen; i++) {
el.hold.children[i].addEventListener("click", func.toggleActive);
}
};

Categories

Resources