Trying to change background color with variable - javascript

Trying to change color using a variable, console works but color not changing when I click on the square.
Color is the variable I want to use.
I have tried an actual string value and that does not work.
<!DOCTYPE html>
<html>
<head>
<link href="main.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<h1>Test Your Reactions!</h1>
<p>Click on the shapes as fast as you can</p>
<div id="shapes">
</div>
<script>
function myFunction() {
var colour = '#'+((Math.random() * (1<<24)|0).toString(16).slice(-6));
document.getElementById("shapes").style.backgroundColour = colour;
console.log(colour);
}
</script>
</body>
</html>

its backgroundColor not Colour .. you have an extra u

You need to replace backgroundColour by backgroundColor without u :
document.getElementById("shapes").style.backgroundColour = colour;
______________________________________________________^
Must be :
document.getElementById("shapes").style.backgroundColor = colour;
NOTE 1: You need to trigger the function to see the effect and you must also give your target div shapes a width/height so you can see it.
NOTE 2: You must listen on DOMContentLoaded event to make sure all the elements are loaded to the DOM before calling your script.
Working sample:
<!DOCTYPE html>
<html>
<head>
<link href="main.css" rel="stylesheet" type="text/css" />
<style>
#shapes {
width: 100px;
height: 100px;
border: 1px solid #000;
}
</style>
</head>
<body>
<h1>Test Your Reactions!</h1>
<p>Click on the shapes as fast as you can</p>
<div id="shapes">
</div>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var shapes = document.getElementById("shapes");
shapes.addEventListener('click', myFunction, false);
});
function myFunction() {
shapes.style.backgroundColor = "#" + (Math.random() * (1 << 24) | 0).toString(16).slice(-6);
}
</script>
</body>
</html>

Try this
const shapes = document.getElementById("shapes"); // You declare once, then you can reuse
function myFunction() {
var colour = '#'+((Math.random() *(1<<24)|0).toString(16).slice(-6));
shapes.style.backgroundColor = colour;
console.log(colour);
}
shapes.addEventListener('click', myFunction); // I guess you want to click somewhere
<h1>Test Your Reactions!</h1>
<p>Click on the shapes as fast as you can</p>
<div id="shapes">Shapes</div>

Below code gives the expected result. please take it.
<!DOCTYPE html>
<html>
<head>
<link href="main.css" rel="stylesheet" type="text/css"/>
<style>
#shapes {
width: 300px;
height: 300px;
background-color: coral;
color: white;
}
</style>
</head>
<body>
<h1>Test Your Reactions!</h1>
<p>Click on the shapes as fast as you can</p>
<div id="shapes" onClick="myFunction();">
test
</div>
<script>
function myFunction() {
var colour = '#'+((Math.random() * (1<<24)|0).toString(16).slice(-6));
document.getElementById("shapes").style.backgroundColor = colour;
console.log(colour);
}
</script>
</body>
</html>

Related

Function not toggling how do I fix this problem?

