Toggle between pool of classes in Javascript - javascript

How to use vanilla JavaScript or jQuery to toggle between two classes is a question, that has been asked and answered many times on stackoverflow and other websites.
What I haven't found though is a solution to use the onclick event to toggle between a pool of classes.
What I want to achive is this:
I have a body element with the class "yellow".
When clicking a button, I want this class removed from the body and replaced with the class "green". Clicking the button again should change the class to "red" and next time to "blue" and finally back to "yellow" and so on.
Any ideas are much appreciated.

Here's a simple answer, you can modify it so you push or pop more classes into the array and so on.
var classes = ["yellow", "green", "red"];
var button = $("#changeColor");
var count = 1;
button.on("click", function(){
$("#foo").removeClass();
$("#foo").addClass(classes[count]);
count++;
if(count > 2){
count = 0;
}
});
.yellow {
background-color: yellow;
}
.red {
background-color: red;
}
.green {
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo" style="width: 200px; height: 50px;" class="yellow">
FOO
</div>
<button id="changeColor">CHANGE</button>

Have a look at below snippet. Please note, in pool all colors should be unique otherwise you have to create an extra variable to track the index of applied color.
var pool = ['yellow', 'green', 'red', 'blue']
var body = document.getElementsByTagName('body')[0];
body.style.backgroundColor = 'yellow';
function changeColor() {
var bodyColor = body.style.backgroundColor;
var appliedIndex = pool.indexOf(bodyColor);
if (appliedIndex === pool.length - 1) {
body.style.backgroundColor = pool[0];
} else {
body.style.backgroundColor = pool[appliedIndex + 1];
}
}
<button id="change" onClick="changeColor()">Change</button>

Related

How to change background color using .getElementsByClassName in JavaScript?

No matter how I try it, I can't make it work. If I use .getElementById, it works... but I need to target multiple divs so I need to use .getElementsByClassName.
Here's what I have so far:
function changeBgColor(color){
document.getElementById("background1").style.background = color;
}
function changeBackground(color){
document.getElementsByClassName("pls-work").style.background = color;
}
#background1{
background: #c0c0c0;
padding: 50px;
color: #fafafa;
}
.background2{
background: #ff7f50;
padding: 20px;
}
.background3{
background: #555;
padding: 20px;
}
<h4>First example</h4>
<div id="background1"><p>My background color will change.</p></div>
<button onclick="changeBgColor('#222');">This function will work, no problem</button>
<br><br>
<h4>Second example</h4>
<div class="background3 pls-work"><p>My background color and my sibling's won't.</p></div>
<div class="background2 pls-work"><p>I am the sibling</p></div>
<button onclick="changeBackground('#222');">This will not work</button>
I've been searching everywhere but I can't find one where they use class instead of id.
I would appreciate any pointers on what I'm doing wrong with this.
Please Try With this,
first get that element in variable and the loop on it.
function changeBackground(color){
var elements = document.getElementsByClassName("pls-work")
for (var i = 0; i < elements.length; i++) {
elements[i].style.background=color;
}
}
The call to document.getElementsByClassName("pls-work") returns an HTMLCollection of elements not a single element. You need to iterate over the collection and set the style property on each element.
See JS: iterating over result of getElementsByClassName using Array.forEach
The getElementsByClassName method returns a collection (NodeList) object, see the docs here. To do what you want to do, you'll have to do the following:
function changeBackground(color) {
let elements = document.getElementsByClassName("pls-work")
for (let i = 0; i < elements.length; i++) {
elements.item(i).style.background = color
}
}
See the docs as listed above for more information on how to iterate over this collection.
getElementsByClassName returns the list of elements , so you can do it two ways
1.mentioning index value in javascript like below snippet
function changeBgColor(color){
document.getElementById("background1").style.background = color;
}
function changeBackground(color){
document.getElementsByClassName("pls-work")[0].style.background = color;
document.getElementsByClassName("pls-work")[0].style.background[1] = color;
}
#background1{
background: #c0c0c0;
padding: 50px;
color: #fafafa;
}
.background2{
background: #ff7f50;
padding: 20px;
}
.background3{
background: #555;
padding: 20px;
}
<h4>First example</h4>
<div id="background1"><p>My background color will change.</p></div>
<button onclick="changeBgColor('#222');">This function will work, no problem</button>
<br><br>
<h4>Second example</h4>
<div class="background3 pls-work"><p>My background color and my sibling's won't.</p></div>
<div class="background2 pls-work"><p>I am the sibling</p></div>
<button onclick="changeBackground('#222');">This will not work</button>
Do iterate over the elements of particular class and add a background color to it
getElementsByClassName returns an “array-like object” of elements which you need to iterate over - as opposed to getElementById which returns a single element.
Check this out:
const changeBgColor = () => {
const elements = document.getElementsByClassName('color-me');
const color = document.querySelector('input').value;
for (let i = 0; i < elements.length; i++) {
elements[i].style.backgroundColor = color;
}
};
<p class='color-me'>Color me!</p>
<p>Can't change me..</p>
<p class='color-me'>Me too!</p>
<input type=color />
<button onclick=changeBgColor()>Click Me</button>
function changeColor() {
let cols = document.getElementsByClassName('col1');
for(i = 0; i < cols.length; i++) {
cols[i].style.backgroundColor = 'blue';
}
}
//maybe type script gives error about style just use //#ts-ignore
Do you just want to change the background-color of the first element?
I prefer to use querySelector
ES5
function changeBackground(color) {
document.querySelector(".pls-work").style.backgroundColor = color;
}
But if you want to apply all the elements, use getElementsByClassName and forEach
function changeBackground(color){
document.getElementsByClassName("pls-work").forEach(e => {
e.style.backgroundColor: color;
});
}
Notice: if you want to change only background color, use backgroundColor

