Css3 div gradient background animation based upon a counter value? [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
My requirement is to change the div gradient background with an animation according to a increasing counter value.
For instance, suppose if a div background gradient is blue-white at counter=== 0.
When counter value is in range of [80, 100], then the div goes to danger range hence the background gradient is suppose to turn in red-white with animation.
I tried doing several tries, however cant do it gracefully.
Can some one tell me how can i acheive it?

I think you could made an adaptative solution. In this example, we are moving :
FROM : background-image: linear-gradient(rgba(220, 20, 20, 1) 0, rgba(255, 255, 255, 1));
TO : background-image: linear-gradient(rgba(20, 120, 220, 1) 0, rgba(255, 255, 255, 1));
Here is the code:
Stylesheet
*{
padding: 0;
margin: 0;
background-color: transparent;
background-image: none;
}
div{
display: block;
margin: 5px;
width: 500px;
height: 300px;
border-radius: 5px;
border: 1px rgba(220, 220, 220, 1) solid;
box-shadow: 1px 3px 9px rgba(220, 220, 220, 1);
background-image: linear-gradient(rgba(20, 120, 220, 1) 0, rgba(255, 255, 255, 1));
transition-duration: .7s;
-o-transition-duration: .7s;
-moz-transition-duration: .7s;
-webkit-transition-duration: .7s;
}
HTML BODY CONTENT
<div data-index="0"></div>
<b>Counter : </b><output></output>
<script type="text/javascript" src="js/JQuery/jquery-2.1.1.js"></script>
Javascript content
$(function() {
var linearDefinition = 'linear-gradient(rgba(RED, BLUE, GREEN, 1) 0, rgba(255, 255, 255, 1))';
setInterval(function() {
var count = parseInt($('div').data('index'));
count = (count === 100) ? 0 : count;
var red = 20 + ((1 + count) * 2);
var blue = 120 - count;
var green = 220 - (2 * (1 + count));
// Asume this is your couter instruction
$('div').data('index', 1 + count);
$('output').text($('div').data(('index')));
$('div').css('background-image', linearDefinition.replace(/RED/, red).replace(/BLUE/, blue).replace(/GREEN/, green))
}, 50);
});

Related

The click events runs only after clicking twice or three times

<html>
<head>
<title>Random manga</title>
<script src="./js/my.js"></script>
<link type="text/css" rel="stylesheet" href="./css/style.css">
</head>
<body>
<div id="al">
<div id="pic">
<img src="" id="img" style="visibility: hidden;">
</div>
<button id="btng" onclick="my()">Suggest me manga</button>
</div>
</body>
</html>
Here is the html for button div and other things
Below is the css
body
{
background : white;
color : black;
}
#pic
{
border-radius : 25px;
background-color : #f2f2f2;
-webkit-border-radius : 35px;
-moz-border-radius : 75px;
box-shadow: rgba(0, 0, 0, 0.25) 0px 54px 55px, rgba(0, 0, 0, 0.12) 0px -12px 30px, rgba(0, 0, 0, 0.12) 0px 4px 6px, rgba(0, 0, 0, 0.17) 0px 12px 13px, rgba(0, 0, 0, 0.09) 0px -3px 5px;
background-size : cover;
text-align : center;
height: 400px;
width: 400px;
background-size : cover;
background-repeat: no-repeat;
background-position: center;
}
#btng
{
backface-visibility: hidden;
background-color: #405cf5;
border-radius: 6px;
border-width: 0;
box-shadow: rgba(50, 50, 93, .1) 0 0 0 1px inset,rgba(50, 50, 93, .1) 0 2px 5px 0,rgba(0, 0, 0, .07) 0 1px 1px 0;
color: #fff;
font-size: 100%;
height: 44px;
line-height: 1.15;
margin: 12px 0 0;
outline: none;
overflow: hidden;
padding: 0 25px;
position: relative;
text-align: center;
text-transform: none;
transform: translateZ(0);
transition: all .2s,box-shadow .08s ease-in;
width: 50%;
}
#btng:focus {
box-shadow: rgba(50, 50, 93, .1) 0 0 0 1px inset, rgba(50, 50, 93, .2) 0 6px 15px 0, rgba(0, 0, 0, .1) 0 2px 2px 0, rgba(50, 151, 211, .3) 0 0 0 4px;
}
#al
{
text-align : center;
position : absolute;
top : 50%;
left : 50%;
transform : translate(-50%, -50%);
}
#img{
height: 100%;
width: 100%;
}
And below the function for onclick on button
function my(){
var bt=document.getElementById("btng");
bt.textContent = "Suggest me another";
var my = new Array("im/R.jpg","im/S.jpg","im/E.jpg");
var randomNum = Math.floor(Math.random() * my.length);
var backgroundImage = my[randomNum];
document.getElementById("img").src = my[randomNum];
document.getElementById("pic").style.backgroundImage=`url(${backgroundImage})`;
}
The onclick event only runs after the button is clicked twice or thrice sometimes I tried doing something to slove it but I was unsuccessful, is there any way to do it? Here is the live preview:- https://mangasuggestions.000webhostapp.com/index.html
Please click on buttons 4/5 times to get the problem I am facing.
The onclick event and the function is working properly. The image didn't update is because the randomNum is the same as the previous one.
Our goal is to prevent using the same number that is generated previously.
One way to do this is to keep track of the last generated random number, and regenerate until it is different from the previous one.
Main logic
let randomNum;
do {
randomNum = Math.floor(Math.random() * images.length);
} while (randomNum === prevRandomNum);
prevRandomNum = randomNum
Full code (With some modification of your original code)
// Keep track of the last random number
let prevRandomNum = -1
function my(){
const btn = document.getElementById("btng");
btn.innerText = "Suggest me another";
const images = ["im/R.jpg","im/S.jpg","im/E.jpg"];
let randomNum;
do {
randomNum = Math.floor(Math.random() * images.length);
} while (randomNum === prevRandomNum);
prevRandomNum = randomNum
const backgroundImage = images[randomNum];
document.getElementById("pic").style.backgroundImage=`url(${backgroundImage})`;
}
Please make the button type="button". it seems working.
<button id="btng" type="button" onclick="my()">Suggest me another</button>
As #AndrewLi already answered, there is possibilty that generated random number is the same as the last one.
Instead of generating new number multiple times (with while loop).
You can filter out currently displayed image from array.
function my(){
var bt=document.getElementById("btng");
bt.textContent = "Suggest me another";
var img = document.getElementById("img");
var my = new Array("/im/R.jpg","/im/S.jpg","/im/E.jpg").filter((src) => src !== new URL(img.src).pathname);
var randomNum = Math.floor(Math.random() * my.length);
var backgroundImage = my[randomNum];
document.getElementById("img").src = my[randomNum];
document.getElementById("pic").style.backgroundImage=`url(${backgroundImage})`;
}
But to make it work, you need provide absolute path to your images in array.
So /im/R.jpg instead of im/R.jpg
Here is the probably most efficient way to do this without filtering the values causing a loop or re-generating values in case we get a duplicate using some index manipulation.
Explanation
For the first image we can select any image within the set of valid indices for the array i.e. 0 to array.length - 1 which we can do using Math.floor(Math.random() * array.length). Then we store the selected index in a variable currentImageIdx.
For any following image we generate a step value which determines the amount of steps we want to move on from the current index to the next value. We need to choose this in the range of 1 to array.length - 1 which we can do by using Math.floor(1 + Math.random() * (arrayLength - 1)) as this will make sure we will never move on so far that we are back at the same index as we currently are. We then just need to add that step value to the current index and take the remainder using modulo to make sure we're not getting out of bounds.
Examples for moving on to next index
For the following examples an array with 3 values is assumed:
We're currently at index 0 so we should either move on 1 or 2 steps. If we were to move on 3 steps we would be at 0 again because (start index + step) % array.length would translate to (0 + 3) % 3 = 0 and we'd be at the start index again.
If we're at index 1 we could again move on 1 or 2 steps but not 3 because (start index + step) % array.length would translate to (1 + 3) % 3 = 1 and we'd be at the start index again.
The same applies for index 2
This will work for an array of any size. Except that for the case of just having one element in the array that one element will of course be selected every time.
let currentImageIdx = undefined;
function my() {
var bt = document.getElementById("btng");
bt.textContent = "Suggest me another";
var my = new Array("https://dummyimage.com/20x20/000/fff", "https://dummyimage.com/20x20/00FF00/000", "https://dummyimage.com/20x20/FF0000/000");
let backgroundImageIdx;
// it is imporant to check for undefined here as currentImageIdx != 0 would also trigger this case if it just was if(!currentImageIdx) and may produce the same picture twice
if (currentImageIdx !== undefined) backgroundImageIdx = getNextImage(currentImageIdx, my.length)
else backgroundImageIdx = Math.floor(Math.random() * my.length);
document.getElementById("img").src = my[backgroundImageIdx];
currentImageIdx = backgroundImageIdx;
console.log(`selected image ${currentImageIdx}`);
document.getElementById(
"pic"
).style.backgroundImage = `url(${my[backgroundImageIdx]})`;
}
function getNextImage(currentIndex, arrayLength) {
// generate random step value between 1 and array.length - 1
// with three elements: either 1 and 2
var step = Math.floor(1 + Math.random() * (arrayLength - 1));
// add the step value to current index and make sure we're not out of bounds
console.log(`(${currentIndex} + ${step}) % ${arrayLength} = ${(currentIndex + step) % arrayLength}`)
return (currentIndex + step) % arrayLength;
}
<div id="al">
<div id="pic">
<img src="" id="img" style="visibility: hidden;">
</div>
<button id="btng" onclick="my()">Suggest me manga</button>
</div>

