Anyways I’m trying to make a lightbulb. It’s just a circle, I have an onclick event on a button, and the event function toggled a class, changing the color. But I want the text in the button to toggle as well when that class is activated.
I finally made it work as I was writing this question. But it still isn’t working how I want it. I only want to have one if statement.
I only want to solve it this specific way, by checking if a class is activated, and if yes, then change the text content of the button, if not, then leave it how it is.
let bulb = document.getElementById("light");
let lightSwitch = document.getElementById("switch");
function activity(event) {
bulb.classList.toggle("lightOn");
if (bulb.classList.contains("lightOn")) {
lightSwitch.textContent = "OFF";
} else if (bulb.classList.contains("lightOff")) {
lightSwitch.textContent = "ON";
}
}
.lightOn {
background: yellow;
}
<div id="light" class="lightOff"></div>
<button id="switch" onclick="activity()">ON</button>
How can I write it with only one if statement, Also, is there a way easier than this? Just vanilla not jQuery.
like this?
...
function activity(event) {
bulb.classList.toggle("lightOn");
lightSwitch.textContent = bulb.classList.contains("lightOn") ? "OFF" : "ON";
}
...
Your code can be simplified by extracting the bulb-specific default styles into a light class, then only toggle a new lightOn class. The default styles describe what to show if the bulb is off, but you can override those styles with !important in the lightOn class. Just like this:
let bulb = document.getElementById("light");
let lightSwitch = document.getElementById("switch");
lightSwitch.addEventListener('click', function() {
bulb.classList.toggle('lightOn');
lightSwitch.textContent = bulb.classList.contains("lightOn") ? "OFF" : "ON";
});
.light {
width: 100px;
height: 100px;
border-radius: 100%;
background: gray;
}
.lightOn {
background: yellow !important;
}
<div id="light" class="light"></div>
<button id="switch">ON</button>
You can also shorten your if-statement into a ternary expression, which is a better choice for this situation because only one value changes.
Related
I have a site with a lot of different div. The thing they have in common is all share (besides their unique classes) a shared class. Lets just call it .changeClass.
What I am looking for is code with a button (or radio buttons) and by clicking the button, the background instance of all these divs will get the same one (which the .changeClass has). So the .changeClass will just be active when the button is toggled/clicked.
I am looking for a way to do this with pure javascript and no Jquery.
Sorry for being a noob :-)
In the solution below, clicking the <button> element will add/remove the class style .changeClass to all elements that have the class style .apply applied.
let button = document.getElementById('change');
let containers = document.getElementsByClassName('apply');
function changeButtonText() {
if(button.innerHTML === "Add")
button.innerHTML = "Remove";
else
button.innerHTML = "Add";
}
button.addEventListener('click', function() {
for(let index = 0 ; index < containers.length ; ++index)
containers[index].classList.toggle('changeClass');
changeButtonText();
});
div {
margin-top: 25px;
}
.apply {
border: 3px solid black;
}
.changeClass {
background-color: black;
color: white;
border: 3px solid red;
margin-top: 25px;
}
<button id="change">Add</button>
<div class="apply">1</div>
<div class="apply">2</div>
<div class="apply">3</div>
<div class="apply">4</div>
<div class="apply">5</div>
First lets get all divs that are on the DOM
const divs = document.getElementsByTagName("div");
You will have array of all the divs that are on the DOM. Then add your class to all of it. In order to do that, lets loop it.
divs.forEach(div => div.className += div.className + " changeClass");
Could this be what you are looking for?
In html:
<button onclick="changeColor('blue');">blue</button>
In JS
function changeColor(newColor) {
var elem = document.getElementsByClassName("changeClass");
elem.style.color = newColor;
}
The HTML color can be any color you would like it to be, just change they name from blue to any color or input a hex code.
We have multiple divs with the same class value
We have given a function to the button that we want the event to happen when it is clicked, using the onclick method. Now when we click the button, the function called myFunction will run.
HTML:
<div class="changeClass">Im Example Div</div>
<div class="changeClass">Me Too</div>
<button type="submit" onclick="myFunction()">Click To Change Div BgColors !
</button>
We must define myFunction as Javascript and change the background color.
We have defined a function called myFunction.
With the getElementsByClassName selector in our function, we got all the data with the class value changeClass in object format.
To add a background (or any css property) to all of these objects; We put the object in a for loop and now we split our elements.
We can now define a background color for our elements with the style.backgroundColor parameter.
JavaScript:
function myFunction(){
var divs = document.getElementsByClassName('changeClass');
for(var i=0; i< divs.length; i++){
divs[i].style.backgroundColor = 'red';
}
}
For more detailed information, you can refer to the resources: https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
Don't be sorry for being new at something and wanting to learn more!
So what you are saying is that the divs you want to change all have a common class of "changeClass". If this is the case then you want a function is passed an argument value of the color you want to be changed. Since all of your divs are static and you probably don't plan on changing, declare a variable outside of this function that has the following code
const divs = document.getElementsByClassName("changeClass")
Then, inside of the function, loop through all of the divs collected inside the variable "divs", or whatever you want to call it. Since "getElementsByClassName" returns a collection, it does not have the built in "foreach" and "map" methods. So you have to use a for loop preferably the following.
const divs = document.getElementsByClassName("changeClass");
function changeColor(color) {
for (let element of divs) {
element.style.backgroundColor = color;
}
}
I may have interpreted this wrong but I hope it helps
You may find using a CSS variable helpful.
For example:
function bg(color) {
document.body.style.setProperty('--bg', color);
}
body {
--bg: cyan;
}
.container {
display: flex;
gap: 1vw;
}
.container div {
width: 100px;
height: 100px;
background-color: black;
}
.container div.changeClass {
background-color: var(--bg);
}
<body>
<button onclick="bg( 'red');">Red</button>
<button onclick="bg( 'green');">Green</button>
<button onclick="bg( 'blue');">Blue</button>
<button onclick="bg( 'black');">Black</button>
<div class="container">
<div class="changeClass"></div>
<div class="changeClass"></div>
<div class="changeClass"></div>
<div></div>
<div class="changeClass"></div>
</div>
</body>
Then when one of the radio buttons is clicked it sets the variable --bg.
Here's a simple snippet:
First of all - thank you for all your replies. And yes I should have included code. I tried so many things that i just gave up at som point - got confused what was right code and what was just rubbish. So I appreciate so much that you all took time to answer me. This was my first post so now I know for the future. The answers I got all was possible ways to solve my problem - so thank you all. I will do better next time. You are awesome...
BTW - All solutions seems to work - but can only checkmark one of them as you know.
You can add or remove a class to change the colours of different div:
document.queryselector('.className').classList.add('classNamethatyouwanttoadd');
document.queryselector('.className').classList.remove('classNamethatyouwanttoadd');
I'm trying to learn some JS, and would like to know if anyone could help me, please.
I would like to do, in a dashboard admin, an control with toggle switch to show on the index of the site whether the service is online or offline.
When on, put a "online" text in a green tag. And when not working, "offline" with a red tag.
How can I do this? With event listener? Thanks!
Example
Here's a simple exaple to show you an approach.
document.getElementById(`status`).addEventListener(`click`, function(){
const classes = this.classList;
if (classes.contains(`offline`)) {
this.textContent = `Online`;
classes.remove(`offline`);
classes.add(`online`);
} else if (classes.contains(`online`)) {
this.textContent = `Offline`;
classes.remove(`online`);
classes.add(`offline`);
}
});
#status {
color: white;
}
.online {
background: green;
}
.offline {
background: red;
}
<span id='status' class='offline'>Offline</span>
I will need to put 2 different actions on a single link which would have an active/inactive state, right now I only know how to do one at the time, something like this (active):
State One
And I would like to have another one on same click (inactive), is there a way to have this dynamically changed? The label shouldn't change, except for color for example - style.
On the other side, it would be a great thing if I could show the list of active items as well, something like:
Active states: State one, State two, State ...
I recommend something other than an A tag for what you're doing. I also recommend the modern equivalent of an onclick, an event listener. I also recommend assigning and toggling the class.
State One
I have removed your onclick and put it into an event listener. I've added a class, so you can toggle it.
function classToggle() {
this.classList.toggle('class123');
this.classList.toggle('class456');
}
This toggles your class, thus allowing you to change the behavior of the link based on the class. Active/Inactive or Class123/Class456 whatever you want to use will work.
document.querySelector('#myDiv').addEventListener('click', classToggle);
This is your listener. It applies the classToggle function on click. You can do this with a div/button/whatever. Personally I'd change the A tag to a Div.
<div id="myElem" class="class123">click here</div>
And here is an example of this stuff working and changing based on the toggle and classes.
function classToggle() {
this.classList.toggle('class123');
this.classList.toggle('class456');
}
document.querySelector('#myElem').addEventListener('click', classToggle);
document.querySelector('#myElem').addEventListener('click', mogrify);
function mogrify(){
if (document.querySelector('#myElem').classList.contains('class123')) {
document.querySelector('#myElem').style.backgroundcolor = "#54C0FF"
document.querySelector('#myElem').innerText = "State Two";
} else {
document.querySelector('#myElem').style.backgroundcolor = "#FF8080"
document.querySelector('#myElem').innerText = "State One";
}
}
.class123 {
color: #f00;
}
.class456 {
color: #00f;
}
State One
I think I got it to work, here's my code, please let me know if good enough.
A href:
State One
js:
<script>
function toggleState(a) {
if ( a.className === 'visible' ) {
HideOneState('state_One', gameInstance);
a.className = '';
} else {
ShowOneState('state_One', gameInstance);
a.className = 'visible';
}
}
</script>
#shandoe2020 has a good answer but here is the "old way" which is pretty easy to understand too. It can be adapted to links (or anything else) quite easily.
<!DOCTYPE html>
<html>
<head>
<style>
.my-button { width:150px; height:150px; }
.my-red { background-color:#ff0000; }
.my-blue { background-color:#0000ff; }
</style>
<script>
/* toggle the state of my-red and my-blue class */
function toggle()
{
/* yeah yeah, hardcoding the item to change is bad */
var elem = document.getElementById("btn")
elem.classList.toggle("my-red")
elem.classList.toggle("my-blue")
}
</script>
</head>
<body>
<div>
<p><button id="btn" class="my-button my-red" onclick="toggle()">Button</button></p>
</div>
</body>
</html>
Probably a simple fix but I've been stuck working through this now for a couple days. I'm building a tic-tac-toe project and I would like to build a method inside my user object called userClick() that satisfies the following conditions:
When the user clicks on a tictactoe tile:
Change the HTML text inside that tile (div) to the user's marker (X or O);
add a CSS class of taken to the tile;
increase the user's score/move count by 1.
Here's the relevant Javascript/jQuery code I've tried to fiddle around with:
var user = {
score: 0,
marker: "X",
userClick: function() {
$('.box').onClick(function() {
this.text(marker);
this.addClass('taken');
score += 1;
});
};
My HTML has 9 divs arranged in a tictactoe grid and all divs have the class of box. My CSS file also has a class of taken that changes the background color of the div when clicked. However, when I click on any of the divs, nothing happens. I've tried making numerous tweaks to the function to get it to work, with no luck. I'm still rather inexperienced with closures, event handlers, and this binding so maybe someone with more experience can shed some light on this for me.
Thanks!
Edit: Here's a JSFiddle of the entire code base so far in case it helps. (Problematic method begins at line 74).
It's not fully clear to me (much less the parser) what you expect "this" to be in your context. Is it the jquery selected element you want? Or is it the user object?
Given that you're trying to add a CSS class to it, I'll assume you want the clicked element. Your handler assignment should then look like so:
$('.box').on('click', function() {
var box = $(this); // refers to the clicked element
box.text(marker);
box.addClass('taken');
score += 1;
});
this inside the handler stands for the DOM element, but both text and addClass belong to jQuery Object. So you need to use them like this.
$(this).text(marker)
I put a fiddle up here for a pretty bare bones jQuery tic-tac-toe per your mention: https://jsfiddle.net/6ynyr7hx/
HTML
<div id="game_container">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
jQuery
$(function() {
var marker_count = 1;
$('.box').click(function() {
if (marker_count === 9) {
$('#game_container').append('GAME OVER');
}
if (marker_count % 2 === 00) {
marker = "X";
} else {
marker = "O";
}
$(this).text(marker).addClass("taken");
//Increment the counter
marker_count = marker_count + 1;
});
});
CSS
#game_container {
width: 140px;
text-align: center;
}
.box {
display: block;
float: left;
width: 40px;
height: 40px;
line-height: 40px;
text-align: center;
margin: 2px;
border: 1px solid #CCC;
}
*NOTE: I didn't bother clearing the floats as this was just a quickie...
// PROBLEM METHOD
userClick: function userClick(marker) { <--- You have to pass the marker
marker = "x"; <- That should be the passed marker
$(".box").click(function() {
$(this).text(marker).addClass("taken");
score += 1;
});
}
}
you will need to pass the marker states and scores back and forth on changing turns etc... This at least gets you a little closer to play with it. Also remove all the html head code including the js and then use the javascript panel cog wheel icon to include jquery x.x.x and set it to onDomready. Pay attention to the terminations I changed in the above code. There was a straggler in there that was causing the script to fail. And un-comment out your on ready userClick function in the fiddle.
Missing } following function at userClick; call user.userClick() within game.initializeGame(); substitute user.marker and user.score for marker, score within .click() function attached to .box selector.
// Game functions
initializeGame: function() {
user.chooseMarker();
computer.chooseMarker();
user.setMarkerInUI();
user.updateScore();
computer.setMarkerInUI();
computer.updateScore();
user.userClick();
$('#score strong').text(totalScore);
}
// PROBLEM METHOD
userClick: function userClick() {
$(".box").click(function() {
console.log(this, user.marker)
$(this).text(user.marker);
$(this).addClass(".taken");
user.score += 1;
})
}
A start plnkr https://plnkr.co/edit/cAOj0Xa0rcNucM9lft1G?p=preview
function hoverHandler(e)
{
if(event.target.getAttribute("id") != "hovering")
{
event.target.setAttribute("id", "hovering");
}
}
This is the code I have, I also have a CSS that sets the color when id is hovering.
The problem:
1) As I am hovering, the color does not get reset back to previous color when I leave the element
Can't you just use Css to solve the problem?
Something like
.element:hover
{
background-color: #FF0000;
}
where element is the class name
try adding, and make sure your checking for onmouseout as well
<script>
function hoverHandler(e)
{
if(e.id=="red") // hovering
{
e.id="blue";
}else {
e.id="red";
}
}
</script>
<span onmouseover="hoverHandler(this)" onmouseout="hoverHandler(this)">test</span>
or an inline event handlers could be
<style>#startStyle {color:lime} #red {color:red}#blue{color:blue}</style>
<span onmouseover="this.id='red'" onmouseout="this.id=''">test</span>
onmouseout would default back to the base style if any; or
<span onmouseover="this.id='red'" onmouseout="this.id='startStyle'">test</span>