Can't change CSS with JavaScript - javascript

I want to create a page that first displays a red rectangle and a button. If you press the button the rectangle will change to blue square. Here is my code:
<!doctype html>
<html>
<head>
<style>
#e1 {
background-color: red ;
width: 400px ;
height: 200px ;
margin: 0 auto;
}
.wrapper {
text-align: center;
}
</style>
</head>
<body>
<div id ="e1">
</div>
<div class="wrapper">
<button type="button" onclick="myfunction()" style="width: 100px; height: 100px; position:center;">Switch</button>
</div>
<script type="text/javascript">
function myfunction() {
document.getElementById("e1").style.background-color= "blue";
document.getElementById("e1").style.width = "400px";
document.getElementById("e1").style.height = "400px";
}
</script>
</body>
</html>
The problem is the rectangle doesn't change to square that means the JavaScript has some issues.

Change:
document.getElementById("e1").style.background-color= "blue";
To:
document.getElementById("e1").style.backgroundColor = "blue";

Two things -
First you have syntax error in
document.getElementById("e1").style.background-color= "blue";
It should be either
document.getElementById("e1").style['background-color']= "blue";
OR
document.getElementById("e1").style.backgroundColor= "blue";
Second, I don't know if it's a type in your question, but you missed the opening < in your button tag. That is the reason it is failing.
What you have here is
button type = "button" onclick = "myfunction()" style = "width: 100px ; hight: 100px ; position:center ;">Switch</button>
Which should be
<button type = "button" onclick = "myfunction()" style = "width: 100px ; hight: 100px ; position:center ;">Switch</button>
Working Fiddle

This Should work
document.getElementById("e1").style['background-color']= "blue";

Here you go. There was a slight problem with your HTML
<!doctype html>
<html>
<head>
<style>
#e1 {
background-color: red ;
width: 400px ;
height: 200px ;
margin: 0 auto;
}
.wrapper {
text-align: center;
}
</style>
</head>
<body>
<div id ="e1">
</div>
<div class="wrapper">
<button type = "button" onclick = "myfunction()" style = "width: 100px ; hight: 100px ; position:center ;">Switch</button>
</div>
<script type="text/javascript">
function myfunction() {
document.getElementById("e1").style.backgroundColor= "blue";
document.getElementById("e1").style.width = "400px";
document.getElementById("e1").style.height = "400px";
}
</script>
</body>
</html>
Two things.
Complete your button tag. It was missing the initial "<" before "button".
Change background-color to backgroundColor in your JavaScript click handler.

Related

Why do I need to press the button 2 times to make this function work? [duplicate]

This question already has answers here:
Why do I have to click this input button twice to call a function?
(4 answers)
Closed 1 year ago.
Below I have 2 pieces of code. The purpose of the code is to alternate between showing and hiding an element by clicking on the button.
Logically, I feel both pieces of code are sound and should work in exactly the same way. However, #1 functions as required whilst #2 doesn't. #2 requires 2 presses of the button to first display the element. After that, it functions as required.
I assume I have made a mistake linked to nomenclature, but I am unable to pinpoint it. Please help in doing so.
#1
<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
visibility: hidden;
}
</style>
</head>
<body>
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.visibility === "hidden") {
x.style.visibility = "visible";
} else {
x.style.visibility = "hidden";
}
}
</script>
</body>
</html>
#2
<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
visibility: hidden;
}
</style>
</head>
<body>
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.visibility === "visible") {
x.style.visibility = "hidden";
} else {
x.style.visibility = "visible";
}
}
</script>
</body>
</html>
That's happening because the x.style returns inline style for an element (the value sets on the div tag <div id="myDIV" style="/*this value*/"> and not the overall element styling) which is empty by default , think of it as any other HTML attributes like id or width.
So what you want to do, is to declare the visibility propriety inside the div like so :
<div id="myDIV" style="visibility: hidden;">
this way x.style.visibility will return 'hidden' from the first time.
Here are two snippets so you see the difference:
The same as your code just added a console.log
<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
visibility: hidden;
}
</style>
</head>
<body>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
console.log('x.style.visibility = '+x.style.visibility);
if (x.style.visibility === "hidden") {
x.style.visibility = "visible";
} else {
x.style.visibility = "hidden";
}
}
</script>
<div id="myDIV">
This is my DIV element.
</div>
</body>
</html>
and now if we set visibility as an inline style
<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
</style>
</head>
<body>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
console.log('x.style.visibility = '+x.style.visibility);
if (x.style.visibility === "hidden") {
x.style.visibility = "visible";
} else {
x.style.visibility = "hidden";
}
}
</script>
<div id="myDIV" style="visibility: hidden;">
This is my DIV element.
</div>
</body>
</html>
account for starting condition
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.visibility === "hidden" || !x.style) {
x.style.visibility = "visible";
} else {
x.style.visibility = "hidden";
}
}