Set darkMode across multiple html pages

I have two html pages(index.htm and details.htm). Whenever I enable dark Mode in details.html, it is retained in the index.html without any issues, but when I go to the details page from the index.html page the darkMode gets disabled.
I'm using local storage for enabling and disabling the darkMode.
My javascript code:
let darkMode = localStorage.getItem("darkMode");
const toggleBtn = document.querySelectorAll("#mode");
document.body.classList.add('lightMode');
function enableDarkMode() {
localStorage.setItem('darkMode', 'enabled');
document.body.classList.add('darkMode');
document.body.classList.remove('lightMode');
}
function disableDarkMode() {
localStorage.setItem('darkMode', null)
document.body.classList.remove('darkMode');
document.body.classList.add('lightMode');
}
toggleBtn.forEach(btn => {
if(darkMode === 'enabled') {
enableDarkMode();
}
btn.addEventListener("click", () => {
darkMode = localStorage.getItem('darkMode')
if (darkMode !== 'enabled') {
enableDarkMode()
} else {
disableDarkMode();
}
});
})
css code :
.lightMode {
--background-color: white;
--textColor: black;
--borderColor: black;
--shadowColor: grey;
--card: white;
--span: rgba(0, 0, 0, 0.459);
--footer: rgb(231, 231, 231);
--element: rgba(0, 0, 0, 0.03);
--tagColor: rgb(66, 66, 66);
}
.darkMode {
--background-color: rgb(25, 25, 25);
--textColor: rgba(255, 255, 255, 0.76);
--borderColor: white;
--shadowColor: black;
--card: rgb(39, 39, 39);
--span: rgba(255, 255, 255, 0.459);
--footer: rgb(56, 56, 56);
--element: rgba(49, 49, 49, 0.493);
--tagColor: rgb(255, 255, 255);
}
My css only consists of a few custom variables with the same name for both themes.
A for my html the body doesn't have any classes. classes for the body tag are added through javascript
Is there a way to set the darkMode to be enabled to all pages unless the the user changes it himself everytime he visits the page?
I see no problem in your JS, you may have not put the class name 'darkMode' in your body tag of html. One thing is for sure that problem is not the script, but css or html. Look your code for these two again.

