I have a variable that I need to add 1 to each time an elements opacity is 1. I need to keep checking the opacity so I have wrapped it in a setInterval.
I am wondering if there is a way to only add 1 to the variable each time the opacity changes to 1 instead of keep adding 1 over and over again because of the interval. Here is my code
var number = 1;
var intervalsizer = setInterval(function() {
if ($(".cardButtons__discuss").css('opacity') == 1) {
number++;
console.log(number)
}
function fooo() {
if (number == 1) {
//do something
}
if (number == 2) {
}
if (number == 3) {
//do something
}
if (number == 4) {
//do something
}
}
}, 50);
Thanks in advance
Tracking an attribute can be done using a MutationObserver. This code tracks all attribute changes on the element and filters out changes to the style and class attributes specifically. When the attributes change it looks if the opacity value has changed.
This solution only works if the opacity is changed on the element itself, by setting a class or by setting a style.
const mydiv = document.getElementById('mydiv')
const observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if(mutation.attributeName !== 'style' && mutation.attributeName !== 'class') return;
const target = $(mutation.target);
const oldVal = target.data("oldOpacity");
const newVal = getComputedStyle(target[0]).opacity;
if(oldVal != newVal) {
console.log(`opacity changed. Old: ${oldVal}, New: ${newVal}`)
target.data("oldOpacity", newVal)
}
});
});
const config = {
attributes: true
};
observer.observe(mydiv, config);
//code to change the opacity and another style attribute.
let i = 0;
setInterval(() => {
switch (i % 4) {
case 0:
mydiv.style.backgroundColor = "red"
break
case 1:
mydiv.style.opacity = "0.5"
break
case 2:
mydiv.classList.add('blue')
break
case 3:
mydiv.style.opacity = ""
mydiv.classList.remove('blue')
mydiv.style.backgroundColor = "blue"
break;
}
i++;
}, 1000)
.blue {
background-color: blue !important;
opacity: 1 !important;
}
#mydiv {
background-color: red;
width: 100px;
height: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mydiv"></div>
Related
I have 9 boxes in my html.
There is a value, id called 'lifepoint'.
There is a mouse-click function: click once & decrease one life point. This code is completed.
function decrementlife() {
var element = document.getElementById('lifepoint');
var value = element.innerHTML;
--value;
console.log(value);
document.getElementById('lifepoint').innerHTML = value;
if(value <= 0) { alert("Game Over!")};
}
Also, there is a css style, called 'crackbox'.
.crackbox {
position: relative;
background: linear-gradient(0deg, black, rgb(120, 120, 120));
width: 12vh;
height: 12vh;
border-radius: 30%;
margin: 5px;
}
I want to change all box class from 'box' to 'crackbox' if life point is zero. Therefore, all box style can be 'crackbox'.
The below code is fail...
$(document).ready(function () {
$(".box").each(function() {
document.getElementById('lifepoint').innerHTML = value;
if(value <= 0) {
".box".toggleClass('crackbox')
};
})
});
Instead of using document ready, call another function from decrement life if the value turns 0. I am writing the code for your help.
function decrementlife() {
var element = document.getElementById('lifepoint');
var value = element.innerHTML;
--value;
console.log(value);
document.getElementById('lifepoint').innerHTML = value;
if(value <= 0) { changeClass(); alert("Game Over!")};
}
function changeClass(){
$('.box').addClass('crackbox').removeClass('box');
}
Hope, it helps!!
The simplest way would be to use querySelectorAll and loop through the elements:
for(let i = 0, list = document.querySelectorAll(".box"); i < list.length; i++)
{
list[i].classList.toggle('crackbox');
}
Or shorter ES6 version:
[...document.querySelectorAll(".box")].forEach(el => el.classList.toggle('crackbox'))
Hi I want to store a number when its value is 0
var count = 3;
var count2 = "0";
var count3;
var btn = document.getElementById("btn");
btn.onclick = function() {
count--;
btn.style.transform = "scale(2)";
setTimeout(function() {
btn.style.transform = "scale(1)";
}, 0005);
if(count === 0) {
/* I want to store the result here in manner that even when the page reload the number remains the same ( 0 in that case ) */
var zero = localStorage.getItem(count);
count3 = parseInt(count2);
localStorage.setItem( count , count3 );
}
}
#btn {
width : 300px;
height : 300px;
border : solid 2px red;
border-radius : 50%;
transition : .1s;
}
<button id="btn">Click me</button>
But I don't need to affect count3 to count since count is already set at 0 :( but I can't affect numbers ? I think there's only string in the 'key' for localStorage.
How I can do that ?
The key for localstorage is to only use String. You can define a function to parse the key to any.... When the page reload, loacalStorage can't be cleared. So you can do it like var key = parse(localStorage.getitem(count)) in your defined function.
localStorage.setItem( count , count3 )
This is wrong. You should write
localStorage.setItem( "where" , value );
So instead of setting the item in the key equal to the variable count, you should set the value in key "count", which is a string. Otherwise, every time you change the integer count, you store the new value (count3) in a new place.
When you then reload the page, the integer count is then trying to fetch the stored information in key 3.
Also, count === 0 could as well be written as count == 0 so it doesn't check if count is an integer first, and instead accepts strings (and boolean, undefined and null).
EDIT: added snippet as example. I refactored the code so it's more readable, commented out localStorage so you can run the snippet on Stack Overflow, and I assumed that count can't get lower than 0.
As a bonus, I removed count2 and count3 while changing the setTimeout from 0.005 (5ms is minimum anyway) to 50ms (half of 0.1s that is in the transition).
var storedCount = getStoredCount();
const GOT_PREVIOUS_VALUE = storedCount != null;
var count = (GOT_PREVIOUS_VALUE) ? storedCount : 3;
var btn = document.getElementById("btn");
btn.onclick = changeCount;
function changeCount() {
if (count > 0) {
count--;
scaleButton();
storeCount();
console.log({count})
}
}
function scaleButton() {
btn.style.transform = "scale(2)";
setTimeout(function() {
btn.style.transform = "scale(1)";
}, 50);
}
function getStoredCount() {
return localStorage.getItem('count') ;
}
function storeCount() {
localStorage.setItem('count', count);
}
#btn {
width: 300px;
height: 300px;
border: solid 2px red;
border-radius: 50%;
transition: .1s;
}
<button id="btn">Click me</button>
I'm working on an assignment, where the user can draw inside an n*n grid. The tasks are as following:
Create a 16x16 grid as default grid upon page-load
Implement a mouseover-EventListener for the grid, that changes the background-color of cells to black
Add a reset button, that asks the user how big the new grid should be
Add 2 buttons that set the mouseover-EventListener (default black) to a different color. First button changes the color to yellow, second button to gray.
My problem:
I'm stuck with the last task. The 2 buttons work just fine. But they can be called only once. If I select yellow - it draws yellow. If I then select gray - it draws gray. After that, the button-clicks don't do anything anymore, but I can still draw in gray.
That's what I have done so far:
First, I querySelected the button-type and added an EventListener "click".
Second, in the colourHover function, a mouseover EventListener gets invoked, depending on the button's id.
Third, the EventListener-mouseover gets defined in the respective functions (grayColour(event), yellowColour(event)).
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
</head>
<body id="start">
<div class="container" id="grid">
</div>
<div><button type="button" class="button" id="gray">Gray Colour</button></div>
<div><button type="button" class="button" id="yellow">Yellow Colour</button></div>
<div><button type="button" id="button">Resize your grid manually.</button></div>
<script>
"use strict";
let container = document.getElementById("grid");
let n;
// creating a grid with number-input from user.
let makeGrid = function makeGrid(input) {
let c;
for (c = 0; c < (input * input); c++) {
let cell = document.createElement("div");
container.appendChild(cell).className = "squares";
};
container.style.gridTemplateColumns = `repeat(${input}, auto)`;
container.style.gridTemplateRows = `repeat(${input}, auto)`;
};
// function gets exectuted, only if a number and below 101
let numberCheck = function numberCheck() {
if ((n % n) === 0 && n <= 100) {
makeGrid(n);
};
while ((n % n) !== 0) {
alert("Please enter a number.");
n = prompt("Choose again.");
if ((n % n) === 0 && n <= 100) {
makeGrid(n);
}
};
while ((n % n) === 0 && n > 100) {
alert("The number is too high.");
n = prompt("Choose again.");
if ((n % n) === 0 && n <= 100) {
makeGrid(n);
}
else if ((n % n) !== 0) {
alert("Please enter a number");
n = prompt("Choose again");
if ((n % n) === 0 && n <= 100) {
makeGrid(n);
}
}
};
};
// default grid on first pageload
makeGrid(16);
// this function sets the hovered items colour to black on default / first pageload
let blackColor = function blackColor(event) {
let colour = event.target;
if (colour.className === "container") {
return;
}
else if (colour.className === "squares") {
colour.style.backgroundColor = "black";
};
};
// addEventListener for blackColor function
let hoverItems = document.querySelectorAll(".container");
hoverItems.forEach(element => { element.addEventListener("mouseover", blackColor)
});
// function to manual selecting a grid-size. Beforehand, old grid gets deleted
let removeElements = function removeElements(event) {
let elements = document.getElementsByClassName("squares");
while (elements.length > 0) {
elements[0].parentNode.removeChild(elements[0]);
};
n = prompt("Choose the size of your grid");
numberCheck(n);
};
// button for selecting a grid-size manually
let button = document.querySelector("#button");
button.addEventListener("click", removeElements);
// this function sets the background-color of the cells on mouseover to gray
let grayColour = function grayColour(event) {
let colour = event.target;
if (colour.className === "container") {
return;
}
else if (colour.className === "squares") {
colour.style.backgroundColor = "gray"
}
}
// this function sets the background-color of the cells on mouseover to yellow
let yellowColour = function yellowColour(event) {
let colour = event.target;
if (colour.className === "container") {
return;
}
else if (colour.className === "squares") {
colour.style.backgroundColor = "yellow";
}
}
let colourHover = function colourHover(event) {
let hover = document.querySelectorAll(".container");
switch (event.target.id) {
case "gray":
//hover.forEach(element => { element.removeEventListener("mouseover", yellowColour)
//});
//hover.forEach(element => { element.removeEventListener("mouseover", grayColour)
//});
hover.forEach(element => { element.addEventListener("mouseover", grayColour)
});
break;
case "yellow":
//hover.forEach(element => { element.removeEventListener("mouseover", yellowColour)
//});
//hover.forEach(element => { element.removeEventListener("mouseover", grayColour)
//});
hover.forEach(element => { element.addEventListener("mouseover", yellowColour)
});
break;
};
};
let colourBtn = document.querySelectorAll(".button");
colourBtn.forEach(element => { element.addEventListener("click", colourHover)
});
</script>
</body>
</html>
I appreciate any hint in the right direction. Really stuck right now.
The simplest way is to use CSS classes for styling the cells, and change the class of the table body in a button click handler. The state of the "widget" should be stored in a JS variable, that way you can avoid unnecessary DOM traversing on each click of the buttons. Something like this:
const buttons = document.querySelectorAll('button'),
table = document.querySelector('.hovered-colors');
// The state of the widget
let currentColor = 'black';
buttons.forEach(button => {
button.addEventListener('click', e => {
const newColor = e.target.getAttribute('data-color');
table.classList.remove(currentColor);
table.classList.add(newColor);
currentColor = newColor;
});
});
.black td:hover {
color: white;
background-color: black;
}
.gray td:hover {
color: black;
background-color: gray;
}
.yellow td:hover {
color: black;
background-color: yellow;
}
<table>
<tbody class="hovered-colors black">
<tr><td>R1C1</td><td>R1C2</td></tr>
<tr><td>R2C1</td><td>R2C2</td></tr>
<tr><td>R3C1</td><td>R3C2</td></tr>
</tbody>
</table>
<button data-color="gray">Gray</button>
<button data-color="yellow">Yellow</button>
I want to change the innerHTML so for every circle thats the same it adds +1
if (document.getElementById("circle1").style.backgroundColor == document.getElementById("circle5").style.backgroundColor) {
document.getElementById("point2").innerHTML = +1
}
if (document.getElementById("circle2").style.backgroundColor == document.getElementById("circle6").style.backgroundColor) {
document.getElementById("point2").innerHTML = +1
}
I suggest you to use innerText then. First get the old value and cast to Number then add by 1 and replace the old value. Example:
if (document.getElementById("circle1").style.backgroundColor == document.getElementById("circle5").style.backgroundColor) {
let obj = document.getElementById("point2");
let oldValue = Number(obj.innerText);
obj.innerText = oldValue + 1;
}
if (document.getElementById("circle2").style.backgroundColor == document.getElementById("circle6").style.backgroundColor) {
let obj = document.getElementById("point2");
let oldValue = Number(obj.innerText);
obj.innerText = oldValue + 1;
}
See difference between innerText and innerHtml.
document.getElementById("point2").innerHTML doesn't give you a number, so you cannot add 1 to it. first you need to parse the content to a number (like with parseInt or Number), and then you can add 1.
// creating the reference variable (for smaller code)
var point2 = document.getElementById("point2").innerHTML
if (document.getElementById("circle1").style.backgroundColor ==
document.getElementById("circle5").style.backgroundColor) {
document.getElementById("point2").innerHTML = increment(point2)
}
if (document.getElementById("circle2").style.backgroundColor ==
document.getElementById("circle6").style.backgroundColor) {
document.getElementById("point2").innerHTML = increment(point2)
}
// function to increment the value of point2
function increment(html) {
return Number(document.getElementById("point2").innerHTML) + 1
}
#circle1 {
background-color: red;
}
#circle5 {
background-color: red;
}
#circle2 {
background-color: red;
}
#circle6 {
background-color: red;
}
<div id="circle1">C1</div>
<div id="circle5">C5</div>
<br />
<div id="circle2">C2</div>
<div id="circle6">C6</div>
<div id="point2">0</div>
I am very new to Javascript so feel free to point out anything I am doing wrong. I am trying to change the colour of a div everytime a button is clicked. This is my code so far:
function setBgColour(){
if (.backgroundColor == '#ff0000'){
document.getElementsByClassName("light")[0].style.backgroundColor = '#ffff00';
} else if (.backgroundColor == '#ffff00'){
document.getElementsByClassName("light")[0].style.backgroundColor = '#00ff00'
} else if (.backgroundColor == '#00ff00'){
document.getElementsByClassName("light")[0].style.backgroundColor = '#ff0000'
}
}
window.onload = function(){
document.getElementById('next').addEventListener('click', setBgColour);
};
The problem is with your condition statements. You're doing:
if (.backgroundColor == '#ff0000')
What's the element you're looking into, to get the backgroundColor property?
You should do something like:
window.onload = function() {
var current = '#ff0000';
function setBgColour() {
var light = document.getElementsByClassName("light")[0];
if (current == '#ff0000') {
current = '#ffff00';
} else if (current == '#ffff00') {
current = '#00ff00';
} else if (current == '#00ff00') {
current = '#ff0000';
}
light.style.backgroundColor = current;
}
document.getElementById('next').addEventListener('click', setBgColour);
setBgColour();
};
.light {
width: 100px;
height: 100px;
}
<div class="light"></div>
<button id="next">Next</button>