Change CSS background-color using Javascript - javascript

As the title suggest, I'm trying to change my css background-color using javascript function. To simplify the problem, I write a new code here.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Potato</title>
<style>
#item {
background-color:blue;
color:red;
}
</style>
<script type="text/javascript">
function changeBG(id,color) {
var id = id;
var color = color;
document.getElementById(id).style.background-color = color;
}
</script>
</head>
<body>
<script type="text/javascript">changeBG(item,green)</script>
<div id="item">I am a potato</div>
</body>
</html>
The default background-color is red (as suggested by CSS), then I want to change it to green before I print it. But the code doesn't work. I don't know where the mistake is.

First item needs to be made first:
<div id="item">I am a potato</div>
<script>
//...stuff....
</script>
Then we need to use strings:
changeBG("item","green")
And finally in JavaScript we say backgroundColor other than background-color.

#media print {
#item {
background-color:green;
}
}
Include this in your css. This will solves your problem while printing.

All css properties in javascript are camelCased rather than spinal-cased
document.getElementById('youElement').style.backgroundColor = 'color';

Use jQuery
$("#item").css("background-color", "green");
Documentation
Or pure JavaScript
document.getElementById("item").style.backgroundColor = "green";
Documentation

Related

js: element.className does not work (create a dark mode)