How to read value of style within CSS function

I'm creating several divs in Javascript by inserting something like this
'<div style="background-color:' + bgColor + '</div>'
Now I want to set the color of the text automatically based on the luminosity of the background to black or white.
I see 2 options - all driven from Javascript or in CSS only. I prefer the CSS option, however, don't know how to read the background color for a CSS function, e.g.
#function set-color($color) {
#if (lightness($color) > 40) {
#return #000;
}
#else {
#return #FFF;
}
}
How can I fetch the background color to do something like this
div { color: set-color(???); }
How about mix-blend-mode ?
There are several ideas put forward in the question about how to choose between black and white for text color depending on the background color.
Most have been answered one way or another in comments. Taking the ideas one by one:
Can we use CSS mix-blend-mode - no. There is no one setting for this that ensures text will appear readable on all possible backgrounds.
Can we use CSS (the preferred method) - unfortunately no as the div requiring the text color to depend on background color is created by JS at run time.
Can we use JS - yes and as the div is being created by JS and having its background-color set then it might as well have its color set then too.
The JS string is as given in the question with the addition of a setting for color:
'<div style="background-color:' + bgColor + '; color: ' + textBlackOrWhite(bgColor) + ';"'
Here is a snippet which defines the function. The snippet also lets you choose a background color and it then sets a color which (roughly) depends on the 'brightness' of the background. See the SO questions referenced here for further discussion as human color perception is a difficult topic.
//from https://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
function textBlackOrWhite(hex) {
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);//also checks we have a well-formed hex number
//from https://stackoverflow.com/questions/596216 the answer by #FranciPenov which gives an approximation: (R+R+G+G+G+B)/6
let itsbright = function () { return ((2*parseInt(result[1], 16) + 3*parseInt(result[2], 16) + parseInt(result[3], 16))/6)>127; }
return result ? (itsbright()) ? '#000000' : '#ffffff' : '#000000';//falls back onto black if bgColor was not a well-formed 3 or 6 digit hex color
}
<div id="div" style="font-family: monospace; box-sizing: border-box; margin: 0; padding: 40px 0; width: 100px; height: 100px; border-style: solid; border-radius: 50%; background-color: black; color: white;text-align:center;">#ffffff</div>
Click to choose background color: <input id="input" placeholder='#00000' type='color' value='#000000'/>
<button onclick="let d = document.getElementById('div'); let i = document.getElementById('input'); d.innerHTML = i.value; d.style.backgroundColor = i.value; d.style.color = textBlackOrWhite(i.value);">Submit</button>
I want to set the color of the text automatically based on the
luminosity of the background to black or white.
I recognise this is a different approach from what you're asking for, but one CSS-only approach to having universally-readable text, regardless of background-color is to have white text with a black outline (or vice versa).
You can use 4 text-shadows for the outline:
text-shadow: 1px 1px rgb(0, 0, 0), -1px 1px rgb(0, 0, 0), -1px -1px rgb(0, 0, 0), 1px -1px rgb(0, 0, 0);
Working Example
const divs = [...document.getElementsByTagName('div')];
for (div of divs) {
let redValue = Math.floor(Math.random() * 255);
let greenValue = Math.floor(Math.random() * 255);
let blueValue = Math.floor(Math.random() * 255);
div.style.backgroundColor = `rgb(${redValue}, ${greenValue}, ${blueValue})`;
}
div {
float: left;
width: 180px;
height: 40px;
margin: 0 6px 6px 0;
line-height: 40px;
color: rgb(255, 255, 255);
font-size: 32px;
text-align: center;
text-shadow: 1px 1px rgb(0, 0, 0), -1px 1px rgb(0, 0, 0), -1px -1px rgb(0, 0, 0), 1px -1px rgb(0, 0, 0);
background-color: yellow;
}
<div>Sample Text</div>
<div>Sample Text</div>
<div>Sample Text</div>
<div>Sample Text</div>
<div>Sample Text</div>
<div>Sample Text</div>
<div>Sample Text</div>
<div>Sample Text</div>
<div>Sample Text</div>
<div>Sample Text</div>
<div>Sample Text</div>
<div>Sample Text</div>

