Basic CSS manipulation using JavaScript - javascript

I'm currently learning JavaScript, but I'm very weak on the fundamentals. I'm trying to write a function that changes the background color when a link is clicked, can you please advise me on what I'm doing wrong?
<head>
<script type="text/javascript">
function change()
{
var abra = document.getElementbyId("body").style;
abra.background-color = "black";
}
</script>
</head>
<body>
<div id="body" style="background-color: red;">
Test
sdfdsfsdfds
</div>
</body>
EDIT: For clarification, I was trying to change the background color of the DIV "body".

The property you're looking for is backgroundColor:
abra.backgroundColor = "black";
In general, Javascript uses the corresponding camelCase for CSS style properties. See a list of some properties for examples.

Instead of
var abra = document.getElementbyId("body").style
abra.background-color = "black";
try
document.body.style.backgroundColor = "black";
document.getElementbyId("body")
looks for an element with ID body, and
abra.background-color
is the same as
(abra.background) - color
which will probably result in an error telling you there is no var named color.

use camelCase:
background-color => backgroundColor
var abra = document.getElementById("body").style;
abra.backgroundColor = "black";
But if you want the body tag use:
document.getElementsByTagName("body")[0]
or
document.body // recommended

Related

created element not styling with current JS code

I created an element in JS to be displayed on the html web page. I am not seeing why the styling is not working properly. Maybe someone would be so kind as to point out any error I may have made. Thank you.
///HTML
<!DOCTYPE html>
<html>
<head>
<title>WEB 115 Final Project</title>
</head>
<body>
<script src= "projectJS.js"></script>
</body>
</html>
///JS
var elemH1 = document.createElement("h1");
elemH1.style.color = "red";
elemH1.style.fontFamily = "Tahoma";
elemH1.style.textAlign = "center";
document.write("<h1>Kent Butler</h1>");
var elemH2 = document.createElement("h2");
elemH2.style.fontFamily = "Garamond";
elemH2.style.color = "red";
elemH2.style.fontStyle = "italic";
elemH2.style.textAlign = "center";
document.write("<h2>WEB 115.0001</h2>");
I am looking for the text to styled red and with the specified font families, etc. Thank you.
you need to set the text on your elements and then add them to document.body
var elemH1 = document.createElement("h1");
elemH1.style.color = "red";
elemH1.style.fontFamily = "Tahoma";
elemH1.style.textAlign = "center";
elemH1.innerText = "Kent Butler";
document.body.appendChild(elemH1);
//document.write("<h1>Kent Butler</h1>");
var elemH2 = document.createElement("h2");
elemH2.style.fontFamily = "Garamond";
elemH2.style.color = "red";
elemH2.style.fontStyle = "italic";
elemH2.style.textAlign = "center";
//document.write("<h2>WEB 115.0001</h2>");
elemH2.innerText = "WEB 115.0001";
document.body.appendChild(elemH2);
The problem is that you're creating the element and setting it's properties but you're not actually using them. Instead, you are creating a whole new element without any style attached in document.write("<h1>Kent Butler</h1>")
Also, you should consider putting the styling in a CSS file instead of hard coding it with JS.

onmouseover function Javascript for changing the background of a section

