JavaScript in HTML changing background - javascript

I have no idea what I am doing. I thought I had everything going well with html, then I had to add some simple javascript.
I am just trying to change the background color when the user clicks a button.
This is what I have so far:
CSS
body {
background-color:grey;
}
Javascript
function changeBackground() {
if (document.body.style.backgroundColor = 'grey')
{
document.body.style.backgroundColor = 'black';
}
else
{
document.body.style.backgroundColor = 'grey';
}
}
Html
<button type="button" onclick="changeBackground()">
Click Me!
</button>

Your if clause is wrong (you are assigning instead of testing the background color):
function changeBackground() {
if (document.body.style.backgroundColor == 'grey'){
document.body.style.backgroundColor = 'black';
} else {
document.body.style.backgroundColor = 'grey';
}
}

Richard, I'll offer an alternative to all of the other answers - and you should consider the following structure in all web front-end that you develop.
HTML is what you display, JS is how it behaves, CSS is how it is styled.
That said, try to avoid styling elements with JS but rather toggle a class and allow CSS to do the work. In your case, you could write:
function changeBackground()
{
$(body).toggleClass('dark');
}
<button type="button" onclick="changeBackground()">
Click Me!
</button>
body
{
background-color: grey;
}
body.dark
{
background-color: black;
}
Here, we're simply toggling a class on and off the body element, the CSS will 'respond' accordingly. We have a nice clear separation of concerns.
You may choose your class name to make more sense than dark, but the idea is your JS doesn't care about colors and details of styling.

Try:
$("button").click(function(){
$("body").css("background-color", "blue");
});

Try the FIDDLE,
The problem is you are using assignment operator = instead of comparison operator == or ===
function changeBackground() {
if (document.body.style.backgroundColor == 'grey') {
document.body.style.backgroundColor = 'red';
} else {
document.body.style.backgroundColor = 'grey';
}
}
Hope this works for you

Related

Change Color onClick

I am trying to change the color of an element using .style.color and it isn't going very smoothly. My goal is for it to change red and then blue on clicks. Any recommendations?
var turns = 0;
function dot_01() {
if (turns === 0) {
turns++;
document.getElementById("dot_01").style.color = 'red';
} else if (turns === 1) {
turns--;
document.getElementById("dot_01").style.color = 'blue';
}
}
<div class="dot" id="dot_01" onclick="dot_01()"></div>
You want to use .style.backgroundColor to change the button color. .color is going to change the font color.
<input type="button" value="Click Me" onclick="this.style.backgroundColor = '#000'; this.style.color = '#FFF';" />
If you mean to change the background color try style.backgroundColor like the following way:
document.getElementById("dot_01").style.backgroundColor = 'red';
function dot_01(el) {
if (el.style.backgroundColor === 'red') {
el.style.backgroundColor = 'blue';
}
else el.style.backgroundColor = 'red';
}
<div class="dot" id="dot_01" onclick="dot_01(this)">Container</div>
I'm using this to change styling, it's a very simple JavaScript that changes the display and height properties of the CSS to show / hide a container.
Sorry I haven't changed it to your desired outcome yet but I hope this helps, just modify it to change the color by doing something like:
style="color:red"
https://jsfiddle.net/raydekker/u821a84d/
style="color:red";

Calling JS Function on Button Click Blocks CSS :hover