How to animate a progress bar with negatives using Element.animate()

I'm attempting to mimic the following widget with HTML/CSS/JavaScript:
https://gyazo.com/76bee875d35b571bd08edbe73ead12cb
The way that I have it set up is the following:
I have a bar with a background color that has a gradient from red to green which is static.
I then have two blinders that is supposed to represent the negative space to give the illusion that the colored bars are animating (in reality, the blinders are simply sliding away)
I did it this way because I figured it might be easier instead of trying to animate the bar going in both directions, but now I'm not so sure lol. One requirement that I'm trying to keep is that the animation only deals with transform or opacity to take advantage of optimizations the browser can do (as described here: https://hacks.mozilla.org/2016/08/animating-like-you-just-dont-care-with-element-animate/)
The example has a few buttons to help test various things. The "Random positive" works great, and is exactly what I want. I haven't quite hooked up the negative yet tho because I'm not sure how to approach the problem of transitioning from positive to negative and vice-versa.
Ideally, when going from a positive to a negative, the right blinder will finish at the middle, and the left blinder will pick up the animation and finish off where it needs to go.
So for example, if the values is initially set to 40%, and the then set to -30%, the right blinder should animate transform: translateX(40%) -> transform: translateX(0%) and then the left blinder should animate from transform: translateX(0%) -> transform: translateX(-30%) to expose the red.
Also, the easing should be seamless.
I'm not sure if this is possible with the setup (specifically keeping the easing seamless, since the easing would be per-element, I think, and can't "carry over" to another element?)
Looking for guidance on how I can salvage this to produce the expected results, or if there's a better way to deal with this.
Note: I'm using jquery simply for ease with click events and whatnot, but this will eventually be in an application that's not jquery aware.
Here's my current attempt: https://codepen.io/blitzmann/pen/vYLrqEW
let currentPercentageState = 0;
function animate(percentage) {
var animation = [{
transform: `translateX(${currentPercentageState}%)`,
easing: "ease-out"
},
{
transform: `translateX(${percentage}%)`
}
];
var timing = {
fill: "forwards",
duration: 1000
};
$(".blind.right")[0].animate(animation, timing);
// save the new value so that the next iteration has a proper from keyframe
currentPercentageState = percentage;
}
$(document).ready(function() {
$(".apply").click(function() {
animate($("#amount").val());
});
$(".reset").click(function() {
animate(0);
});
$(".random").click(function() {
var val = (Math.random() * 2 - 1) * 100;
$("#amount").val(val);
animate(val);
});
$(".randomPos").click(function() {
var val = Math.random() * 100;
$("#amount").val(val);
animate(val);
});
$(".randomNeg").click(function() {
var val = Math.random() * -100;
$("#amount").val(val);
animate(val);
});
$(".toggleBlinds").click(function() {
$(".blind").toggle();
});
$(".toggleLeft").click(function() {
$(".blind.left").toggle();
});
$(".toggleRight").click(function() {
$(".blind.right").toggle();
});
});
$(document).ready(function() {});
.wrapper {
margin: 10px;
height: 10px;
width: 800px;
background: linear-gradient(to right, red 50%, green 50%);
border: 1px solid black;
box-sizing: border-box;
position: relative;
overflow: hidden;
}
.blind {
height: 100%;
position: absolute;
top: 0;
background-color: rgb(51, 51, 51);
min-width: 50%;
}
.blind.right {
left: 50%;
border-left: 1px solid white;
transform-origin: left top;
}
.blind.left {
border-right: 1px solid white;
transform-origin: left top;
}
<div class="wrapper">
<div class='blind right'></div>
<div class='blind left'></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js" type="text/javascript"></script>
<input id="amount" type="number" placeholder="Enter percentage..." value='40' />
<button class="apply">Apply</button>
<button class="random">Random</button>
<button class="randomPos">Random Positive</button>
<button class="randomNeg">Random Negative</button>
<button class="toggleBlinds">Toggle Blinds</button>
<button class="toggleLeft">Toggle L Blind</button>
<button class="toggleRight">Toggle R Blind</button>
<button class="reset" href="#">Reset</button>
I've modified your code. Have a look at the code.
let currentPercentageState = 0;
function animate(percentage) {
var animation = [{
transform: `translateX(${currentPercentageState}%)`,
easing: "ease-out"
},
{
transform: `translateX(${percentage}%)`
}
];
var timing = {
fill: "forwards",
duration: 1000
};
if (percentage < 0) {
$(".blind.right")[0].animate(
[{
transform: `translateX(0%)`,
easing: "ease-out"
},
{
transform: `translateX(0%)`
}
], timing);
$(".blind.left")[0].animate(animation, timing);
} else {
$(".blind.left")[0].animate(
[{
transform: `translateX(0%)`,
easing: "ease-out"
},
{
transform: `translateX(0%)`
}
], timing);
$(".blind.right")[0].animate(animation, timing);
}
// save the new value so that the next iteration has a proper from keyframe
//currentPercentageState = percentage;
}
$(document).ready(function() {
$(".apply").click(function() {
animate($("#amount").val());
});
$(".reset").click(function() {
animate(0);
});
$(".random").click(function() {
var val = (Math.random() * 2 - 1) * 100;
$("#amount").val(val);
animate(val);
});
$(".randomPos").click(function() {
var val = Math.random() * 100;
$("#amount").val(val);
animate(val);
});
$(".randomNeg").click(function() {
var val = Math.random() * -100;
$("#amount").val(val);
animate(val);
});
$(".toggleBlinds").click(function() {
$(".blind").toggle();
});
$(".toggleLeft").click(function() {
$(".blind.left").toggle();
});
$(".toggleRight").click(function() {
$(".blind.right").toggle();
});
});
$(document).ready(function() {});
.wrapper {
margin: 10px;
height: 10px;
width: 800px;
background: linear-gradient(to right, red 50%, green 50%);
border: 1px solid black;
box-sizing: border-box;
position: relative;
overflow: hidden;
}
.blind {
height: 100%;
position: absolute;
top: 0;
background-color: rgb(51, 51, 51);
min-width: 50%;
}
.blind.right {
left: 50%;
border-left: 1px solid white;
transform-origin: left top;
}
.blind.left {
border-right: 1px solid white;
transform-origin: left top;
}
<div class="wrapper">
<div class='blind right'></div>
<div class='blind left'></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js" type="text/javascript"></script>
<input id="amount" type="number" placeholder="Enter percentage..." value='40' />
<button class="apply">Apply</button>
<button class="random">Random</button>
<button class="randomPos">Random Positive</button>
<button class="randomNeg">Random Negative</button>
<button class="toggleBlinds">Toggle Blinds</button>
<button class="toggleLeft">Toggle L Blind</button>
<button class="toggleRight">Toggle R Blind</button>
<button class="reset" href="#">Reset</button>
You need to animate the things in two steps. The first step is to reset the previous state to initial state(which should be set to 0) and in the second step, you need to run the other animation which will actually move it to the destination state.
In order to achive this you can do,
let currentPercentageState = 0;
const animationTiming = 300;
function animate(percentage) {
let defaultTranformVal = [{
transform: `translateX(${currentPercentageState}%)`,
easing: "ease-out"
}, {transform: `translateX(0%)`}];
var animation = [{
transform: `translateX(0%)`,
easing: "ease-out"
},{
transform: `translateX(${percentage}%)`,
easing: "ease-out"
}];
var timing = {
fill: "forwards",
duration: animationTiming
};
if (percentage < 0) {
if(currentPercentageState > 0) {
$(".blind.right")[0].animate(defaultTranformVal, timing);
setTimeout(() => {
$(".blind.left")[0].animate(animation, timing);
}, animationTiming);
} else {
$(".blind.left")[0].animate(animation, timing);
}
}
if(percentage > 0) {
if(currentPercentageState < 0) {
$(".blind.left")[0].animate(defaultTranformVal, timing);
setTimeout(() => {
$(".blind.right")[0].animate(animation, timing);
}, animationTiming);
} else {
$(".blind.right")[0].animate(animation, timing);
}
}
// save the new value so that the next iteration has a proper from keyframe
currentPercentageState = percentage;
}
Here, you will see we have two transformations. The first one defaultTranformVal will move the currentPercentageState to zero and then the other one which will move from 0 to percentage.
You need to handle a couple of conditions here. The first one is if you are running it the first time(means there is no currentPercentageState), you don't need to run defaultTranformVal. If you have currentPercentageState then you need to run defaultTranformVal and then run the second animation.
Note:- You also need to clear the timeout in order to prevent the memory leak. This can be handle by storing the setTimout return value and then when next time it's running clear the previous one with the help of clearTimeout.
Here is the updated codepen example:-
https://codepen.io/gauravsoni119/pen/yLeZBmb?editors=0011
EDIT: I actually did manage to solve this!
let easing = "cubic-bezier(0.5, 1, 0.89, 1)";
let duration = 1000;
let easeReversal = y => 1 - Math.sqrt((y-1)/-1)
https://codepen.io/blitzmann/pen/WNrBWpG
I gave it my own cubic-bezier function of which I know the reversal for. The post below and my explanation was based on an easing function using sin() which isn't easily reversible. Not only that, but the built in easing function for ease-out doesn't match the sin() one that I had a reference for (I'm not really sure what the build in one is based on). But I realized I could give it my own function that I knew the reversal for, and boom, works like a charm!
This has been a very informative experience for me, I'm glad that I've got a solution that works. I still think I'll dip my toes in the other ideas that I had to see which pans out better in the long term.
Historical post:
So, after a few nights of banging my head around on this, I've come to the conclusion that this either isn't possible the way I was thinking about doing it, or if it is possible then the solution is so contrived that it's probably not worth it and I'd be better off developing a new solution (of which I've thought of one or tow things that I'd like to try).
Please see this jsfiddle for my final "solution" and a post-mortem
https://jsfiddle.net/blitzmann/zc80p1n4/
let currentPercentageState = 0;
let easing = "linear";
let duration = 1000;
function animate(percentage) {
percentage = parseFloat(percentage);
// determine if we've crossed the 0 threshold, which would force us to do something else here
let threshold = currentPercentageState / percentage < 0;
console.log("Crosses 0: " + threshold);
if (!threshold && percentage != 0) {
// determine which blind we're animating
let blind = percentage < 0 ? "left" : "right";
$(`.blind.${blind}`)[0].animate(
[
{
transform: `translateX(${currentPercentageState}%)`,
easing: easing
},
{
transform: `translateX(${percentage}%)`
}
],
{
fill: "forwards",
duration: duration
}
);
} else {
// this happens when we cross the 0 boundry
// we'll have to create two animations - one for moving the currently offset blind back to 0, and then another to move the second blind
let firstBlind = percentage < 0 ? "right" : "left";
let secondBlind = percentage < 0 ? "left" : "right";
// get total travel distance
let delta = currentPercentageState - percentage;
// find the percentage of that travel that the first blind is responsible for
let firstTravel = currentPercentageState / delta;
let secondTravel = 1 - firstTravel;
console.log("delta; total values to travel: ", delta);
console.log(
"firstTravel; percentage of the total travel that should be done by the first blind: ",
firstTravel
);
console.log(
"secondTravel; percentage of the total travel that should be done by the second blind: ",
secondTravel
);
// animate the first blind.
$(`.blind.${firstBlind}`)[0].animate(
[
{
transform: `translateX(${currentPercentageState}%)`,
easing: easing
},
{
// we go towards the target value instead of 0 since we'll cut the animation short
transform: `translateX(${percentage}%)`
}
],
{
fill: "forwards",
duration: duration,
// cut the animation short, this should run the animation to this x value of the easing function
iterations: firstTravel
}
);
// animate the second blind
$(`.blind.${secondBlind}`)[0].animate(
[
{
transform: `translateX(${currentPercentageState}%)`,
easing: easing
},
{
transform: `translateX(${percentage}%)`
}
],
{
fill: "forwards",
duration: duration,
// start the iteration where the first should have left off. This should put up where the easing function left off
iterationStart: firstTravel,
// we only need to carry this aniamtion the rest of the way
iterations: 1-firstTravel,
// delay this animation until the first "meets" it
delay: duration * firstTravel
}
);
}
// save the new value so that the next iteration has a proper from keyframe
currentPercentageState = percentage;
}
// the following are just binding set ups for the buttons
$(document).ready(function () {
$(".apply").click(function () {
animate($("#amount").val());
});
$(".reset").click(function () {
animate(0);
});
$(".random").click(function () {
var val = (Math.random() * 2 - 1) * 100;
$("#amount").val(val);
animate(val);
});
$(".randomPos").click(function () {
var val = Math.random() * 100;
$("#amount").val(val);
animate(val);
});
$(".randomNeg").click(function () {
var val = Math.random() * -100;
$("#amount").val(val);
animate(val);
});
$(".flipSign").click(function () {
animate(currentPercentageState * -1);
});
$(".toggleBlinds").click(function () {
$(".blind").toggle();
});
$(".toggleLeft").click(function () {
$(".blind.left").toggle();
});
$(".toggleRight").click(function () {
$(".blind.right").toggle();
});
});
animate(50);
//setTimeout(()=>animate(-100), 1050)
$(function () {
// Build "dynamic" rulers by adding items
$(".ruler[data-items]").each(function () {
var ruler = $(this).empty(),
len = Number(ruler.attr("data-items")) || 0,
item = $(document.createElement("li")),
i;
for (i = -11; i < len - 11; i++) {
ruler.append(item.clone().text(i + 1));
}
});
// Change the spacing programatically
function changeRulerSpacing(spacing) {
$(".ruler")
.css("padding-right", spacing)
.find("li")
.css("padding-left", spacing);
}
changeRulerSpacing("30px");
});
.wrapper {
margin: 10px auto 2px;
height: 10px;
width: 600px;
background: linear-gradient(to right, red 50%, green 50%);
border: 1px solid black;
box-sizing: border-box;
position: relative;
overflow: hidden;
}
.blind {
height: 100%;
position: absolute;
top: 0;
background-color: rgb(51, 51, 51);
min-width: 50%;
}
.blind.right {
left: 50%;
border-left: 1px solid white;
transform-origin: left top;
}
.blind.left {
border-right: 1px solid white;
transform-origin: left top;
}
#buttons {
text-align: center;
}
/* Ruler crap */
.ruler-container {
text-align: center;
}
.ruler, .ruler li {
margin: 0;
padding: 0;
list-style: none;
display: inline-block;
}
/* IE6-7 Fix */
.ruler, .ruler li {
*display: inline;
}
.ruler {
display:inline-block;
margin: 0 auto;https://jsfiddle.net/user/login/
background: lightYellow;
box-shadow: 0 -1px 1em hsl(60, 60%, 84%) inset;
border-radius: 2px;
border: 1px solid #ccc;
color: #ccc;
height: 3em;
padding-right: 1cm;
white-space: nowrap;
margin-left: 1px;
}
.ruler li {
padding-left: 1cm;
width: 2em;
margin: .64em -1em -.64em;
text-align: center;
position: relative;
text-shadow: 1px 1px hsl(60, 60%, 84%);
}
.ruler li:before {
content: '';
position: absolute;
border-left: 1px solid #ccc;
height: .64em;
top: -.64em;
right: 1em;
}
<div class="wrapper">
<div class='blind right'></div>
<div class='blind left'></div>
</div>
<div class="ruler-container">
<ul class="ruler" data-items="21"></ul>
</div>
<div id="buttons">
<input id="amount" type="number" placeholder="Enter percentage..." value='-80' />
<button class="apply">Apply</button>
<button class="random">Random</button>
<button class="randomPos">Random Positive</button>
<button class="randomNeg">Random Negative</button>
<button class="flipSign">Flip Sign</button>
<button class="toggleBlinds">Toggle Blinds</button>
<button class="toggleLeft">Toggle L Blind</button>
<button class="toggleRight">Toggle R Blind</button>
<button class="reset" href="#">Reset</button>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js" type="text/javascript"></script>
<hr />
<p><strong>A note</strong> on the attempt made here:</p>
<p>
I was trying to animate a percentage bar that has both positive and negative values. But I set a challenge as well: I wanted to achieve this via animations utilizing only the compositor - which means animating opacity or transform <strong>only</strong> (no color, width, height, position, etc). The ideas presented here were based on the concept of blinds. I have a static element with a background gradient of red to green, then I have two elements that "blind" the user to the background. These blinds, being a simple element, simply slide into and out of place.
</p>
<p>The problem that I ran into was timing the two animations correctly when they switched signage. It's currently working (very well) for linear animation, but as soon as you introduce an easing function it gets wonky. The reason for this is due to the value that I'm using to set the first animation length (iteration, not duration), as well as the second animations start to pick up where the first left off. The value that I was using is the percentage of the total travel distance that each of the blinds will have to do.</p>
<p>So, for example, if you have a value of 50, and go to -80, that's a total travel distance of 130. The first blind travels <code>50 / 130 = ~0.3846</code> of the total distance, and the second blind will travel <code>1 - ~0.3846 = ~0.6154</code> of the total distance.</p>
<p>But, these are not the correct values for the <em>duration</em> of the animation. Instead, these are the percentages of the easing values (the y-axis). To get the duration for these, I would have to find the x value (given the known y value). eg, for an ease-out animation for a value going from 50 to -80, the animation crosses our 0 at ~0.03846, and we would have to solve for x given <code>0.03846 = sin((x * PI) / 2)</code>.</p>
<p>With the help of Wolfram Alpha, I was able to find a few test values this got me much closer to the actual animation, but the blinds always stopped slightly off the mark. I eventually chalked this up to one of two reasons: the fact that the valuess are always going to be approximate and the browser is never going to be 100% accurate, or / and 2) the browser is using a slightly different easing function than I was using for reference. Regardless, being so constrained by the fact that this "animation" relies on two different aniamtions lining up perfectly, I decided to leave this version be and go in a different direction.</p>
<p>
If anyone finds an actual solution to this, please post an answer here: https://stackoverflow.com/questions/62866844/how-to-animate-a-progress-bar-with-negatives-using-element-animate
</p>
Thanks to those that attempted this admittedly tricky problem