I was trying to write a function that changes the color of background of a section by going over it with the mouse - using 'onmouseover'. I was looking for similar question and tried the solutions that was offered but it did not work on my code.
Here is what i did:
function Rectangle(count){
var newRec = document.createElement("SECTION");
newRec.style.width="202px";
newRec.style.height="312px";
newRec.style.border="1px solid #3f3f3f";
newRec.style.background = "#FFFFFF";
newRec.style.display = "inline-block";
newRec.style.margin= "44px";
newRec.style.size= "50px";
var appendRec = function() {
document.addEventListener("onmouseover", myFunction);
document.getElementsByTagName('main')[0].appendChild(newRec);
};
function myFunction() {
document.getElementTagName("SECTION").style.background = "#000000";
};
appendRec();
};
Can anyone tell me what i did wrong?
And I was trying to work with the console but this code doesn't say anything is wrong...
document.getElementTagName("SECTION").style.background = "#000000"; is wrong.
First, it's called getElementsByTagName(). And second, it returns an array, not just one element.
Solution: Give the <section> an id and use getElementById() instead.
You just need
document.getElementById('WhichElementWillBeHoveredID').onmouseenter = function() {
// when entering element...
}
document.getElementById('WhichElementWillBeHoveredID').onmouseleave = function() {
// when leaving element
}
Sure... you can easily use CSS as well..
SELECTOR:hover { background-color: #444 }
I created a fiddle to change background color and this is the only requirenment then I think it is good
http://jsbin.com/cagawa/edit?html,css,output
#mydiv{
background: #cccccc;
}
#mydiv:hover{
background: #ffdd00;
}
try change
var appendRec = function() {
document.addEventListener("onmouseover", myFunction);
document.getElementsByTagName('main')[0].appendChild(newRec);
};
to
var appendRec = function() {
document.getElementsByTagName('main')[0].appendChild(newRec);
newRec.addEventListener("mouseover", myFunction);
};
I edited littlebit code, try now :)
If im not wrong on line 12:
document.addEventListener("onmouseover", myFunction);
should be replaced by
document.addEventListener("onmouseover",myFunction());

Event listener not working?

Sorry for so many questions, but I suck at javascript and want to get good at it. I'm trying to make a page change colors when you press a button as another proof of concept for me, but it's not working and I'm not entirely sure why...
<html>
<head>
</head>
<body>
<button Id="BGchange">BUTTON!</button>
<script type="text/javascript">
button.eventlistener(BGchange, BGcolor());
function BGcolor (){
var BG = BG2+1
var BG2 = BG
if(BG==0){
document.body.style.background = white;
}
else
if(BG==1){
document.body.style.background = black;
}
}
</script>
</body>
</html>
k, fixed a little, here's what I have now:
<html>
<head>
</head>
<body>
<button Id="BGchange">BUTTON!</button>
<script type="text/javascript">
BGchange.addEventListener("click", BGcolor);
var BG++
function BGcolor (){
if(BG==0){
backgroundcolor = "white";
}
else
if(BG==1){
backgroundcolor = "black";
}
}
</script>
</body>
</html>
If you're trying to listen for an event click, then you need something like this:
document.getElementById("BGchange").addEventListener("click", BGcolor);
Then, you need to fix some things in this function:
function BGcolor (){
var BG = BG2+1
var BG2 = BG
if(BG==0){
document.body.style.background = white;
} else if (BG==1) {
document.body.style.background = black;
}
}
Because you are trying to reference BG2 before it has been initialized so it is not clear what you want to be doing there.
In order, the things I changed:
Get the DOM element for the button with document.getElementById()
Use addEventListener() which is the standard way of adding event handlers
Change to the click event which is what buttons create when you click on them
Pass just a reference to the event handler as BGcolor without the parens. You were calling it immediately rather than passing a reference to the function that can be called later.
In addition, a bunch of things to fix in your BGcolor() function:
Variables that remember their state from one function call to the next must be declared outside that function.
A color value is a string so you would use "white", not white.
To change just the background color, it's best to use the backgroundColor property.
Here's a working version:
<button Id="BGchange">BUTTON!</button>
<script type="text/javascript">
document.getElementById("BGchange").addEventListener("click", BGcolor);
var curColor = "white";
function BGcolor (){
if (curColor == "white") {
curColor = "black";
} else {
curColor = "white";
}
document.body.style.backgroundColor = curColor;
}
</script>
Working demo: http://jsfiddle.net/jfriend00/Nk2N5/

How to make a div's background color randomly change when the page refreshes