When the element's first clicked on its color should turn red. That part works. When the element's clicked on a second time it's should turn black, it's initial default color, and so on and so forth. That's the part that doesn't work. Once the element turns red it stays in that "state".
function toggleClass() {
var monday = document.getElementById("monday");
monday.classList.add("redColor");
monday.classList.remove("redColor");
this.classList.toggle("redColor");
}
monday.addEventListener("click", toggleClass)
.greenColor {
color: green;
}
.redColor {
color: red;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Practise App</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<div id="monday" class="">Monday</div>
<script src="index.js" type="text/javascript"></script>
</body>
</html>
You just need the toggle, it will toggle the class for you - you don't need the add or remove: monday.classList.toggle("redColor");
for example:
function toggleClass() {
var monday = document.getElementById("monday");
monday.classList.toggle("redColor");
}
function toggleClass() {
var monday = document.getElementById("monday");
monday.classList.toggle("redColor");
}
monday.addEventListener("click", toggleClass)
.greenColor {
color: green;
}
.redColor {
color: red;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Practise App</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<div id="monday" class="">Monday</div>
<script src="index.js" type="text/javascript"></script>
</body>
</html>
You don't need this two instructions:
monday.classList.add("redColor");
monday.classList.remove("redColor");
Just the toggle is enough. Also if you already captured the div in the variable monday, you don't need the reference to this:
function toggleClass() {
var monday = document.getElementById("monday");
monday.classList.toggle("redColor");
}
monday.addEventListener("click", toggleClass)
this should do the trick.
Here's a pen to illustrate: https://codepen.io/ePresas/pen/BaQjVwG
DOMTokenList.toggle()
The toggle() method of the DOMTokenList interface removes a given token from the list and returns false. If token doesn't exist it's added and the function returns true.
You do not need to use add() and remove(), simply toggle() should do the trick.
Also, as this keyword refers to the currently clicked element, I think you do not need to get the element by id here:
function toggleClass() {
this.classList.toggle("redColor");
}
monday.addEventListener("click", toggleClass)
.redColor {
color: red;
}
.greenColor {
color: green;
}
<div id="monday" class="">Monday</div>

JavaScript function not called at onclick button in Visual Studio 2015 Community Edition

I am learning JavaScript and CSS and made a test project in Visual Studio 2015 Community Edition. The problem that I have is, the function changeTitleCSSStyle isn't called when using Visual Studio 2015 Community Edition. At online editor https://js.do/ and in Google Chrome browser the function call works properly. My code:
index.htm
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="css/default.css">
<title>JavaScript and HTML</title>
<meta charset="utf-8" />
<script>
function changeTitleCSSStyle() {
alert("Aanroep");
var title = document.querySelector("#mainTitle");
title.style.color = 'black';
title.style.backgroundColor = "yellow";
title.style.border = "5px dashed red";
}
</script>
</head>
<body>
<h1 id="mainTitle">My home page</h1>
<p>This is an example of interactivity between JavaScript and the HTML content of a document.</p>
<button onclick="javascript: changeTitleCSSStyle();">Change style</button>
</body>
</html>
default.css
h1 {
color: red;
background-color: lightGreen;
border: 12px solid violet;
padding: 5px;
border-radius: 15px;
text-align: center;
}
p, h1 {
font-family: cursive;
}
p, img, button {
margin-left: 50px;
}
Not sure why it doesn't work when using VS. Maybe inline click events are not supported for some reason.
Perhaps it works if you try setting the event in your script itself like this:
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript and HTML</title>
<meta charset="utf-8" />
<script>
function changeTitleCSSStyle() {
alert("Aanroep");
var title = document.querySelector("#mainTitle");
title.style.color = 'black';
title.style.backgroundColor = "yellow";
title.style.border = "5px dashed red";
}
document.addEventListener("DOMContentLoaded", function(event) {
var button = document.getElementById('change_style_button')
button.addEventListener('click', function(){
changeTitleCSSStyle()
});
});
</script>
</head>
<body>
<h1 id="mainTitle">My home page</h1>
<p>This is an example of interactivity between JavaScript and the HTML content of a document.</p>
<button id="change_style_button">Change style</button>
</body>
</html>
You can try
<button onclick="changeTitleCSSStyle();">Change style</button>

Own JavaScript not running

I'm starting to learn HTML5+CSS+JS. It was all going fine on my Windows desktop, but when I try doing something on my Linux notebook, no javascript seems to work.
This is the mini tutorial I followed: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/JavaScript
and this is my page with the result: http://www.lele.bbt.net.ar/prueba01/
(As you can see, the JS is not doing a thing).
// JavaScript demonstration
var changeBg = function(event) {
console.log("method called");
var me = event.target,
square = document.getElementById("square");
square.style.backgroundColor = "#ffaa44";
me.setAttribute("disabled", "disabled");
setTimeout(function() {
clearDemo(me)
}, 2000);
}
function clearDemo(button) {
var square = document.getElementById("square");
square.style.backgroundColor = "transparent";
button.removeAttribute("disabled");
}
var button = document.querySelector("button");
button.addEventListener("click", changeBg);
console.log(button);
#square {
width: 120px;
height: 120px;
border: 2px inset gray;
margin-bottom: 1em;
}
button {
padding: .5em 2em;
}
<!DOCTYPE html>
<html>
<head>
<title>Mozilla CSS Getting Started - JavaScript demonstration</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<h1>JavaScript sample</h1>
<div id="square"></div>
<button>Click Me</button>
</body>
</html>
(Here it works, but for some reason, not when I do it on my computer).
I don't know if it can be a priviledge problem or something like that (js has read/write priviledges, not execute. But I guess that's how it should be)
Thanks!
I'm pretty sure it's because the script can't find the button.
You load your script before everything else is loaded, which is fine. But you can have problems like this. To avoid this kind of problems you load the JavaScript file after the HTML.
At the moment if you try to print the var "button" you will receive "null".
The Chrome console when you open the page gives you this error:
Uncaught TypeError: Cannot read property 'addEventListener' of null
That means that it is trying to read the property of the button, which is null.
Move the script tag to the very end, just before the closing </body> tag:
<body>
<h1>JavaScript sample</h1>
<div id="square"></div>
<button>Click Me</button>
<script type="text/javascript" src="script.js"></script>
</body>