Repeatedly change background colour of picture onMouseOver

I have a picture and wish its background to change and repeatedly take random colours sequencially from all over the spectrum till the user's mouse exits the picture. I guess the solution should use setInterval (see this) and the following shall help:
var red = Math.round(Math.random() * 255);
var green = Math.round(Math.random() * 255);
var blue = Math.round(Math.random() * 255);
var bg = "background-color: rgb(" + red + "," + green + "," + blue + ");";
x.style = bg;
Here is a fiddle trying to implement what I have in mind: The first smiley should change colour onMouseOver and return to normal onMouseOut.
Here is what I have in mind: I want to implement what FontAwesome.com do on their logo at their footer: it changes colours onmouseover and stops otherwise. But that's not a picture, it's a font(?). Instead, I have a logo that I made transparent, and I want to change the background dynamically so that it replicates the nice trick of Fontawesome. Any ideas?
* Updated *
I am posting a detailed solution to my question below based on the answers of the community. Looks like I followed Leo's way but Rakibul's solution worked well too.
I achieved what I want.
I wanted my logo to change colours "nicely" when a user's mouse hovers over it (like magic and similar to FontAwesome's logo at their footer).
.OAlogo {
background-color: transparent;
animation-play-state: paused;
}
.OAlogo:hover {
animation: colorReplace 10s infinite;
animation-timing-function: linear;
animation-direction: alternate;
}
#keyframes colorReplace {
0% {
background-color: rgb(44, 132, 231);
}
10% {
background-color: rgb(61, 192, 90);
}
20% {
background-color: rgb(255, 211, 59);
}
30% {
background-color: rgb(253, 136, 24);
}
40% {
background-color: rgb(243, 129, 174);
}
50% {
background-color: rgb(34, 138, 230);
}
60% {
background-color: rgb(62, 192, 89);
}
70% {
background-color: rgb(255, 211, 59);
}
80% {
background-color: rgb(71, 193, 86);
}
90% {
background-color: rgb(253, 126, 20);
}
100% {
background-color: rgb(233, 109, 132);
}
}
<img class="OAlogo" src="http://www.stouras.com/OperationsAcademia.github.io/images/OA-logo-solo.png" style="background: black;" width="100">
You have to declare setInterval() with your required time interval (In the example below 500 is set) for the color to be changed randomly on definite interval. And onmouseover is used to simply detect the hover on the image and then it sets the color randomly. Finally, when onmouseout is detected, the color changes to no-color.
var randomColor = function() {
var r = Math.floor(Math.random() * 12);
var g = Math.floor(Math.random() * 128);
var b = Math.floor(Math.random() * 100);
return "#" + r + g + b;
};
var colorChange;
document.getElementById("myImage").onmouseover = function() {
colorChange = setInterval(function() {
document.getElementById("myImage").style.backgroundColor = randomColor();
}, 500);
};
document.getElementById("myImage").onmouseout = function() {
this.style.backgroundColor = "";
clearInterval(colorChange);
};
<img id="myImage" src="https://www.w3schools.com/jsref/smiley.gif" alt="Smiley">
Use CSS animation to change colors and use the animation-play-state: pause on hover.
.button {
width:100px;
height:20px;
background-color: red;
animation: colorReplace 5s infinite;
}
.button:hover {
animation-play-state: paused;
}
#keyframes colorReplace
{
0% {background-color:red;}
30% {background-color:green;}
60% {background-color:blue;}
100% {background-color:red;}
}
<input type="submit" value="submit" class="button" />
You can just use the setInterval function to run your code over and over. You also had some minor errors in your code which I have fixed. See your updated fiddle here: https://jsfiddle.net/zvebco3r/3/
You can change the interval time (currently 25ms) to your desired length.
HTML:
<img id="img" src="https://www.w3schools.com/jsref/smiley.gif" alt="Smiley" width="32" height="32">
JS:
var img = document.getElementById('img');
img.onmouseover = function() {
changeIt = setInterval(function(){
var red = Math.floor(Math.random() * 255);
var green = Math.floor(Math.random() * 255);
var blue = Math.floor(Math.random() * 255);
img.style.backgroundColor="rgb("+red+","+green+","+blue+")";
},25);
}
img.onmouseout = function() {
this.style.backgroundColor="transparent";
clearInterval(changeIt);
}

Categories