I've made a quiz which has 10 questions, and stores your points in a value called total. The total points you are able to get is 20, so when total > 10, I want the background to turn red.
I have already set a background using CSS on my website here:
<style type="text/css">
body{
background-image: url("twins.jpg");
}
However I can't seem to get my condition to work properly. I've tried:
if (total > 10) {
document.body.style.backgroundColor = "red";
}
I've tried:
if (total > 10) {
document.body.style.backgroundColor = "#AA0000";
}
And:
if (total > 10) {
document.getElementById('body').style.backgroundImage = "url(ashishot.jpg)";
}
But nothing seems to work. Maybe I'm placing my if statement in the wrong place, or maybe I'm trying to set the background incorrectly, I just want to know if this is the correct way to change a background image from CSS into JavaScript.
Yes this is the correct way to change background color using JS.
document.body.style.backgroundColor = "#AA0000";
Please try:
Placing alert() inside the IF block to see if block is executing
See if something is overlayed(z-indexed) on body
The javascript instruction is correct
document.body.style.backgroundColor = "red";
Your error may be the if condition, check if total its work properly usign the console or an alert to check it:
console.log(total);
or
alert(total);
You have more than one issue
Use directly the body property
document.body.style.backgroundImage
You need to quote the whole assignment and you need inner quotes for the image
'url("ashishot.jpg")';
Working example:
function setBackground() {
document.body.style.backgroundImage = 'url("http://lorempixel.com/300/200/")';
}
setTimeout(setBackground, 2000);
body {
background-image: url("http://lorempixel.com/400/200/");
}
if (total > 10) {
document.body.style.backgroundImage = "url(ashishot.jpg)";
}
body is not an id. also, setting background-color will not work because browser treat background-image first. To display background-color instead of background-image, simply delete the image. Setting classes is more flexible.
document.body.classList.add("total");
body {
background-image: url("http://www.studiocity-macau.com/uploads/images/SC/Entertainment/Batman/batman_share.jpg");
}
body.total {
background-image: none;
background-color: red;
}
Be aware that your backgound-image will be on top of the color you are setting in the if block. If the image covers the background entirely you will not notice the effect of changing the background color.
Both document.body.style.backgroundColor = "#AA0000" and document.body.style.backgroundColor = "red" are valid (although "red" == "#FF0000").
Make sure the if statement runs every time total increases.
Related
I am making a computer game on Twine, which accepts html, javascript, css.
I am trying to display images based on the state of the game.
This code below, works correctly i shows all 3 images overlapping correctly.
However, i want to display other images based on game state. For example if the player is at 20% health, it should display 2a.pgn instead of 2.pgn
or if it is poisoned, it should show 3a.pgn instead of 3.
And so on and so on, it does not make sense having to specify all possible combinations. Instead i just want to change a single layer at a time based on a variable/switch.
<html>
<div class="a1"></div>
<style>
.a1 {
width: 100%;
height: 1000px;
background-image: url(3.png),url(2.png),url(1.jpg);
background-repeat: no-repeat;}
</style>
</html>
Could you please help?
Thank you very much.
Cheers,
There are multiple ways - setting url() (and preloading everything on load), changing visibility, opacity or z-index, but if you want to stick with multiple backgrounds:
//imageIndex - your image for given HP
//imagesLen - images count
var HPimgArr = Array(imagesLen).fill('-9999px 0');
HPimgArr[imageIndex] = '0 0';
document.querySelector('.a1').style.backgroundPosition = HPimgArr.join(', ')
If you are refering to Javascript try this (you need jQuery for this):
var maxHealth = 10;
var health = 10; //He is apparently at full health
function updateHealth(newHealth){
health = newHealth;
if(health < maxHealth / 5) {
var stats = $('.a1').css('background-image').split(','); //Put every different stat in array
stats[1] = 'url(2a.png)';
$('.a1').css('background-image', stats.toString());
}
}
Whenever you want to change his health call updateHealth(...).
I haven't tested this but something along these lines should work.
I'm building a questionnaire that asks 10 questions and keeps a score, called total. I want so that if the total < 10, the screen turns red, however I had to remove the wallpaper that was there previously:
/*body{
background-image: url("twins.jpg");
}*/ <-- which is now a comment
So that this code would work:
if (total < 10){
alert("...RED SCREEN OF DEATH!");
document.body.style.backgroundColor = "#AA0000";
}
So now, when a user scores lower than 10, the screen turns red successfully, however that's now just half of the issue solved.
My next issue is that I want twins.jpg to be my background before the screen turns red, meaning I have twins.jpg as my wallpaper, then when total < 10, screen turns red.
My question is, what is the correct way to do this so that I can still see my background change red when total < 10 ? When I use this:
body{
background-image: url("twins.jpg");
}
It changes the background to twins.jpg, but overlaps the red when it changes colour, therefore I cannot see it.
The best way to solve this would probably be that you create a <div id="redbg"></div> around your content which is the same size than your <body> element (by adding a height and width of 100%).
You then add the background color to the new div:
if (total < 10){
document.getElementById('redbg').style.backgroundColor = "#AA0000";
}
As soon as you want to remove the background color, you could do it by making it transparent:
document.getElementById('redbg').style.backgroundColor = "transparent";
In CSS, properties like background and its properties like it do not override each other. If you set the image, then color, they will not over one each other.
To solve you problem, instead of using "background-image" and "background-color", change them both to just "background" as this will override the other choice.
Let me know if this solves your problem! (COMMENT)
Bryce
I am trying to create a very low specificity css property using javascript. Just like !unimportant (which doesn't exists)
I don't know whether this is possible or not.
My reason to look for something like !unimportant is that I am writing a small javascript plugin. In which I want to add a default style to a element which should be later easily overriden by the user.
But if I write:
element.style.backgroundColor = "green";
The user will not be able to override the above style easily without using !important. So, I added a dynamic style tag by using the following code:
var style = document.createElement('style');
// WebKit hack :(
style.appendChild(document.createTextNode(""));
document.head.appendChild(style);
and then to the above code, I added a dynamic stylesheet using the following code:
var element = document.getElementById('main');
// To use attribute names to apply the styles
element.setAttribute('custom-el', '1');
var sheet = style.sheet;
var properties = "background-color: green;";
var elName = "[custom-el]";
if (sheet.insertRule) {
sheet.insertRule(elName + "{" + properties + "}", 0);
} else if (sheet.addRule) {
sheet.addRule(elName, properties, 0);
}
Now the background-color: green can be overriden by using the following code:
div.main {
background-color: red;
}
But as you can see in css, I used higher specificity to override background-color: green i.e div + .green.
But I want the overriden to happen even when user writes the following css:
.main{ /* Could be simple class name or id name or even tag name */
background-color: red;
}
Fiddle
This might seems to be a small issue. but it is a big problem for me. Please help.
I would simply write like this:
element.style.backgroundColor = element.style.backgroundColor || "green";
Where, if backgroundColor is undefined then it uses green as backgroundColor else it would take the backgroundColor from stylesheet.
Finally I got the answer..
document.head.insertBefore(style, document.head.children[0]);
I should just insert the dynamic stylesheet above already present stylesheets in the head tag.
Working Fiddle
Unfortunately, this is not working in any IE version. I am still looking for answer.
I want to change image height only when its src is not empty
with JQuery or JavaScript , i have an image that have fixed height and in chrome they always keep blank place for it even when there is no source for it i want show this height only when image have source
jQuery is not necessary, just use css to define a zero height for images with an empty src attribute:
img[src=""] {
height: 0
}
If you want to use javascript instead of CSS, you can try calling this function whenever you want to check if the image has a source / display the image.
Set an ID for your image and then:
function check()
{
if (document.getElementById("yourimgidhere").src == "")
{
document.getElementById("yourimgidhere").style.display = "none";
}
else
{
document.getElementById("yourimgidhere").style.display = "inline";
}
}
The CSS method is far more effective and is the proper way of doing it as other people have answered, but this should work too.
You can use
img[src=""] {
display: none;
}
You can change the height or not display it..
What is the difference between the two?
document.body.background refers to the deprecated background attribute of the body tag
http://www.w3schools.com/TAGS/att_body_background.asp
document.body.style.backgroundImage refers to the CSS background-image property of the body tag. It is equivalent to something like...
body {
background-image:url('paper.gif');
}
Use the latter :-)
There's a third important entry to consider in addition to the depracated document.body.background and the way to change the CSS background image with document.body.style.backgroundImage.... You can use document.body.style.background to change all the background properties, including color image and repeat:
document.body.style.background = "red";
or, to set more than one property
document.body.style.background="#0000FF url(example.jpg) repeat-x";
The above sets a background color, a background image, and sets a horizontal repeat for that image.
This is similar to the CSS:
body {
background:#0000FF url('example.jpg') repeat-x; }
( here's a little more info about document.body.style.background at W3Schools... I'm sure there's more complete info elsewhere though )
document.body.background: You are not using CSS.
document.body.style.backgroundImage: you are setting using CSS.