im trying to get a set of four different colored div's to flash for a second in a random sequence that keeps repeating adding one more flash each time, by adding a class that sets their opacity to 0, but only the last div in the sequence appears to be flashing, here is the javascript code:
$(function() {
x="";
for(i=0;i<3;i++){
x+=String(Math.floor(Math.random()*4)+1);
$("#test").append(x);
j=0;
flashinglight();
$("#red").removeClass("redflash");
$("#blue").removeClass("blueflash");
$("#yellow").removeClass("yellowflash");
$("#green").removeClass("greenflash");
};
})
function flashinglight(){
if(j<x.length){
setTimeout(function(){
$("#red").removeClass("redflash");
$("#yellow").removeClass("yellowflash");
$("#green").removeClass("greenflash");
$("#blue").removeClass("blueflash");
if(x[j]=="1"){
$("#red").addClass("redflash");
}
else if(x[j]=="2"){
$("#yellow").addClass("yellowflash");
}
else if(x[j]=="3"){
$("#green").addClass("greenflash");
}
else if(x[j]=="4"){
$("#blue").addClass("blueflash");
}
j+=1;
flashinglight();
},1000);
}
else{
return;
}
}
You'll be glad to know it can ba a lot simpler than that. :-) See comments inline:
// Your existing ready callback
$(function() {
// Array of color names
var colors = ["red", "blue", "yellow", "green"];
// Start
flashlight();
function flashlight() {
// Get a random color
var c = colors[Math.floor(Math.random() * colors.length)];
// Get the matching element
var elm = $("#" + c);
// And class
var cls = c + "flash";
// Add the class
elm.addClass(cls);
// A second later...
setTimeout(function() {
// Remove it
elm.removeClass(cls);
// And run again
flashlight();
}, 1000);
}
});
.container div {
display: inline-block;
width: 40px;
height: 40px;
}
#red {
border: 2px solid red;
}
#blue {
border: 2px solid blue;
}
#yellow {
border: 2px solid yellow;
}
#green {
border: 2px solid green;
}
.redflash {
background-color: red;
}
.blueflash {
background-color: blue;
}
.yellowflash {
background-color: yellow;
}
.greenflash {
background-color: green;
}
<div class="container">
<div id="red"></div>
<div id="blue"></div>
<div id="yellow"></div>
<div id="green"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
That "flashes" for a full second before moving on to the next. If you need a shorter flash and a delay between them, it's just a matter of setting up a second timer.
Watching that for a moment, it bothered me when the same color was picked twice. So if you want a version that excludes the current color when picking the next:
// Your existing ready callback
$(function() {
// Array of color names
var colors = ["red", "blue", "yellow", "green"];
// The current color
var color = null;
// Start
flashlight();
function flashlight() {
// Pick a random color, excluding the one we're currently using
var available = colors.filter(function(c) {
return c !== color;
});
color = available[Math.floor(Math.random() * available.length)];
// Get the matching element
var elm = $("#" + color);
// And class
var cls = color + "flash";
// Add the class
elm.addClass(cls);
// A second later...
setTimeout(function() {
// Remove it
elm.removeClass(cls);
// And run again
flashlight();
}, 1000);
}
});
.container div {
display: inline-block;
width: 40px;
height: 40px;
}
#red {
border: 2px solid red;
}
#blue {
border: 2px solid blue;
}
#yellow {
border: 2px solid yellow;
}
#green {
border: 2px solid green;
}
.redflash {
background-color: red;
}
.blueflash {
background-color: blue;
}
.yellowflash {
background-color: yellow;
}
.greenflash {
background-color: green;
}
<div class="container">
<div id="red"></div>
<div id="blue"></div>
<div id="yellow"></div>
<div id="green"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Related
I want to remove/add the classList of some element if the classList of another element is equal to "sth". But there is a little problem that it only runs the command once, I mean the condition doesn't check the classList of the first element every second so it runs it without any problem. If the if is true then it runs the if condition and then it won't check else if and so reverse.
Here is my code:
const dToggle = () => {
const firstElm = document.querySelector('.firstElm');
firstElm.classList.toggle('red-border');
};
document.querySelector('button').addEventListener('click', dToggle);
const orangeOrRed = () => {
const firstElm = document.querySelector('.firstElm');
const secondElm = document.querySelector('.secondElm');
firstElm.classList === 'red-border' ? secondElm.classList.add('red') : secondElm.classList.add('orange');
// if (firstElm.classList === 'red-border') {
// secondElm.classList.remove('orange');
// secondElm.classList.add('red');
// } else if (firstElm.classList === 'orange-border' {
// secondElm.classList.remove('red');
// secondElm.classList.add('orange');
// };
};
// Maybe the exact problem is right here.
window.addEventListener('load', orangeOrRed);
console.log(document.querySelector('.secondElm').classList.value);
.d-none {
display: none !important;
}
.firstElm {
margin-top: 10px;
width: 200px;
height: 100px;
background-color: blue;
}
.orange-border {
border: orange 3px solid;
}
.red-border {
border: red 3px solid;
}
.secondElm {
margin-top: 10px;
width: 200px;
height: 100px;
background-color: green;
}
.orange {
background-color: orange !important;
}
.red {
background-color: red !important;
}
<button type="button" style="cursor: pointer;">Click here.</button>
<p>It should run the conditional statement whenever I click on the button to apply the border.</p>
<p> First Elm Border Color (MUST BE) Second Elm Background Color</p>
<div class='firstElm orange-border'></div>
<div class='secondElm'></div>
<p style="padding-bottom: 10px;">Remember that I only want to do this with(conditioal statements), It's possible either with classList.toggle() but I don't want to.</p>
Here we have three problems:
1. Checking for the wrong condition
classList is a DOMTokenList that has a contains method which returns true if the element has the desired className or vice versa
2. Adding the same className multiple times without removing the old one
you need to remove the orange className if you want to add the red className and vice versa
3. The orangeOrRed function runs only once
The orangeOrRed function runs only once on window's load event
You need to add the same event listener to the button's click event
const dToggle = () => {
const firstElm = document.querySelector('.firstElm');
firstElm.classList.toggle('red-border');
};
document.querySelector('button').addEventListener('click', dToggle);
const orangeOrRed = () => {
const firstElm = document.querySelector('.firstElm');
const secondElm = document.querySelector('.secondElm');
if (firstElm.classList.contains('red-border')) {
secondElm.classList.remove('orange');
secondElm.classList.add('red');
} else if (firstElm.classList.contains('orange-border')) {
secondElm.classList.remove('red');
secondElm.classList.add('orange');
};
};
// You're right, the exact problem is right here.
window.addEventListener('load', orangeOrRed);
document.querySelector('button').addEventListener('click', orangeOrRed);
console.log(document.querySelector('.secondElm').classList.value);
.d-none {
display: none !important;
}
.firstElm {
margin-top: 10px;
width: 200px;
height: 100px;
background-color: blue;
}
.orange-border {
border: orange 3px solid;
}
.red-border {
border: red 3px solid;
}
.secondElm {
margin-top: 10px;
width: 200px;
height: 100px;
background-color: green;
}
.orange {
background-color: orange !important;
}
.red {
background-color: red !important;
}
<button type="button" style="cursor: pointer;">Click here.</button>
<p>It should run the conditional statement whenever I click on the button to apply the border.</p>
<p> First Elm Border Color (MUST BE) Second Elm Background Color</p>
<div class='firstElm orange-border'></div>
<div class='secondElm'></div>
<p style="padding-bottom: 10px;">Remember that I only want to do this with(conditioal statements), It's possible either with classList.toggle() but I don't want to.</p>
Achieving the same results using the MutationObserver API.
It's useful when you have no toggle button or when you're not in control of when the class name of the element changes.
const firstElm = document.querySelector('.firstElm');
const secondElm = document.querySelector('.secondElm');
const orangeOrRed = () => {
if (firstElm.classList.contains('red-border')) {
secondElm.classList.remove('orange');
secondElm.classList.add('red');
} else if (firstElm.classList.contains('orange-border')) {
secondElm.classList.remove('red');
secondElm.classList.add('orange');
};
}
// Callback function to execute when mutations are observed
const callback = (mutationsList) => {
// check to see if the changed attribute that caused the mutationObserver callback to be called is the class attribute and run the desired code
if (mutationsList[0].attributeName === 'class') orangeOrRed();
};
// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);
// Options for the observer (which mutations to observe)
// Here the MutationObserver will call the specified callback just if attributes of the target node have changed
const config = { attributes: true, childList: false, subtree: false };
// Start observing the target node (firstElm) for configured mutations
observer.observe(firstElm, config);
const dToggle = () => {
firstElm.classList.toggle('red-border');
};
document.querySelector('button').addEventListener('click', dToggle);
// You're right, the exact problem is right here.
window.addEventListener('load', orangeOrRed);
.d-none {
display: none !important;
}
.firstElm {
margin-top: 10px;
width: 200px;
height: 100px;
background-color: blue;
}
.orange-border {
border: orange 3px solid;
}
.red-border {
border: red 3px solid;
}
.secondElm {
margin-top: 10px;
width: 200px;
height: 100px;
background-color: green;
}
.orange {
background-color: orange !important;
}
.red {
background-color: red !important;
}
<button type="button" style="cursor: pointer;">Click here.</button>
<div class='firstElm orange-border'></div>
<div class='secondElm'></div>
<p style="padding-bottom: 10px;">Remember that I only want to do this with(conditioal statements), It's possible either with classList.toggle() but I don't want to.</p>
You've misinterpreted what the problem is here; it's not that the conditional isn't running, it's that it's checking the wrong thing.
You're looking to see if a DOM element's classList === 'orange-border' but this will never be true; classList isn't a simple string. What you want is to see if the classList includes orange-border.
const dToggle = () => {
const firstElm = document.querySelector('.firstElm');
firstElm.classList.toggle('red-border');
};
document.querySelector('button').addEventListener('click', dToggle);
const orangeOrRed = () => {
const firstElm = document.querySelector('.firstElm');
const secondElm = document.querySelector('.secondElm');
// I'm not sure why you have both this ternary and the similar if:else below, but I've fixed both to at least be checking the classList correctly:
firstElm.classList.contains('red-border') ? secondElm.classList.add('red') : secondElm.classList.add('orange');
if (firstElm.classList.contains('red-border')) {
secondElm.classList.remove('orange');
secondElm.classList.add('red');
} else if (firstElm.classList.contains('orange-border')) {
secondElm.classList.remove('red');
secondElm.classList.add('orange');
};
};
window.addEventListener('load', orangeOrRed);
console.log(document.querySelector('.secondElm').classList.value);
.d-none {
display: none !important;
}
.firstElm {
margin-top: 10px;
width: 200px;
height: 100px;
background-color: blue;
}
.orange-border {
border: orange 3px solid;
}
.red-border {
border: red 3px solid;
}
.secondElm {
margin-top: 10px;
width: 200px;
height: 100px;
background-color: green;
}
.orange {
background-color: orange !important;
}
.red {
background-color: red !important;
}
<button type="button" style="cursor: pointer;">Click here.</button>
<p>It should run the conditional statement whenever I click on the button to apply the border.</p>
<p> First Elm Border Color (MUST BE) Second Elm Background Color</p>
<div class='firstElm orange-border'></div>
<div class='secondElm'></div>
<p style="padding-bottom: 10px;">Remember that I only want to do this with(conditioal statements), It's possible either with classList.toggle() but I don't want to.</p>
Struggling to have the script work 'on click' by selecting one of the 4 random colour classes.
Currently selects one at random, but does not refresh on individual clicks of #myNav.
I have tried using toggleClass also, however I believe it is down to poor coding as I am very new to js.
$(document).ready(function(){
var colors = ['black','blue','mistyrose','white'];
var new_color = colors[Math.floor(Math.random()*colors.length)];
$('#myNav').addClass(new_color);
});
may be this
$(document).ready(function() {
var colors = ['black','blue','mistyrose','white'];
function getRandomColor() {
return colors[ Math.floor(Math.random() * colors.length) ];
}
$('.button').click(function() {
var color = getRandomColor();
$('#myNav').addClass(color);
});
});
Try
myNav.classList.toggle(new_color);
function changeColor() {
var colors = ['black', 'blue', 'mistyrose', 'white'];
var new_color = colors[Math.floor(Math.random() * colors.length)];
myNav.classList.toggle(new_color);
}
.box { width: 100px; height: 100px; border: 1px solid black; cursor: pointer; }
.black { background: black; }
.blue { background: blue; }
.mistyrose { background: mistyrose; }
.white { background: white; }
<div id="myNav" class="box" onclick="changeColor()"></div>
So I made a bunch of divs stacked on each other, and I want each div to change its background color whenever its hover, but that's not what happens
When I hover an item its background color should change to green,
but it doesn't work even that I wrote div.oldiv:hover{background-color: #48FF0D;}
The problem is probably in CSS code.
Here is a snippet :
body{
background-color: #48FF0D;
}
#bigdiv {
height: 90%;
width: 100%;
}
.oldiv {
height: 0.390625%;
width: 100%;}
div.oldiv:hover{
background-color: #48FF0D;
}
#bigdiv2 {
height: 0;
width: 100%;
}
.btn {
border: none;
color: white;
padding: 14px 28px;
cursor: pointer;
}
.uptodown {
background-color: #e7e7e7;
color: black;
}
.uptodown:hover {
background: #ddd;
}
.l{
float: right;
}
<body>
<script>
var b = "",k = "",a,q,d;
for(a = 0;a<=256;a++){
d =" <div id=\"du\" class=\"oldiv\" style=\"background-color: rgb("+a+","+a+","+a+");\"></div>";
q =" <div id=\"du\" class=\"oldiv\" style=\"background-color:rgb("+(256-a)+","+(256-a)+","+(256-a)+");\"></div>";
b = b+"\n"+d;
k = k+"\n"+q;
}
window.onload = function (){
document.getElementById("bigdiv").innerHTML = b;
document.getElementById("bigdiv2").innerHTML = k;
}
function utd(a){
var bigdiv = document.getElementById("bigdiv");
var bigdiv2 = document.getElementById("bigdiv2");
if(a == 0){
bigdiv.style.height = "0";
bigdiv2.style.height= "90%";
}else{
bigdiv.style.height = "90%";
bigdiv2.style.height= "0";
}
}
</script>
<div id="bigdiv">
</div>
<div id="bigdiv2">
</div>
<div>
<button class="btn uptodown" onclick="utd(0)">white to black</button>
<button class="btn uptodown l" onclick="utd(1)">black to white</button>
</div>
</body>
Don't word about all the Javascript, its just to generate elements and adding them to HTML
I have no idea what the purpose of this code is, but I think I have fixed it..... Whatever it is :P
Your #bigdiv and #bigdiv2 percentage height were not working because the height of the document wasn't 100%. So I just added html, body {height:100%;} to fix that.
/* code added START */
html, body {
height:100%;
}
div.oldiv:hover {
background-color: #48FF0D!important;
}
/* code added END */
body{
background-color: #48FF0D;
}
#bigdiv {
height: 90%;
width: 100%;
}
.oldiv {
height: 0.390625%;
width: 100%;
}
/* div.oldiv:hover{background-color: #48FF0D;} */
#bigdiv2 {
height: 0;
width: 100%;
}
.btn {
border: none;
color: white;
padding: 14px 28px;
cursor: pointer;
}
.uptodown {
background-color: #e7e7e7;
color: black;
}
.uptodown:hover {
background: #ddd;
}
.l {
float: right;
}
<script>
var b = "",k = "",a,q,d;
for(a = 0;a<=256;a++){
d =" <div id=\"du\" class=\"oldiv\" style=\"background-color: rgb("+a+","+a+","+a+");\"></div>";
q =" <div id=\"du\" class=\"oldiv\" style=\"background-color:rgb("+(256-a)+","+(256-a)+","+(256-a)+");\"></div>";
b = b+"\n"+d;
k = k+"\n"+q;
}
function utd(a) {
var bigdiv = document.getElementById("bigdiv");
var bigdiv2 = document.getElementById("bigdiv2");
if(a == 0) {
bigdiv.style.height = "0";
bigdiv2.style.height= "90%";
} else {
bigdiv.style.height = "90%";
bigdiv2.style.height= "0";
}
}
</script>
<div id="bigdiv">
<script>document.write(b);</script>
</div>
<div id="bigdiv2">
<script>document.write(k);</script>
</div>
<div>
<button class="btn uptodown" onclick="utd(0)">white to black</button>
<button class="btn uptodown l" onclick="utd(1)">black to white</button>
</div>
Well, there is no use of Javascript here. I'm not able to understand what problem you're facing but refer here : https://www.w3schools.com/cssref/sel_hover.asp
CSS already has property of hover and can be used like element:hover {your properties inside like whatever event has to be happened on hover}. There is no need to use JS here. Hope this helps.
UPDATE:
I would also suggest you to follow good practice of writing JS code and CSS code in a separate file not in a HTML file.
I was doing some initial testing in jsFiddle as follows: https://jsfiddle.net/6pqxfy2o/
$(function(){
console.log("fired");
$("div").each(function(){
console.log($(this).attr("class"));
console.log($(this).css("background-color"))})
})
.color{
background-color:teal;
}
.dim{
width: 200px;
height: 200px;
}
.sub-dim{
width: 50px;
height:50px;
border: solid 1px white;
}
.ping {
background-color: cyan;
}
.ack {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dim color">
<div class="sub-dim ack">
</div>
<div class="sub-dim ping">
</div>
<div class="sub-dim">
</div>
</div>
This was showing that when running, it did not actually pass the inherited color into the child.
I am curious though how I can get the background color of the sub-dim which has no background color, such as: current background-color or nearest.
My end goal would be to say: When iterating over sub-dim to return [red, cyan,teal] or color codes. Based on the item I gave you, the div is transparent and the parent's color is showing through.
If the color is transparent, you can just set it to inherit and get the new computed color.
// Some browsers say "transparent" and some "rgba(0, 0, 0, 0)"
var transparent = (function() {
var backup = document.body.style.backgroundColor;
document.body.style.backgroundColor = 'transparent';
var bg = getComputedStyle(document.body).backgroundColor;
document.body.style.backgroundColor = backup;
return bg;
})();
[].forEach.call(document.getElementsByTagName("div"), function(el) {
var bg = getComputedStyle(el).backgroundColor;
if (bg === transparent) {
var backup = el.style.backgroundColor;
el.style.backgroundColor = 'inherit';
bg = getComputedStyle(el).backgroundColor;
el.style.backgroundColor = backup;
}
console.log(el.className, ":", bg);
});
.color {
background-color: teal;
}
.dim {
width: 200px;
height: 200px;
}
.sub-dim {
width: 50px;
height: 50px;
border: solid 1px white;
}
.ping {
background-color: cyan;
}
.ack {
background-color: red;
}
<div class="dim color">
<div class="sub-dim ack"></div>
<div class="sub-dim ping"></div>
<div class="sub-dim"></div>
</div>
I'm not sure I completely understand the problem, but you could try
.sub-dim.ack {
background-color: red;
}
or
.ack, .ack * {
background-color: red;
}
Obviosly try to be ore specific with which child elements you'd like to target.
This would likely be a lot easier in SASS.
I am new to jQuery and I am experimenting a bit here. Please be patient.
I am trying to give div's a "random" background color on hover. If the div is not hovered I want them to be white.
I realize that random may not be the right word here because I want the script to chose a color from the following array, preferably in the same order: ['#009c61', '#cc0099', '#cc9900', '#cc0033', '#0099cc', '#6600cc', '#66cc00']
I guess some of the problem is because all divs have the same class.
How can this be achieved with jQuery?
jQuery(document).ready(function($) {
var bgColorArray = ['#009c61', '#cc0099', '#cc9900', '#cc0033', '#0099cc', '#6600cc', '#66cc00'],
selectBG = bgColorArray[Math.floor(Math.random() * bgColorArray.length)];
$('.article-container').css('background-color', selectBG)
});
.article-container {
color: #000;
font-family: 'Oswald', sans-serif;
text-align: center;
height: 200px;
width: 200px;
border: solid 3px #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="article-container">Div 1</div>
<div class="article-container">Div 2</div>
<div class="article-container">Div 3</div>
<div class="article-container">Div 4</div>
So far I have tried this:
jQuery(document).ready(function($) {
var bgColorArray = ['#009c61', '#cc0099', '#cc9900', '#cc0033', '#0099cc', '#6600cc', '#66cc00'],
selectBG = bgColorArray[Math.floor(Math.random() * bgColorArray.length)];
$('.article-container').css('background-color', selectBG)
});
Problem is this changes the color on page refresh and it changes the bg color of all divs.
Try to use .hover(mouseInHandler,mouseOutHandler) function at this context,
var colors = ['#009c61', '#cc0099', '#cc9900', '#cc0033', '#0099cc', '#6600cc', '#66cc00'];
$(".article-container").hover(function() {
$(this).css("background-color", colors[(Math.random() * colors.length) | 0])
}, function() {
$(this).css("background-color", "")
});
DEMO
Take a look at this
Jquery :
$(document).ready(function()
{
$("a").hover(function(e)
{
var randomClass = getRandomClass();
$(e.target).attr("class", randomClass);
});
});
function getRandomClass()
{
//Store available css classes
var classes = new Array("green", "purple", "teal", "violet", "pink");
//Give a random number from 0 to 5
var randomNumber = Math.floor(Math.random()*6);
return classes[randomNumber];
}
CSS :
a.green:hover { color: #1ace84; }
a.purple:hover { color: #a262c0; }
a.teal:hover { color: #4ac0aa; }
a.violet:hover { color: #8c78ba; }
a.pink:hover { color: #d529cd; }
Searched on google and got it from Telmo
Cool idea. I just wanted to take a stab at making something pretty.
var numberOfBlocks= 250;
var colors = ['#009c61','#cc0099','#cc9900','#cc0033','#0099cc','#6600cc','#66cc00'];
var lastColor = 0;
(function init() {
var wrap = document.getElementById('wrap');
var block = document.createElement('div');
block.setAttribute('class', 'block');
for(var i=0; i<numberOfBlocks; i++) {
wrap.appendChild(block.cloneNode(true));
}
$('.block').hover(function() {
$(this).css('background-color', colors[lastColor++])
lastColor = (lastColor>=colors.length?0:lastColor);
},
function() {
$(this).css('background-color', '#fff');
});
})();
.block {
width: 20px;
height: 20px;
border: 1px solid white;
display: inline-block;
margin-top: -5px;
margin-left: -1px;
transition: all .1s ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrap">
</div>