How can you randomize hover effects?
For example:
<p>test</p>
p:hover {
background: yellow;
}
p:hover:
background: red;
}
Please note that the above is for-example only. The question is, how can you randomize hover effects, so it shows the background:yellow; and background:red; once in random order on the onmouseover?
There should not be any order, like for example: on first hover - one class is added, on second - another. It should be completely random.
Use the following function to get random colors and use mouseover event to change the background color.
function getRandomColor () {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
})
$( "p" ).mouseover(function() {
$(this).css("background",getRandomColor());
});
Please check this Fiddle.
You could add a random class to the element on hover and remove it when the hover event is done.
If you have the following CSS:
.yellow {
background: yellow;
}
.red {
background: red;
}
You could use the follow jQuery code example:
// Declare all classes that can be used in the random selection
var classes = ['yellow', 'red'];
$("p").hover(
function() {
// Select a random class
var randomClass = classes[Math.floor(Math.random() * classes.length)];
$(this).addClass(randomClass);
}, function() {
$(this).removeClass();
}
);
You can check an example on this Fiddle.
The random selection is made on the classes array using the Math.random() function.
$(document).ready(function(){
$("p[data-random]").mouseover(function(){
max_value=5;
random_value= Math.floor((Math.random() * max_value) + 1);
$(this).attr("data-random",random_value);
});
})
p[data-random]{
padding: 10px;
border:1px solid black;
}
p[data-random]:hover {
cursor: pointer
}
p[data-random="1"]:hover {
background: yellow;
}
p[data-random="2"]:hover {
background: red;
}
p[data-random="3"]:hover {
background: black;
}
p[data-random="4"]:hover {
background: white;
}
p[data-random="5"]:hover {
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p data-random="1">Hello</p>
This is best way to do random effect on background, here I have considered 5 colors for random effect.
You should play with setting different classes using javascript.
For example something like that (jquery) :
var randomClasses = ['class1','class2','class3'];
$('p').mouseover(function(){
$(this).toggleClass(function() {
var randomColor = randomClasses[getRandomInt(0,randomClasses.length-1)];
return randomColor;
});
})
function getRandomInt(min, max)
{
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Related
I need to make a function that changes the background colour to various colours(as an animation). I have used for loop to change hexadecimal colour code. But only I can see the changing it into one colour.
function changeColors() {
var colors = 000100;
for (var i = 0; i < 99999; i++) {
colors += i;
var x = (document.body.style.backgroundColor = "#" + colors);
}
}
changeColors();
body {
background-color: #80eb80;
}
<html>
<body></body>
</html>
function changeHex() {
let hex = '#';
const hexValues = [0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F'];
for (let i = 0; i < 6; i++) {
const index = Math.floor(Math.random() * hexValues.length);
hex += hexValues[index];
}
document.querySelector('body').style.backgroundColor = hex;
}
setInterval(() => changeHex(), 1500);
You can check it by this URL here
You don't need JavaScript for this. This can be easily done by using CSS animation.
#keyframes bg {
0% { background: #000000; }
25% { background: #000099; }
50% { background: #009999; }
75% { background: #999999; }
100% { background: #000000; }
}
body {
background: #000;
animation: bg 5s linear infinite;
}
Just change the colors to whatever you want. Working example: https://codepen.io/CodinCat/pen/bGaYRVz?editors=0100
If you need to start the animation dynamically by JavaScript, just put the animation part to a CSS class and toggle the class.
And just some additional notes. The reason that your code is not working is because your for loop is synchronous. The entire for loop ends immediately, maybe a few milliseconds. Browsers are smart enough to execute the JavaScript at once, and then re-paint the screen only once.
Is it possible to change the color of val without changing the color of "Solution" and have them display in the same line (code shown below)?
result.innerText = "Solution:" + val.toFixed(2);
I know that you can add
result.style="color:red";
but that changes the color of the entire line including "solution:" when I run;
<div id="result" align ="center"></div>
EDIT: Changes I made by adding pseudo element and classes but nothing is displayed apart from "Solution"
val = sumsc/sumcr;
var result = document.querySelector('#result');
if(isNaN(sumsc/sumcr)){
val=0.00;
result.innerText = val.toFixed(2);
result.className = "white";
else if(val<3 & val>0.1){
result.innerText = val.toFixed(2);
result.className = "red";
}
else if(val>3 & val<3.5){
result.innerText = val.toFixed(2);
result.className = "pink";
}
else if(val>3.5){
result.innerText = val.toFixed(2);
result.className = "green";
}
#result{
text-align:center;
}
#result::before {
content: "Solution: ";
color: black;
}
.white {
color: white;
}
.red {
color: red;
}
.pink{
color: pink;
}
.green{
color: green;
}
Surrounding val with a span and adding styles to it should work:
result.innerHTML = 'Solution: <span class="red">' + val.toFixed(2) + '</span>';
.red {
color: red;
}
An alternate might be to put the span in the markup, <div id="result">Solution:<span class="solutionval"></span></div> then just change the text/value there.
let resutltTextSpan = document.getElementById('result')
.getElementsByClassName('solutionval')[0];
resutltTextSpan.innerText = val.toFixed(2);
Here I use a function so you can see simple changes over time with set of timeout functions that call it with a value.
More information on adding, removing, toggle etc. of classes : https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
EDIT: added toggle of class as that might be most elegant given the comments.
function setVal(val = 0) {
let resutltTextSpan = document.getElementById('result')
.getElementsByClassName('solutionval')[0];
resutltTextSpan.innerText = val.toFixed(2);
// now we can do other things
if (val === 0) {
resutltTextSpan.classList.add("unset");
}
if (val > 0 && val < 9000) {
resutltTextSpan.classList.add("good");
}
resutltTextSpan.classList.toggle("bad",(val > 9000 && val <= 9300) );
if (val > 9900) {
resutltTextSpan.classList.add("ugly");
}
}
let val = 456;
setVal(); //use default 0 since we pass nothing
setTimeout(function() {
val = 9200.2455;
setVal(val);
}, 5000);
// change it after 10 seconds
setTimeout(function() {
val = 9934.56;
setVal(val);
}, 10000);
#retult {
text-align: center;
}
.solutionval.unset {
color: #0000ff;
}
.solutionval {
color: #ffffff;
}
.solutionval.good {
color: #00ff00;
}
.solutionval.bad {
font-weight: bold;
}
.solutionval.ugly {
color: #ff0000;
}
<div id="result">Solution:<span class="solutionval"></span></div>
You can do this by creating a ::before pseudo element of the word "solution" - this allows you to set the value of the number and have the text automatically placed as the first child of the div.
EDIT: I have addded a ternary equation to allow the changing of the color based on the value. Note that this has to be determined from the number not the .toFixed(2) value since that is now a string. This can be used as regular if / else statements if there are more than two options.
Also - it is better to apply styles via adding / removing classes than directly targetting the style attribute withing the JS.
var val = 13.789;
var result = document.querySelector('#result');
result.innerText = val.toFixed(2);
val > 10
? result.className = "red"
: result.className = "blue"
#result{
text-align:center;
}
#result::before {
content: "Solution ";
color: black;
}
.red {
color: red;
}
.blue {
color: blue;
}
<div id="result"><div>
I have a JS which picks out a random div from a "list" of divs, shows it for a few seconds and fades it out, all in a random loop.
Now logically, sometimes the same div is picked directly one after another. I want to prevent this. The best case would be, if the JS would process all divs of the list in a random order, before it will start a new random "round". So e.g. div no. 5 would not be shown again directly on after another.
Here is my JS:
var myVar;
function showDiv() {
var random = Math.floor(Math.random() * $('.notification').length);
$('.notification').eq(random).prependTo('.container').fadeIn(200).delay(3000).fadeOut(200);
createRandomInterval();
}
function createRandomInterval() {
setTimeout(showDiv, 500 + Math.random() * 4000);
}
$(document).ready(function() {
createRandomInterval();
});
Here is my complete fiddle: https://jsfiddle.net/brapbg1h/
What I would do is store the last result, and if it lands on it, then process again.
something like this.
let lastResult = -1;
function getRandom() {
const res = Math.floor(Math.random() * $('.notification').length);
return res === lastResult ? getRandom() : res;
}
function showDiv() {
var random = getRandom();
lastResult = random;
$('.notification').eq(random).prependTo('.container').fadeIn(200).delay(3000).fadeOut(200);
createRandomInterval();
}
Save the random to a global variable, like lastDiv. Check random against lastDiv and it is a match, re-run the function again.
var lastDiv;
function showDiv() {
var random = Math.floor(Math.random() * $('.notification').length);
if(random == lastDiv) {
console.log('random matches lastDiv, re-running.');
return showDiv();
}
lastDiv = random;
$('.notification').eq(random).prependTo('.container').fadeIn(200).delay(3000).fadeOut(200);
createRandomInterval();
}
function createRandomInterval() {
setTimeout(showDiv, 500 + Math.random() * 4000);
}
$(document).ready(function() {
createRandomInterval();
});
.notification {
width: 200px;
height: 50px;
background-color: yellow;
border: 1px solid rgba(0, 0, 0, 0.2);
margin-bottom: 5px;
text-align: center;
padding-top: 20px;
display: none;
/* hide initially so that fadIn() fadeOut() will work */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div class="container">
<div class="notification">1</div>
<div class="notification">2</div>
<div class="notification">3</div>
<div class="notification">4</div>
</div>
Previous Div in a variable
If you do not want 2 consequent divs to be the same, just assign the number of the div (since it is from a list) to a variable and if it is equal to current selection run the function again in a do..while loop.
var random;
function showDiv() {
do {
var random = Math.floor(Math.random() * $('.notification').length);
} while(random==previousDiv);
$('.notification').eq(random).prependTo('.container').fadeIn(200).delay(3000).fadeOut(200);
createRandomInterval();
var previousDiv = random;
}
This code works, but how can I make it so that only a div changes color as oppose to the entire body?
var color = function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
setInterval(function() {
document.body.style.backgroundColor = color(); //() to execute the function!
}, 1000);
div {
font-family: cursive;
font-size: 3em;
text-align: center;
width: full;
height: 100px;
}
<div></div>
You need to be able to query the DOM for the correct element. A very simple way of doing this would be to use document.querySelector which uses CSS selector style syntax to find elements in the DOM. Using that, your code would look like this.
var color = function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
setInterval(function() {
document.querySelector('div').style.backgroundColor = color(); //() to execute the function!
}, 1000);
div {
font-family: cursive;
font-size: 3em;
text-align: center;
width: full;
height: 100px;
}
<div></div>
But that's just one way of querying the DOM. You could use document.getElementsByTagName which retrieves a collection of every element with the matching tag.
var divs = document.getElementsByTagName('div');
// Change the first one
divs[0].style.backgroundColor = color();
You could also give the div an ID and use document.getElementById:
<div id="coloredDiv"></div>
--
document.getElementById('coloredDiv').style.backgroundColor = color();
There are numerous ways of querying the DOM, just use the one that works best for your situation.
You can assign an id to div and set it's color by accessing it by getElementById
<script>
var color = function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
setInterval(function() {
document.getElementById("mydiv").style.backgroundColor = color(); //() to execute the function!
}, 1000);
</script>
div {
font-family: cursive;
font-size: 3em;
text-align: center;
width: full;
height: 100px;
}
<body>
<div id="mydiv"></div>
</body
I'm new to JavaScript but moving over from ActionScript, so I'm using a lot of AS3 logic and not sure what's possible and not.
I have a series of 5 dots for an image slider nav. The dots are just CSS styled dots, so I'm trying to make it so I can control the colors using element.style.backgroundColor.
Here's my script:
function btnFeatured(thisBtn) {
btnFeatured_reset();
for (i = 1; i <= 5; i++) {
if (thisBtn === document.getElementById("dotFeat" + i)) {
document.getElementById("dotFeat" + i).style.backgroundColor = "#ffae00";
}
}
}
function btnFeatured_reset() {
for (i = 1; i <= 5; i++) {
document.getElementById("dotFeat" + i).style.backgroundColor = "#969696";
}
}
Seems to work just fine, but when I click the dot, it turns orange (ffae00) and then immediately turns back to gray (969696).
And just in case, here's the style I'm using for the dots:
#featured-nav a {
display: inline-block;
width: 8px;
height: 8px;
border-radius: 8px;
background-color: #969696;
border-bottom: none;
margin: 0 14px;
}
#featured-nav a:hover {
background-color: #ffae00;
border-bottom: none;
}
And my html:
Change the HTML to
test
test
test
test
test
and the JS:
function btnFeatured(thisBtn) {
for (i = 1; i <= 5; i++) {
var state = parseInt(thisBtn.id.slice(-1),10) == i,
elem = document.getElementById("dotFeat" + i);
elem.style.backgroundColor = (state ? "#ffae00" : "#969696");
}
return false;
}
FIDDLE
Even better would be to not use inline JS, but proper event handlers.