Cannt read img width added from css file [duplicate]

This question already has answers here:
How to get element's attribute set in CSS class
(6 answers)
Closed 9 years ago.
I checked it in two newest browsers.
JS code:
window.onload = function () {
alert
(document.getElementById("slideshow").getElementsByTagName ("img") [0].style.width);
}
HTML code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Title</title>
<script src="script.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="slideshow">
<img src="slides/1.gif">
<img src="slides/2.gif">
<img src="slides/3.gif">
</div>
</body>
</html>
CSS code:
#slideshow img {
display : none;
width : 300px;
height : 200px;
}
But I have empty string from alert. Why the error (no errors in Firebug) occurs? Can I read style added from css file at all ? http://jsfiddle.net/HM47Q/
Use getComputedStyle instead.
window.onload = function () {
var elem = document.getElementById("slideshow").getElementsByTagName("img")[0];
console.log(window.getComputedStyle(elem, null).getPropertyValue("width"));
}
jsFiddle example
Empty images doesn't have width/height
Because you are retrieving inline style.
use this:
var element = document.getElementbyId("#slideshow").getElementsByTagName('img')[0];
var style = window.getComputedStyle(element),
var width = style.getPropertyValue('width');
JSFiddle: http://jsfiddle.net/enzoferber/HM47Q/2/
var firstImg = document.getElementById("slideshow").getElementsByTagName ("img") [0];
alert ( window.getComputedStyle(firstImg).width );
You have to use getComputedStyle in order to do it.
This is working::
Make your image display:block,otherwise it will return 0.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Title</title>
<style>
#slideshow img {
display : block;
border:1px solid;
width : 300px;
height : 200px;
}
</style>
</head>
<body>
<div id="slideshow">
<img src="slides/1.gif">
<img src="slides/2.gif">
<img src="slides/3.gif">
</div>
<script>
window.onload = function () {
alert(document.getElementsByTagName('img')[0].clientWidth);
}
</script>
</body>
</html>

var ball = document.getElementById("ball"); returns null object?

I've got 3 files
file 1: index.html
<!DOCTYPE html>
<html>
<head>
<LINK href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="bounce.js"></script>
<title>Bouncing ball</title>
</head>
<body>
<div id='ball'></div>
</body>
</html>
file 2: bounce.js
var ball = document.getElementById("ball");
var nx = 0;
var ny = 0;
setInterval(loop, 1000 / 30);
function loop() {
nx++;
ny++;
ball.style.left = nx;
ball.style.top = ny;
}
file 3: style.css
#ball {
position: absolute;
border-radius: 50px;
width: 50px;
height: 50px;
background: black;
}
i'm load the .css and the .js in the html file.
Now i'm trying to get te div "ball" and i want to do something with it. In this case, i want to let it bounce agains the borders of the browser. But the point is, i'm getting errors.
Uncaught TypeError: Cannot read property 'style' of null
The bonce.js can not get the elment ball. Why not? What am i doing wrong?
You are trying to get the element before it's loaded in the DOM. Do this:
<!DOCTYPE html>
<html>
<head>
<LINK href="style.css" rel="stylesheet" type="text/css">
<title>Bouncing ball</title>
</head>
<body>
<div id='ball'></div>
<script type="text/javascript" src="bounce.js"></script>
</body>
</html>
It's a good practice to include all your JavaScript at the bottom, so it doesn't block the page while downloading. And it will make sure you don't have any errors like this.
That's because your code is executed before the DOM is ready. There is no element with this id at this time.
Put your code inside a onload callback :
window.onload = function(){
var ball = document.getElementById("ball");
var nx = 0;
var ny = 0;
setInterval(loop, 1000 / 30);
function loop() {
nx++;
ny++;
ball.style.left = nx;
ball.style.top = ny;
}
};
Move your script to the end of the page or wrap it in an onload event. You're executing it before the element has loaded.
<!DOCTYPE html>
<html>
<head>
<LINK href="style.css" rel="stylesheet" type="text/css">
<title>Bouncing ball</title>
</head>
<body>
<div id='ball'></div>
<script type="text/javascript" src="bounce.js"></script>
</body>
</html>

Categories

Resources