Add tags to existing text

How to add new tags to text that is already present inside some element. Is there a better way than copying the text into new element and then deleting from old?
In the example below, text Hello World! is already present inside a div. The goal is to add h1 around the text.
<head>
<script>
let myFunction = function() {
let d = document.getElementById("testId");
let h = document.createElement("h1");
h.textContent = d.textContent;
d.textContent = "";
d.appendChild(h);
};
</script>
<style>
.testClass {
height: 100px;
margin: auto;
width: 200px;
border-style: solid;
text-align: center;
}
</style>
</head>
<body>
<div id="testId" class="testClass">Hello World!</div>
<button onclick="myFunction()">Click Here</button>
</body>
This question is likely going to get multiple opinions.
Mine is that you are doing it just fine using the DOM API. However, if you understand the performance and security implications of .innerHTML, you could do this:
<head>
<script>
let myFunction = function() {
let d = document.getElementById("testId");
d.innerHTML = "<h1>" + d.textContent + "</h1>";
};
</script>
<style>
.testClass {
height: 100px;
margin: auto;
width: 200px;
border-style: solid;
text-align: center;
}
</style>
</head>
<body>
<div id="testId" class="testClass">Hello World!</div>
<button onclick="myFunction()">Click Here</button>
</body>

Java script Switching color of div