I implement a CSS hover method on all of my buttons. It looks like this:
.button:hover { background-color: #36a39c; }
This method works perfectly fine until I click on one of my buttons. When the button is clicked, a JS function is called using this code:
<div id= "one"><button class="button" id = "b1" value="0" onclick="checker(this.id)"></button></div>
This is the JS Script:
var checker = function(id)
{
var xyz = id;
var value = document.getElementById(xyz).value
if (answerjson[value].is_right_choice==1)
{
for (var i = 1; i <=4; i++) {
document.getElementById("b"+i).style.background='#722F37';
}
document.getElementById(xyz).style.background='green';
setTimeout(function(){ alert("Correct!"); }, 100);
}
else {
for (var i = 1; i <=4; i++) {
document.getElementById("b"+i).style.background='#722F37';
}
document.getElementById(xyz).style.background='red';
setTimeout(function(){ alert("Sorry, Try Again"); }, 100);
}
}
After that script is called, my buttons no longer change color on hover. Any ideas why?
This happens because when you add background color using javascript it is added as inline styling and it overrides the css class selector because inline styling always takes more preference. You need to make a class with that color and add/remove that using javascript. e.g. make a class
.green{
background-color: green;
}
and then add it using javascript like this:
document.getElementById(xyz).className += " green";
You're setting the inline style="" attribute in your JS code.
Properties set in inline styles always override CSS selectors (except with !important), so your CSS no longer does anything.
You should add a CSS class instead of setting an inline style.

javascript .style property of span tag in anchor tag not working as expected

I am trying to style some buttons for my website
This is my html
<div>
<a class="page_numbers"><span>100</span></a>
<a class="page_numbers"><span>2</a></span></div>
this is my css
.page_numbers{
display:table-cell;
border:solid;
padding:0px;
border-radius:100px;
width:50px;
height:50px;
text-align:center;
vertical-align:middle;
}
div {
display:table;
border-spacing:10px;
}
}
and finally this is my javascript
var obj=document.getElementsByClassName("page_numbers")
for (i in obj){
console.log(obj[i].children)
obj[i].children[0].style.color="black"
obj[i].style.borderColor="rgb(85,170,255)"
function jun(i){
obj[i].addEventListener('mouseenter',function(){obj[i].style.background="yellow";obj[i].style.color="red"},true)
//
obj[i].addEventListener('mouseleave',function(){
obj[i].style.background="white";
obj[i].style.color="rgb(12,31,22)";},true)
}
jun(i);
}
the background color changes on mouseleave and enter but not the font color...I suppose I am doing something wrong along the way or I am missing a fundamental concept
this is my jsfiddle link
http://jsfiddle.net/repzeroworld/boqv8hak/
advice please..still learning JS
Firstly, all of this should be in CSS and is trivial to do so
.page_numbers:hover
{
background-color: yellow;
}
.page_numbers:hover span
{
color: red;
}
Now the issue you are having is that on about the 4th line of your JS you explicitly set the color of the child element (the span) inside the .page_number element to be black. Now on you mouse enter you are setting the color on the page_number element, but since the child has a style applied directly to it (i.e. color: black) it does not inherit the parent style. Inline styles (i.e. style applied directly to the element with the style="" attribute, which is what JS does) always have the highest precedence. This is why it is generally not best practice to put inline styles on an element, as you have just seen, they are pretty much impossible to override. So change either the child to not have an explicit style, or on the mouse enter change the child not the parent
var obj = document.getElementsByClassName("page_numbers")
for (i in obj) {
console.log(obj[i].children)
obj[i].children[0].style.color = "black"
obj[i].style.borderColor = "rgb(85,170,255)"
function jun(i) {
obj[i].addEventListener('mouseenter', function () {
obj[i].style.background = "yellow";
obj[i].children[0].style.color = "red"
}, true)
//
obj[i].addEventListener('mouseleave', function () {
obj[i].style.background = "white";
obj[i].children[0].style.color = "rgb(12,31,22)";
}, true)
}
jun(i);
}
or
var obj = document.getElementsByClassName("page_numbers")
for (i in obj) {
console.log(obj[i].children)
obj[i].style.borderColor = "rgb(85,170,255)"
function jun(i) {
obj[i].addEventListener('mouseenter', function () {
obj[i].style.background = "yellow";
obj[i].style.color = "red"
}, true)
//
obj[i].addEventListener('mouseleave', function () {
obj[i].style.background = "white";
obj[i].style.color = "rgb(12,31,22)";
}, true)
}
jun(i);
}
but as I indicated all this should really be in CSS
You trying to change color of a instead of span
Try like this
obj[i].children[0].style.color = "red"
JSFIDDLE

Body bgcolor attribute weightage

