Apply random color to class elements individually?
$(document).ready(function() {
$('.main').each(function () {
var hue = 'rgb(' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ')';
$(this).css("background-color", hue);
});
});
Generate random colors for each box individually all at the same time using JQuery, HTML, and CSS
This is what you want:
var myColors = ['red', 'purple', '#E84751', 'blue', 'orange', '#323643', '#97FF73', '#362EFF', '#FF6513'];
function clickMe() {
$(".square").each(function() {
var randomize = Math.floor(Math.random() * myColors.length);
$(this).css("background-color", myColors[randomize]);
});
}
function cloneMe() {
$(document).ready(function() {
$(".square:first").clone().attr('class', 'square').appendTo('.orange-square-container');
clickMe();
});
}
Inside your clickMe
function you forgot to change $("#square")
to $(".square")
i've moved the randomize
into the .each
function.
Demo
var myColors = ['red', 'purple', '#E84751', 'blue', 'orange', '#323643', '#97FF73', '#362EFF', '#FF6513'];
function clickMe() { $(".square").each(function() { var randomize = Math.floor(Math.random() * myColors.length); $(this).css("background-color", myColors[randomize]); });
}
function cloneMe() { $(document).ready(function() {
// var i = 1; // while(i <= 5) { $(".square:first").clone().attr('class', 'square').appendTo('.orange-square-container'); clickMe(); // i++;
});}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div class="btn-alt-container"> <a class="btn btn1-alt" onclick='clickMe()'>Push Me</a> <div class="btn btn2-alt" onclick='cloneMe()'>Make More</div></div>
<div class="container"></div>
<div class="orange-square-container"> <div class="square"> <div class="content"> Hack Reactor's Awesome :) </div> </div></div>
Random color for div tag generated by jquery is not permanent
The library you're using ScrollReveal
is replacing your css with its own. Cleaning up your code snippet, and removing the library makes your code work fine - ie, there was nothing in particular wrong with the jQuery you had written to assign random background colours to elements on your page
var colors = ['red', 'green', 'blue', 'orange', 'yellow'];$(document).ready(function() { $(".random-color").each(function() { $(this).css('background-color', colors[Math.floor(Math.random() * colors.length)]); });});
div { height: 40px; padding: 10px; text-align: center; margin-bottom: 10px;}#d1 { background-color: #00A388;}#d2 { background-color: #FFFF9D;}#d3 { background-color: #BEEB9F;}#d4 { background-color: #79BD8F;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><!DOCTYPE html><html>
<body>
<p data-sr>Scroll Reveal-Default</p>
<!--Enter Properties The enter keyword controls the vector origin (direction) of your animation.--> <!-- Reveal with a downward motion --> <div class="random-color" data-sr='enter top'>enter top</div> <br>
<!-- The other accepted values... --> <div class="random-color" data-sr='enter left'>enter lef</div> <br> <div class="random-color" data-sr='enter right'>enter right</div> <br> <div class="random-color" data-sr='enter bottom'>enter bottom</div> <br> <!--Enter Properties Ends-->
<!--Move Properties The move keyword controls the distance (in pixels) traveled during animation.--> <div class="random-color" data-sr='move 24px'>move 24px</div> <!--Enter Properties Ends--> Over The over keyword sets the duration (in seconds) of your animation.
<div class="random-color" data-sr='over 0.6s'>over 0.6s</div> <div class="random-color" data-sr='over 1.3s'>over 1.3s</div> Flip The flip keyword is a rotation keyword, controlling rotation along the X axis (pitch).
<div class="d1" data-sr="enter left, hustle 20px">enter left, hustle 20px</div> <div class="d2" data-sr="wait 2.5s, ease-in-out 100px">wait 2.5s, ease-in-out 100px</div> <div class="d3" data-sr="move 16px scale up 20%, over 2s">move 16px scale up 20%, over 2s</div> <div class="d4" data-sr="enter bottom, roll 45deg, over 2s">enter bottom, roll 45deg, over 2s</div>
</body>
</html>
Apply random class to multiple groups of elements with no repeat
You're on the right track.
Without speaking of methods to optimize the code, here's (one) way to get quickly to where you need to be:
function shuffle(obj) {
var l = obj.length,
i = 0,
rnd,
tmp;
while (i < l) {
rnd = Math.floor(Math.random() * i);
tmp = obj[i];
obj[i] = obj[rnd];
obj[rnd] = tmp;
i += 1;
}
}
// declare OUTSIDE the function for correct scope
var classes;
// Simple function to set up the classes variable and shuffle.
function setUpClasses() {
classes = ["centre", "left", "right"];
shuffle(classes);
}
jQuery(".mini-thumbnail-individual-image").each(function() {
// Check if classes is set / empty. If so, set up the classes again.
if (!classes || classes.length < 1) {
setUpClasses();
}
jQuery(this).addClass(classes.pop());
});
If you want to look at cleaner / briefer ways to shuffle the array, this article has some other techniques. Here's one of them:
yourArray.sort(function() { return 0.5 - Math.random() });
So you could literally remove your shuffle function, and just do this:
function setUpClasses() {
classes = ["centre", "left", "right"];
classes.sort(function() { return 0.5 - Math.random() });
}
Or, if you wanted maximum brevity:
function setUpClasses() {
classes = ["centre", "left", "right"].sort(function() { return 0.5 - Math.random() });
}
Here is a working Fiddle
Random Color From Array
How about this?
var rgb = [];
for(var i = 0; i < 3; i++)
rgb.push(Math.floor(Math.random() * 255));
myDiv.style.backgroundColor = 'rgb('+ rgb.join(',') +')';
If you want to constrict it to known colors, you can create an array of the colors and randomly select it like so.
var colors = ['red', 'green', 'blue', 'orange', 'yellow'];
myDiv.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
JSFiddle
Update - Using the first method to apply to all .post-content
.
var divs = document.querySelectorAll('.post-content');
for(var i = 0; i < divs.length; i++)
divs[i].style.backgroundColor = 'rgb('+ rgb.join(',') +')';
If you want to apply a random background to each .post-content
individually, you would do this.
var divs = document.querySelectorAll('.post-content');
for(var i = 0; i < divs.length; i++) {
var rgb = [];
for(var i = 0; i < 3; i++)
rgb.push(Math.floor(Math.random() * 255));
divs[i].style.backgroundColor = 'rgb('+ rgb.join(',') +')';
}
Last Update - using jQuery, as you mentioned.
var colors = ['red', 'green', 'blue', 'orange', 'yellow'];
$('.post-content').each(function() {
$(this).css('background-color', colors[Math.floor(Math.random() * colors.length)]);
});
Easiest way to put different background colours to each diffrent element
Use nth-child
pseudo class
.gridTab:nth-child(1){background:red}
.gridTab:nth-child(2){background:lime}
.gridTab:nth-child(3){background:green}
.gridTab:nth-child(4){background:violet}
DEMO
If you are looking for IE9 below solution then use the following method
For IE7+ Support
.gridTab:first-child {background:red}
.gridTab:first-child + div.gridTab{background:lime}
.gridTab:first-child + div + div.gridTab{background:green}
.gridTab:first-child + div + div + div.gridTab{background:violet}
DEMO for IE7+
Related Topics
Make a <Br> Instead of <Div></Div> by Pressing Enter on a Contenteditable
Duplicating an Element (And Its Style) with JavaScript
Dynamically Changing Stylesheet Path Not Working in Ie and Firefox
Detecting Click Event on Padding Only
Auto Image Resize Based on Browser Window Dimensions
How to Set a External Svg Color in HTML Using CSS
Convert Gulp Watch in Gulp@3.9.1 to Gulp@4
How to Remove the White Border from Chart.Js Pie Chart
How to Make a Rotated Element Height:100% of Its Parent
How to Access the Content of the "Embed" Tag in HTML
Apply Random Color to Class Elements Individually
Wrap Text Inside Fixed Div with CSS or JavaScript
Google Chrome Customize Developer Tools Theme/Color Schema
Copy All Styles from One Element to Another
Automatic Two Columns with CSS or JavaScript
How to Pass Styles to Child Component and Use It as Scoped Style in Vue