The following script is creating a grid of 16 divs. Per mouseover effect I would like to change the color of the divs permanently. Can somebody give me a pointer how what function changeColor could look like?
<script>
let gridcontainer = document.querySelector('#gridcontainer');
gridcontainer.setAttribute('style', 'width: 20px; display: grid; grid-template-columns: auto auto auto auto;')
var index = [];
var boxes;
var i;
var change;
function createGrid(){
for(i=0;i<16;i++){
//console.log(index);
boxes = document.createElement('div');
console.log(boxes);
boxes.classList.add('boxes');
boxes.setAttribute('style','width: 30px; height:30px; background-color:
blue; margin: 5px;');
boxes.setAttribute('onmouseover', changeColor());
gridcontainer.appendChild(boxes);
}}
function changeColor(){
change = document.querySelector('.boxes');
change.setAttribute('style','background-color: red');
}
</script>
Thank you all for your help.
I have used jquery function (toggleClass) to change the color div on hover
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style type="text/css">
.b1{
background:red;
width: 30px;
height: 40px;
margin: 10px;
}
.b{
background:blue;
width: 30px;
height: 40px;
margin: 10px;
}
</style>
</head>
<body>
<div class="b1"></div>
<div class="b1"></div>
<div class="b1"></div>
<div class="b1"></div>
<div class="b1"></div>
<script type="text/javascript">
$('div').hover(function () {
// body...
$("div").toggleClass("b");
});
</script>
</body>
</html>

How javascript alert a css value? [duplicate]

This question already has answers here:
why javascript this.style[property] return an empty string? [duplicate]
(2 answers)
Closed 6 years ago.
Hi there I'm having a problem. I made a box of blue color in HTML/CSS and want javascript to alert the name of color when the box is clicked. Here is my code.`
var clr = document.getElementById("box").style.backgroundColor;
document.getElementById("box").onclick= function() {
alert(clr);
}
<!DOCTYPE html>
<html>
<head>
<title>
</title>
<style>
#box {
height: 100px;
width: 100px;
background-color: blue;
margin: 0px;
display: inline-block;
}
</style>
</head>
<body>
<div id="box" class="box">
</div>
</body>
</html>
You need to use getComputedStyle(). .style is use to set a new value for target element.
var div = document.getElementById("box"), // element
divCSS = window.getComputedStyle(div), // element CSS
bgColor = divCSS.getPropertyValue('background-color'); // property
document.getElementById("box").onclick= function() {
alert(bgColor);
}
#box{
height: 100px;
width: 100px;
background-color: blue;
margin: 0px;
display: inline-block;
}
<div id="box" class="box"></div>
Here is the working code
<!DOCTYPE html>
<html>
<head>
<title>
</title>
<style>
#box {
height: 100px;
width: 100px;
background-color: blue;
margin: 0px;
display: inline-block;
}
</style>
</head>
<body>
<div id="box" class="box">
</div>
</body>
</html>
<script>
/* var clr = document.getElementById("box").style.backgroundColor;*/
document.getElementById("box").onclick= function() {
var ele = document.getElementById("box");
var style = window.getComputedStyle(ele);
var bColor = style.getPropertyValue("background-color");
alert(bColor);
}
</script>
This works
var clr = document.getElementById("box").style.backgroundColor;
document.getElementById("box").onclick= function() {
alert(clr);
}
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<div id="box" class="box" style="height: 100px;width: 100px;background-color: blue;margin: 0px;display: inline-block;"></div>
</body>
</html>
You can also use below code with provided html
<script>
var clr= window.getComputedStyle(document.getElementById("box")).getPropertyValue('background-color'); // property
document.getElementById("box").onclick= function() {
alert(clr);
}
</script>
Try using the variable clr inside the function.
Also invoke the fucntion using onclick on the div itself.
Using regex to get the property backgorund color in whole css.
You can also use filter on #box using
var boxCss = clr.match(/#box{((.*\s*.*)*)}/g);
<!DOCTYPE html>
<html>
<head>
<title>
</title>
<script>
function colorAlert() {
var clr = document.getElementsByTagName("style")[0].innerHTML;
var res = clr.match(/background-color:.*;/g);
alert(res[0]);
}
</script>
<style>
#box{
height: 100px;
width: 100px;
background-color: blue;
margin: 0px;
display: inline-block;
}
</style>
</head>
<body>
<div id="box" class="box" onclick="colorAlert();">
</div>
</body>
</html>
You have two ways to solve this :
keep <script> tag after after closing <div> tag
move clr var in side the onclick function,then you can write <script> tag where ever you want

Setting CSS from javascript events

I'm getting started with javascript and I'm trying to do a simple example but changing the CSS of a div based on the onmouseover and onmouseout of the div element.
My test is to create a green box. When I mouse over it it should turn blue. When I mouse out it should go back to green.
Here is my source:
<html>
<head>
<title>TEST</title>
<style>
#box {
width: 30px;
height: 30px;
background-color: green;
}
</style>
<script type="text/javascript">
function setBlue(){
document.getElementById("box").style.background-color = "blue";
}
function setGreen(){
document.getElementById("box").style.background-color = "green";
}
</script>
</head>
<body>
<div id="box" onmouseover="setBlue()" onmouseout="setGreen()" />
</body>
</html>
When the pages loads the green box shows but when I mouse over nothing happens.
style.background-color should be style.backgroundColor
<html>
<head>
<title>TEST</title>
<style>
#box {
width: 30px;
height: 30px;
background-color: green;
}
</style>
<script type="text/javascript">
function setBlue() {
document.getElementById("box").style.backgroundColor = "blue";
}
function setGreen() {
document.getElementById("box").style.backgroundColor = "green";
}
</script>
</head>
<body>
<div id="box" onmouseover="setBlue()" onmouseout="setGreen()" />
</body>
</html>
This can be done with style alone:
<html>
<head>
<style>
.example { background-color:green; }
.example:hover { background-color:blue; }
</style>
</head>
<body>
<span class='example'>Hallo World</span>
</body>
</html>
Instead "-" upper signal
document.getElementById("box").style.backgroundColor = "blue";
Try using the # sign when you are referencing an id, like so:
document.getElementById("#box").style.background-color = "blue";

Categories

Resources