I have written in css that body will have a blue color but in javascript i have made that body will change color every second, It worked until i added global css. I can't remove the css as it has many rules that i can't unlink. I want a way that all css rules will load but my body color won't get affected.
Screenshot to prove that body bgcolor has been changing by script but not shown:
http://i.gyazo.com/b6a7a0f4c5153c61b38c3552cdcd65fc.gif
Can someone show that how can i include that external global CSS but then also my script can change bgcolor and css will not stop it.
P.S : I am Noob :) !
EDIT:
My Code : http://fiddle.jshell.net/dfywom6a/
Help!
try to use document.body.style.background = color; instead of document.bgColor = color;
That will override global css applied onto body element.
I hope this helps http://jsfiddle.net/ceueqetn/
The bgColor attribute is deprecated. So maybe the CSS rule overrides the color stated in the bgColor attribute.
So, instead of changing bgColor in your JavaScript, consider changing the CSS like this:
var body = document.getElementsByTagName('body')[0];
body.style.setProperty('background-color', 'red');
Here is the updated version of your code.
You need to change your code instead of document.bgColor to this document.body.style.background
Working example here http://fiddle.jshell.net/dfywom6a/42/
function cc() {
window.setInterval("Farbe()", 500);
}
farbe = 1;
function Farbe() {
if (farbe == 1) {
document.body.style.background = "indigo";
farbe = 2;
} else if (farbe == 2) {
document.body.style.background = "red";
farbe = 3;
} else if (farbe == 3) {
document.body.style.background = "orange";
farbe = 4;
} else if (farbe == 4) {
document.body.style.background = "blue";
farbe = 1;
}
}
try to add the !important on your color css.
body {
background: #f00 !important;
}

Changing a button's background color when it's clicked [duplicate]

This question already has answers here:
How do I reference a JavaScript object property with a hyphen in it?
(11 answers)
Closed 8 years ago.
I'm trying to change the background-color property of a button using JavaScript. The script checks what the current background-color is set to and then toggles it.
This is the JavaScript code:
function btnColor(btn,color) {
var property=document.getElementById(btn);
if (property.style.background-color == "#f47121") {
property.style.background-color=Color;
}
else {
property.style.background-color = "#f47121";
}
}
and this is what I pass in html:
<input type="button" id="btnHousing" value="Housing" onclick="toggleLayer('transparent1');btnColor('btnHousing','#fff200');" />
toggleLayer is another function I am using, which works perfectly fine.
I can't seem to figure out why it doesn't work.
Why not just use jQuery?
Core Javascript is so raw!
If you're just changing the background-color then use the on click event in jQuery:
$('#btnHousing').click(function() {
//Now just reference this button and change CSS
$(this).css('background-color','#f47121');
});
Personally for me it reads so much better then raw javascript.
Regards
I made a working example in JsBin : LINK HERE
I renammed the function to setColor
I changed the property property.style.background-color by window.getComputedStyle(property).backgroundColor
Try this function in your javascript :
function setColor(btn,color){
var property=document.getElementById(btn);
if (property.style.backgroundColor == "#f47121") {
property.style.backgroundColor = color;
} else {
property.style.backgroundColor = "#f47121";
}
}
To avoid repeating the id of your input in the onclick attribute, you can do this :
HTML :
<input type="button" id="btnHousing" value="Housing" onclick="toggleLayer('transparent1');btnColor(this, '#fff200');" />
JavaScript (be careful, the var names are case sensitive, cf. Color => color) :
function setColor(btn, color){
if (btn.style.backgroundColor == "#f47121") {
btn.style.backgroundColor = color;
} else {
btn.style.backgroundColor = "#f47121";
}
}
Change your code to this...
function btnColor(btn, color) {
var property = document.getElementById(btn);
if (property.style.backgroundColor == "#f47121") {
property.style.backgroundColor = Color;
} else {
property.style.backgroundColor = "#f47121";
}
}
Hyphenated css attributes are camel cased in JS.
For example background-color becomes -> backgroundColor
The above code should work.

Categories

Resources