creat button for change background color

I want to create two buttons in HTML called 'green' and 'red'. When clicking on them, the style "background-color: {COLOR-SELECTED}" should be changed dynamically.
var verde = document.getElementById('verde')
var vermelho = document.getElementById('vermelho')
var body = document.querySelector('body')
function verde() {
body.className = "verde";
}
function vermelho() {
body.className = "vermelho";
}
.verde {
background-color: darkgreen;
}
.vermelho {
background-color: darkred;
}
<body>
<button class="verde" onclick="verde ()" id="verde"></button>
<button class="vermelho" onclick="vermelho ()" id="vermelho"></button>
</body>
You should use the classList API to add or remove a class to body.
More info HERE
function verde () {
body.classList.remove('vermelho');
body.classList.add('verde');
}
Here are a few changes I've made:
Remove the space between the function name and the () in the HTML.
Removed the first two lines of the javascript – you never use these variables.
Changed querySelector to getElementsByTagName, which creates a list of elements, so that you can select the first one using [0]
The snippet below should work as expected:
var body = document.getElementsByTagName('body')[0];
function verde() {
body.className = "verde";
}
function vermelho() {
body.className = "vermelho";
}
.verde {
background-color: darkgreen;
}
.vermelho {
background-color: darkred;
}
<body class="none">
<button class="verde" onclick="verde()" id="verde"></button>
<button class="vermelho" onclick="vermelho()" id="vermelho"></button>
</body>

How do I toggle between two IDs of a HTML element with javascript?

<div id = 'ONE' onclick = "change to id TWO" >One</div>
What I want is that every time I click that div it'll toggle between ID ONE and ID TWO, if it's on ID TWO and I click it, it switches to ID ONE and vice versa. How can I do that?
This is most easily accomplished with jQuery.
First thing that comes to my mind is setting a click counter to 0. If it's even, we will change the id to red, if it's odd, we change the id to blue.
var clickCount = 0;
$("div").on("click", function() {
clickCount++;
$("div").attr("id", clickCount % 2 === 0 ? "blue" : "red");
});
#red { color: red; }
#blue { color: blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>This is a div</div>
Here is the native JavaScript equivalent.
var div = document.getElementById("my-div");
var clickCount = 0;
div.addEventListener("click", function() {
clickCount++;
div.setAttribute("id", clickCount % 2 === 0 ? "blue" : "red");
});
#red { color: red; }
#blue { color: blue; }
<div id="my-div">This is a div</div>
I found the solution:
function changediv() {
if (document.getElementById("one")) {
document.getElementById("one").id = "two";
} else {
document.getElementById("two").id = "one";
}
}
Then on your div
<div id = "one" onclick = "changediv()" >Your stuff</div>

Javascript: Compare backgroundColor set by javascript

