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/
Related
first of all: I‘m not a coder!
I want to inject a dynamic h1 based on page title on a webpage.
Example: <title>Garden</title>
Now I need this as H1 class - I want to include this H1 after a given div class <div class="teaser"></div>
It is may totally simple and I already read some stuff but i don‘t get it…
Fairly trivial
window.addEventListener('DOMContentLoaded', function() {
const h1 = document.createElement('h1')
h1.innerHTML = document.title;
document.querySelector(".teaser").insertAdjacentElement("afterend", h1)
})
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Garden</title>
</head>
<body>
<div class="teaser">Teaser</div>
</body>
</html>
I would like to make my navbar dynamic so that when I am on that selected page the class active is added.
I know I can do as bellow, however, is there a simpler way even with Javascript so that I don't need to copy and paste a bunch of times?
(maybe with a different class?)
$a='home';
<nav>
home
</nav>
this is a JavaScript salutation:
<!doctype html>
<html>
<head>
<style>
.active {
color: red;
}
</style>
</head>
<body>
Curent Page
Difrent Page
Difrent Page
<script>
var navClass = document.getElementsByClassName("nav-item");
var path = window.location.href;
for (i = 0; i < navClass.length; i++) {
if (path.includes(navClass[i].href)) {
navClass[i].classList.add("active");
}
}
</script>
</body>
</html>
it takes the content of the href and sees if it is included in curent url if yes it adds a class
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")
I cannot get my javascript to run. I have added several different options, and removed them, I have had the function in the and now moved it to the . No matter what I try the button does not work. I am trying to learn javascript. It doesn't seem that difficult to learn, but If I can't test it, what is the use? Please help!
<!DOCTYPE HTML>
<html>
<head>
<meta charset=utf-8 />
<title>Change Paragraph Text</title>
</head>
<body>
<p id ="text">I’m going to change this text, I hope.</p>
<button type="button" onclick="js_style()">Click on Me</button>
<script>
function js_style() {
'use strict';
//font styles added by JS:
document.getElementById("text").style.color="purple";
document.getElementById("text").style.fontSize="18pt";
document.getElementById("text").style.fontFamily="Comic Sans MS";
}
document.getElementById("text").innerHTML = js_style();
</script>
</body>
</html>
The code you present throws undefined on the text you want to change. Simply remove
document.getElementById("text").innerHTML = js_style();
and everything should work, I suppose. Here is an example:
https://jsfiddle.net/nmLrpvhy/
The issue is that you have this line:
document.getElementById("text").innerHTML = js_style();
running automatically (because it's outside of your function) and changing the text immediately, so clicking the button does work, but it's just setting the same styles that were already set.
Additionally, innerHTML is for setting the "content" of an element, not its style. In your case, that line attempts to set the return value from the js_style function as the value for the innerHTML. But, the function doesn't return a value - - it only concerns itself with modifying styles.
Don't use inline HTML event attributes (onclick, etc.). See here for why. Instead, do all your work in JavaScript.
<!DOCTYPE HTML>
<html>
<head>
<meta charset=utf-8 />
<title>Change Paragraph Text</title>
</head>
<body>
<p id ="text">I’m going to change this text, I hope.</p>
<button type="button">Click on Me</button>
<script>
// get a reference to the button
var btn = document.querySelector("[type='button']");
// set up the click event handler
btn.addEventListener("click", js_style);
function js_style() {
//font styles added by JS:
document.getElementById("text").style.color="purple";
document.getElementById("text").style.fontSize="18pt";
document.getElementById("text").style.fontFamily="Comic Sans MS";
}
</script>
</body>
</html>
here is the solution of your code:
the line in which you were trying to get your changed text was actually outside the scope of the 'js_style' function that why nothing was happening when you clink on button.
<!DOCTYPE HTML>
<html>
<head>
<meta charset=utf-8 />
<title>Change Paragraph Text</title>
</head>
<body>
<p id="text">I’m going to change this text, I hope.</p>
<button type="button" onclick="js_style()">Click on Me</button>
<script>
function js_style() {
//font styles added by JS:
document.getElementById("text").style.color = "purple";
document.getElementById("text").style.fontSize = "18pt";
document.getElementById("text").style.fontFamily = "Comic Sans MS";
document.getElementById("text").innerHTML = "Changed Text"; /* this
line should be here if you want to change the text of #text in you
html */
}
/* you were written this line here which out of the scope of
function */
</script>
</body>
</html>
Can you try:
<script type="text/javascript">
instead of just
<script>
?
try with onclick="js_style">:
<!DOCTYPE HTML>
<html>
<head>
<meta charset=utf-8 />
<title>Change Paragraph Text</title>
</head>
<body>
<p id ="text">I’m going to change this text, I hope.</p>
<button type="button" onclick="js_style">Click on Me</button>
<script>
function js_style() {
'use strict';
//font styles added by JS:
document.getElementById("text").style.color="purple";
document.getElementById("text").style.fontSize="18pt";
document.getElementById("text").style.fontFamily="Comic Sans MS";
}
document.getElementById("text").innerHTML = js_style();
</script>
</body>
</html>
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