this is my first question here so excuse me if I did anything wrong.
I'm doing the layout of a website and I want the header to change colors randomly when the user refresh the page. I already did some research and got these javascript codes:
<script type="text/javascript">
var randnum = Math.random();
var inum = 2;
var rand1 = Math.round(randnum * (inum-1)) + 1;
var colors = new Array;
colors[1] = "#385c78";
colors[2] ="#9d302f";
var color = colors[rand1]
document.getElementById('navbar').style.backgroundColor = image;
</script>
This one goes inside the head tag. It picks a random hexadecimal code between the two ones I want and store it on the var color.
The second one I'm using goes on the body.
<script type="text/javascript">
//writes "<div id="header" style="background-color:#something">"
document.write('<div id="header" style="background-color:' + color + '">')
</script>
<!-- continuation of div id="navbar" -->
*Header code here*
</div>
The problem is that this way of doing it is giving me some troubles, since the div id="header" is written inside javascript. I can't wrap other divs properly and Google Chrome's inspect element tells me that the body size is 1333px x 80px (as it can be seen here http://puu.sh/2yjKi), exactly and only the header size, and it doesn't wraps the rest of the website content.
So my question is: Is there any way to improve that code? Make the background color of that div change via javascript or something like that?
I thank you all in advance for reading and appreciate your help.
Though the post is little old but my answer may help others who would land here just like me!!
DEMO
HTML:
<div style="height:150px">
<div>
<h1><center>That's how i change color!!</center></h1>
</div>
<br><br>
<div class="bordered" id="fancy">
<center>I behave like a chameleon!!</center>
</div>
</div>
JS:
setInterval(function () {
document.getElementById("fancy").style.background= '#'+Math.floor(Math.random()*16777215).toString(16);
document.body.style.background= '#'+Math.floor(Math.random()*16777215).toString(16);
}, 1000);
Hope this would help someone!!
Output your header as normal HTML, and then use JavaScript to update the color onDomReady. Something about like this:
$(document).ready(function() {
var colors = ["#385c78", "#9d302f"],
selectedColor = colors[Math.floor(Math.random()*colors.length)]
header = $("div#header");
header.css("background-color", selectedColor);
});
http://jsfiddle.net/ryanbrill/GD3qB/
function changecolor() {
var colors = ["#B40404", "#0000FF", "#FE2E9A", "#FF0080", "#2EFE2E", ];
var rand = Math.floor(Math.random() * colors.length);
$('#controls-wrapper').css("background-color", colors[rand]);
setTimeout('changecolor()', 1000);
}

What is the syntax for document.body.style.backgroundColor?

I am a JavaScript newbie. I have the following code and it is behaving very strangely. What it is supposed to do is originally set the background color to red, then cycle through a series of background colors after an alert dialogue is cleared. Color names are currently in string formats, but the same behavior results if I use the hex IDs.
Usually, when the page is loaded, it starts off coloring the body red like it is supposed to. The first alert clear sometimes changes the background to orange, sometimes not, then there is no change as the next dialogues (yellow, green, blue, indigo, black) are cleared until the last color change, which sometimes takes and sometimes doesn't.
<html>
<head>
<title>Color Flasher</title>
</head>
<body>
<script type="text/javascript">
function color1() {
document.body.style.backgroundColor = 'red';
}
function color2() {
document.body.style.backgroundColor = 'orange';
}
function color3() {
document.body.style.backgroundColor = 'yellow';
}
function color4() {
document.body.style.backgroundColor = 'green';
}
function color5() {
document.body.style.backgroundColor = 'blue';
}
function color6() {
document.body.style.backgroundColor = 'indigo';
}
function color7() {
document.body.style.backgroundColor = 'black';
}
function color8() {
document.body.style.backgroundColor = 'violet';
}
color1();
alert("ready for another color? - orange");
color2();
alert("ready for another color? - yellow");
color3();
alert("ready for another color? - green");
color4();
alert("ready for another color? - blue");
color5();
alert("ready for another color? - indigo");
color6();
alert("ready for another color? - black");
color7();
alert("ready for another color? - violet");
color8();
</script>
<center>
<h1>Color Flasher<br></h1>
</center>
<hr>
</body>
</html>
Can someone explain where I'm getting the syntax wrong?
You should try placing your <script> in the <head> or if you really want your script in the body tag, you should place before the closing </body> tag.
FYI it works fine on my side. Tested on JSFiddle and they automatically place the <script> in the body tag.

Categories