I want to change the css properties of many html objects (but in this example I only took body to simplify. My goal is to display dark mode if the current mode is light, or display light mode if current mode is dark.
My javascript function does not work.
debug.html:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="debug.css">
<script src="darkmode.js"></script>
</head>
<body id="bodyElem" class="my-body light-mode">
<h1>Settings</h1>
<p>Dark mode:</p>
<button type="button" onclick="invertMode()">click</button>
</body>
</html>
debug.css:
.my-body.light-mode{
background-color: yellow;
}
.my-body.dark-mode{
background-color: black;
}
darkmode.js:
function invertMode() {
var body = document.getElementById("bodyElem");
var currentClass = body.className;
body.className = currentClass == "dark-mode" ? "light-mode" : "dark-mode";
}
You will need to add an ID for the <body> tag to be able to find it using your code.
<body id="bodyElem" class="light-mode">
and access it using:
var body = document.getElementById("bodyElem");
If you need to access mutiple elements, you can use their CSS class name like:
document.getElementsByClassName("CLASSNAMEHERE");
then loop them all to apply the changes you need.
you will be using .classList.remove("CLASSNAME") to remove single class and .classList.add("CLASSNAME") to add single class to DOM element
Here is a complete sample fiddle:
https://jsfiddle.net/j3o8Lt5k/1/

Why the JavaScript function doesn't work?

If you click the button, it should have showed, but it doesn't.
Is any wrong here?
I have written many JavaScript files in this way, and tried many ways like changing the position of JavaScript code anywhere. But all the files I wrote don't work
Thanks in advance!
An instance :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Debug</title>
</head>
<style>
.debug {
display : none;
}
</style>
<body>
<div class = "debug">
<p>Welcome!</p>
</div>
<button class = "show" onclick = "JavaScript : show();">Show</button>
<script type = "text/JavaScript">
function show() {
document.querySelector("debug").style.display = "flex";
}
</script>
</body>
</html>
Thanks to all of you!
About .querySelector()
The Document method querySelector() returns the first Element within the document that matches the specified selector. [...] The selector is a CSS selector string.
- MDN web docs
You should, therefore, put in your code:
document.querySelector(".debug")
You can also select HTML elements by their tags, for example, you want to select the first div:
document.querySelector("div")
document.querySelector("div").style.color = "lightgreen"
<div>Hello World</div>
Imagine you had your own HTML tag: <hello>, then you can select all hello elements with:
document.querySelector("hello")
document.querySelector("hello").style.color = "lightblue"
<hello>Hello World</hello>
Side note on inline eventListeners
Also in HTML for inline event listener instead of:
<button class = "show" onclick = "JavaScript : show();">Show</button>
you can simply write:
<button class = "show" onclick = "show();">Show</button>
It is recommended to use JavaScript to initiate these eventListeners instead of having them inline inside your HTML markup. Use the .addEventListener() method:
document.querySelector(".show").addEventListener('click', show)
↑ ↑
event function
type
Back to your code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Debug</title>
</head>
<style>
.debug {
display : none;
}
</style>
<body>
<div class = "debug">
<p>Welcome!</p>
</div>
<button class ="show">Show</button>
<script type = "text/JavaScript">
document.querySelector(".show").addEventListener("click", show)
function show() {
document.querySelector(".debug").style.display = "flex";
}
</script>
</body>
</html>
Last thing
Also it's better to keep HTML, JavaScript and CSS all in separate files, for instance:
- index.html
- style.css
- script.js
And call the CSS and JavaScript files in your HTML file with the link (preferably inside <head>) and script (at the bottom of <body>) tags:
<link rel="stylesheet" type="text/css" href="style.css">
And
<script src="script.js"></script>
For class selector you need to add a dot (.) e.g. .debug
Also, in HTML, you can simply have onclick as onclick="show();"
function show() {
document.querySelector(".debug").style.display = "flex";
}
.debug {
display: none;
}
<div class="debug">
<p>Welcome!</p>
</div>
<button class="show" onclick="show();">Show</button>
You were not passing class to querySelector. Set ".debug" instead of "debug".
Below is working code:
function show() {
document.querySelector(".debug").style.display = "flex";
}
.debug {
display: none;
}
<div class="debug">
<p>Welcome!</p>
</div>
<button class="show" onclick="JavaScript : show();">Show</button>
queryselectors requires . and # for class and ID selector:
querySelector(".debug")

Add Class not working even in document ready

the add class is not working even if it is in document ready. I tried both with document ready and without it. it is not working but alert is working.
var $jbanner = jQuery.noConflict(true);
if ($jbanner(window).width() < 1200) {
alert("Less than 1200");
$jbanner("#wad").addClass("hide");
}
other code
var $jbanner = jQuery.noConflict(true);
$jbanner(document).ready(function () {
if ($jbanner(window).width() < 1200) {
alert("Less than 1200");
$jbanner("#wad").addClass("hide");
}
})
With document ready function even the alert box is not working. is it conflicting with other jquerys in the page.
#wad is an image
<img id="wad" src="images/banner.jpg"/>
thanks
ok this should be pretty easy, but not working for me. I just pasted what i am trying to do in a separate html file. but still not working, any help is appreciated.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.js"></script>
<script type="text/javascript">
var $jbanner = jQuery.noConflict(true);
if ($jbanner(window).width() < 1200) {
alert("Less than 1200");
$jbanner("#wad").addClass("hide");
}
else {
alert("greater than 1200");
$jbanner("#wad").addClass("show");
}
</script>
<style type="text/css">
.hide{display:none;}
.show{display:block;}
</style>
</head>
<body><div>
<div id="wallpaperad">
<a href="http://www.yaho.com" target="_blank" rel="nofollow">
<img src="http://www.placehold.it/160x160" alt="banners" id="wad" /> </a>
</div>
</div>
</body>
</html>
I am just trying to create a floating banner ad. that hides for smaller screen sizes.
Try to without jbanner.
$("#wad").addClass("hide");

Trying to make animated nav bar in Jquery

Im attempting to make a navigation bar with Jquery. the idea is that you click on the navigation button and several links(in the form of divs) will slide out. However, i am unable to get the initial click action to work. Currently im just trying to move the #Home button to the left 100px after you click the #clickme button.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src = "jquery-2.0.1.js"></script>
<script>
$("#clickme").click(function(){
$("#Home").animate({left: 100} , "fast");
});
</script>
<style type="text/css">
#Nav {
position:absolute;
width:200px;
height:115px;
z-index:1;
top: 268px;
left: 530px;
background-color: blue;
}
.Button{
position:absolute;
width:200px;
height:115px;
z-index:0;
background-color:#693;
}
</style>
</head>
<body>
<div id="Nav">
<div id="Home" Class = "Button">Home</div>
<div id="About" Class = "Button">About The Internship</div>
<div id="Meet" Class = "Button">Meet the Interns</div>
<div id="Request" Class = "Button">Request an Intern</div>
<div id="clickme" Class = "Button">Navigation</div>
</div>
</body>
</html>
You have to wait 'till your dom is ready + you've the wrong selector.
.ID is for Classes (css)
#ID is for actual ID's
$(function(){
$("#clickme").click(function(){
$("#Home").animate({left: 100} ,"fast");
});
})
This should work..
In addition to stackErr's answer:
'fast' should be passed as a string.
fiddle: http://jsfiddle.net/jonigiuro/xt57a/
$("#clickme").click(function(){
$("#Home").animate({left: 100} ,'fast');
}
the problem seems to be with the selector. id must be used with # not with .
try
$("#clickme").click(function(){
$("#Home").animate({left: 100} ,fast);
});
you can place this code at the bottom before </body> using scripts at the bottom of the page makes page faster & executes when dom is ready. otherwise wrap the codde with $(function())
Your id selector is incorrect.
Your code should be:
$("#clickme").click(function(){
$("#Home").animate({left: 100} ,'fast');
});
this shouldnt matter but script tag should have the type attribute since you are not using HTML5:
<script type="text/javascript" src="jquery-2.0.1.js"></script>

Javascript doesn't change document?

Take a look at this example code, which doesn't work:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
<!--
function moveMe() {
document.getElementById('moveme').top = 200;
document.getElementById('moveme').style.backgroundcolor = 'green';
document.getElementById('writeme').innerHtml = 'abc';
alert('called!');
}
// -->
</script>
<style type="text/css">
.moveable {
position: absolute;
top: 30px;
left: 200px;
width: 100px;
height: 100px;
background-color: yellow;
}
#writeme {
background-color: red;
color: white;
}
</style>
</head>
<body>
<div id="moveme" class="moveable" onClick="moveMe()">
<p id="writeme">Hello!</p>
</div>
</body>
</html>
When I click on the text the alert is displayed, but nothing is changed in the document. The paragraph text is not overwritten, the div is not moved... tested it in FF and IE, also checked the DOM via Firebug: strange thing is that the new values are written to the nodes, but they are displayed in bold, and the old values are still there. WTF?
I guess I'm missing something fundamental here.
Non-zero lengths require units, "200" is missing its unit
JavaScript is case sensitive: backgroundColor and innerHTML
Since you appear to be using XHTML, your script is commented out
document.getElementById('moveme').top = 200;
needs to be
document.getElementById('moveme').style.top = "200px";
I think; and
document.getElementById('writeme').innerHtml = 'abc';
needs to become
document.getElementById('writeme').innerHTML = 'abc';
and it's backgroundColor with a capital C as #David spotted first.
Try this:
<script type="text/javascript">
function moveMe() {
document.getElementById('moveme').style.top = '200px';
document.getElementById('moveme').style.backgroundColor = 'green';
document.getElementById('writeme').innerHTML = 'abc';
alert('called!');
}
window.onload = moveMe;
</script>
Additionally to what the others said: Drop the <?xml version='1.0' encoding='UTF-8' ?>
, because that puts IE in Quirksmode.

Categories

Resources