How can compare the background color of an element, when the color is set with javascript, I want a function that toggles the backgroundColor:
function toggleBgColor() {
if(document.getElementById("id").style.backgroundColor === "blue"){
document.getElementById("ide").style.backgroundColor = "red");
}else{
document.getElementById("ide").style.backgroundColor = "blue");
}
}
The problem is that the comparison is always false, so my background is always blue, but it want the color to switch from blue to red and vice versa when the function is called
Use Window.getComputedStyle() — https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle.
The backgroundColor property can get tricky with various representations of color. Consider changing classes instead:
JavaScript
function toggleBgColor() {
var el = document.getElementById("id");
var hasBlue = el.classList.contains('blue');
el.classList.toggle('blue', !hasBlue);
el.classList.toggle('red', hasBlue);
}
CSS
.blue {
background-color: blue;
}
.red {
background-color:red;
}
Or more semantically correct:
JavaScript
function toggleBgColor() {
document.getElementById("id").classList.toggle('selected');
}
CSS
#id {
background-color:red;
}
#id.selected {
background-color:blue;
}
Why not simply add a class that gets toggled?
function toggleBgClass() {
var element = document.getElementById('id');
if (element.classList.contains('blue')) {
element.classList.add('blue');
element.classList.remove('red');
}
else {
element.classList.add('red');
element.classList.remove('blue');
}
}
Now, in your CSS:
.blue {
background-color: blue;
}
.red {
background-color: red;
}
You have written the incorrect code.
The correct code is
function toggleBgColor()
{
if(document.getElementById("ptag").style.backgroundColor === "blue")
{
document.getElementById("ptag").style.backgroundColor = "red";
}
else
{
document.getElementById("ptag").style.backgroundColor = "blue";
}
};
Html File
<html>
<head>
<script type="text/javascript" src="js/backgroundtry.js"></script>
</head>
<body>
<p id="ptag" style="background-color:blue;">
Hi How are you
</p>
<a class="mybutton" onclick="toggleBgColor();">
Change Color
</a>
</body>
</html>

does javascript remove event listeners?

On a test webpage I have, there is a link like so:
HOME
The style for it is like so:
nav > a {
text-decoration: none;
color: #0000aa;
display: inline-block;
width: 80px;
padding: 0 10px;
}
nav > a:hover {
background-color: #eeeeee;
}
and switchf() (switch field) is like so:
function switchf(field,tab) {
document.getElementById("home").style.display = "none";
document.getElementById("about").style.display = "none";
document.getElementById("account").style.display = "none";
document.getElementById("contact").style.display = "none";
document.getElementById("t1").style.backgroundColor = "#dddddd";
document.getElementById("t2").style.backgroundColor = "#dddddd";
document.getElementById("t3").style.backgroundColor = "#dddddd";
document.getElementById("t4").style.backgroundColor = "#dddddd";
document.getElementById(field).style.display = "inline-block";
tab.style.backgroundColor = "#cccccc";
}
The link basically acts as a tab, to show a different thing. There are three others like it.
The JavaScript works fine switching tabs, but when I hover over a tab after I've used switchf(), it doesn't change color anymore.
Is there something wrong with my code?
thanks.
EDIT
this is how I fixed mine:
first, I added class="tab" to all the links, so they looked like this:
HOME<br />
second, I changed the javascript so that the function switchf() was like this:
function switchf(field,tab) {
document.getElementById("home").style.display = "none";
document.getElementById("about").style.display = "none";
document.getElementById("account").style.display = "none";
document.getElementById("contact").style.display = "none";
var t = document.getElementsByClassName("tag"); // here is different
for(var i = 0; i < t.length; i++) {
t[i].style.backgroundColor = "#dddddd";
t[i].addEventListener("mouseover");
t[i].addEventListener("mouseout");
}
document.getElementById(field).style.display = "inline-block";
tab.style.backgroundColor = "#cccccc";
}
and it worked.
Inline CSS takes precedence over stylesheets. Once you click on a link, it will set the background-color property for all links, hence all links will not change color when you hover over it.
A better alternative than hard-coding the style in your elements, you can try adding a CSS class to your links (like page-active) and style those elements as needed.
Yet another alternative that saves you from clearing old classes is adding a class or ID to the page and use that to hide/show links as needed.
<style>
nav > a {
display: none;
}
#page-about nav > a#link-home {
display: inline-block;
}
<body id="page-about">
<nav>
Home
About
</nav>
</body>
This should give you a general idea, polishing it is an exercise for the reader.

Categories

Resources