I would like to add different colours to different texts. The list of colours that I would like to add is stored in an array. How will I use that array to assign colours to my texts? Please check the code that I have written. The text "hai" is supposed to be in cyan colour. But the output is not as expected.
<!doctype html>
<html>
<body>
<script>
var colors=['blue','cyan','gold','grey','green'];
</script>
<h1 style="color:colors[1]">hai</h1>
</body>
</html>
You should first give your desired element an id then retrieve it through js and style it:
<!doctype html>
<html>
<body>
<script>
window.onload = function() {
var colors = ['blue', 'cyan', 'gold', 'grey', 'green'],
h = document.getElementById('heading1');
h.style.color = colors[1];
};
</script>
<h1 id="heading1">hai</h1>
</body>
</html>
dNitro's solution works. I'm confused why you need to store colors in an array. If you want to provide different colors to different text. The common solution is design different color styles in css and use it in your element. As the code below
<!doctype html>
<html>
<style media="screen">
.cyan
{
color: cyan;
}
.blue
{
color: blue;
}
</style>
<body>
<h1 class="cyan">Hello, </h1>
<h1 class="blue">World</h1>
</body>
</html>
Related
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/
Trying to change color using a variable, console works but color not changing when I click on the square.
Color is the variable I want to use.
I have tried an actual string value and that does not work.
<!DOCTYPE html>
<html>
<head>
<link href="main.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<h1>Test Your Reactions!</h1>
<p>Click on the shapes as fast as you can</p>
<div id="shapes">
</div>
<script>
function myFunction() {
var colour = '#'+((Math.random() * (1<<24)|0).toString(16).slice(-6));
document.getElementById("shapes").style.backgroundColour = colour;
console.log(colour);
}
</script>
</body>
</html>
its backgroundColor not Colour .. you have an extra u
You need to replace backgroundColour by backgroundColor without u :
document.getElementById("shapes").style.backgroundColour = colour;
______________________________________________________^
Must be :
document.getElementById("shapes").style.backgroundColor = colour;
NOTE 1: You need to trigger the function to see the effect and you must also give your target div shapes a width/height so you can see it.
NOTE 2: You must listen on DOMContentLoaded event to make sure all the elements are loaded to the DOM before calling your script.
Working sample:
<!DOCTYPE html>
<html>
<head>
<link href="main.css" rel="stylesheet" type="text/css" />
<style>
#shapes {
width: 100px;
height: 100px;
border: 1px solid #000;
}
</style>
</head>
<body>
<h1>Test Your Reactions!</h1>
<p>Click on the shapes as fast as you can</p>
<div id="shapes">
</div>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var shapes = document.getElementById("shapes");
shapes.addEventListener('click', myFunction, false);
});
function myFunction() {
shapes.style.backgroundColor = "#" + (Math.random() * (1 << 24) | 0).toString(16).slice(-6);
}
</script>
</body>
</html>
Try this
const shapes = document.getElementById("shapes"); // You declare once, then you can reuse
function myFunction() {
var colour = '#'+((Math.random() *(1<<24)|0).toString(16).slice(-6));
shapes.style.backgroundColor = colour;
console.log(colour);
}
shapes.addEventListener('click', myFunction); // I guess you want to click somewhere
<h1>Test Your Reactions!</h1>
<p>Click on the shapes as fast as you can</p>
<div id="shapes">Shapes</div>
Below code gives the expected result. please take it.
<!DOCTYPE html>
<html>
<head>
<link href="main.css" rel="stylesheet" type="text/css"/>
<style>
#shapes {
width: 300px;
height: 300px;
background-color: coral;
color: white;
}
</style>
</head>
<body>
<h1>Test Your Reactions!</h1>
<p>Click on the shapes as fast as you can</p>
<div id="shapes" onClick="myFunction();">
test
</div>
<script>
function myFunction() {
var colour = '#'+((Math.random() * (1<<24)|0).toString(16).slice(-6));
document.getElementById("shapes").style.backgroundColor = colour;
console.log(colour);
}
</script>
</body>
</html>
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>
Maybe what I'm trying to do is impossible, but I'd like to ask before I give up.
I'm editing my blog and would like the background colors of my text posts to change randomly every time the page is visited.
I found this on teamtreehouse.com from a Google search:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf=8">
<style type="text/css">
#posts {
width: 90%;
height: 700px;
margin: auto
}
</style>
</head>
<body onload="return ran_col()">
<div id="posts">
</div>
<script type="text/javascript">
function ran_col() { //function name
var color = '#'; // hexadecimal starting symbol
var letters = ['000000','FF0000','00FF00','0000FF','FFFF00','00FFFF','FF00FF','C0C0C0']; //Set your colors here
color += letters[Math.floor(Math.random() * letters.length)];
document.getElementById('posts').style.background = color; // Setting the random color on your div element.
}
</script>
</body>
</html>
The effect works really well. The problem I'm having with it is that I have multiple #posts divs and it will only generate a random background color for one of the #posts divs. The rest have no background colors.
I would like each #posts div on my site to have a different random color, not the same random color. Is there a way to do that? I'll admit I'm not very good at these sorts of things but once I get an idea in my head I have a hard time letting it go. Any suggestions or tips would be great.
Thanks!
Use the following function:
document.getElementsByClassName("posts").style.background = color;
instead of
document.getElementById('posts').style.background = color;
An Id, must be unique, a class can have multiple items. Maks sure you go change your divs to contain this class instead of the Id you are using.
Example:
<div id="posts">
should be
<div class="posts">
Edit#1:
As per comments below, the css file has has to be changed so that that the IDs become classes. So just change the #posts to .posts
Edit#2:
getElementsByClassName will return an array of the elements, you then have to iterate through them to change the background color with something like this:
var x = getElementsByClassName("posts");
var i;
for(i=0;i<x.length;i++)
{
x[i].style.backgroundColor = color;
}
Edit #3:
This is a final working example of all the above. Try it out. I added a div="page" container that becomes visible at the end of the script so that the divs don't load one after the other.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf=8">
<style type="text/css">
.posts {
width: 90%;
height: 700px;
margin: auto
}
#page{
display:none;
}
</style>
<script>
function ran_col() { //function name
var color; // hexadecimal starting symbol
var letters = ['000000','FF0000','00FF00','0000FF','FFFF00','00FFFF','FF00FF','C0C0C0']; //Set your colors here
var x= document.getElementsByClassName("posts");
var i;
for(i=0;i<x.length;i++)
{
color="#";
color += letters[Math.floor(Math.random() * letters.length)];
x[i].style.backgroundColor = color;
}
document.getElementById("page").style.display = "block";
}
</script>
</head>
<body onload="ran_col()">
<div id="page">
<div class="posts">
test1
</div>
<div class="posts">
test2
</div>
<div class="posts">
test3
</div>
</div>
</body>
</html>
I want to write text with the print () function. I added cufon file. Unfortunately, the text is not displayed. Why? Please help me.
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="jquery.js" type="text/javascript"></script>
<script src="raphael.js" type="text/javascript"></script>
<script src="harabara.cufonfonts.js" type="text/javascript"></script>
</head>
<body>
<script>
window.onload = function() {
var r = new Raphael('holder', 640, 480);
var font1 = r.getFont("Harabara");
var text1 = r.print(10,100, "click me", font1, 48).attr({"stroke-width": 3, fill: "red", "stroke": "blue"});
};
</script>
<style type="text/css">
#holder { width: 640px; height: 480px; border: 2px solid #aaa; }
</style>
<div id="holder"></div>
</body>
One thing I see right away:
var text1 = r.print(10,100, "click me", font1, 48).attr({"stroke-width": 3, fill: "red", "stroke": "blue"});
returns a Raphael path object. So you need to assign that path to your Raphael paper.
Paper.print() Creates path that represent given text written using
given font at given position with given size. Result of the method is
path element that contains whole text as a separate path.
http://raphaeljs.com/reference.html#Paper.print
Have not tested it yet, but just leaving the code the way you wrote will not print anything to the paper.
One more thing: keep your style tags in your header.