Have a java script table that connects to a web socket and update table.
I want to use jquery falsher to flash if the value is greater than and less than the current value.
Update Table function
var child = createStockNode(stock, type, template);
// try to replace
var stockNode = document.querySelector(type + "[data-symbol=" + stock.n + "]");
if (stockNode) {
table.replaceChild(child, stockNode);
} else {
// add new stock
table.appendChild(child);
}
//stock.c ===> close Price
var bg = stock.c < 0
? '255,148,148' // red
: '154,240,117'; // green
$row = child;
$row.flash(bg, 1000);
//child.flash(bg , 1000)
}
Jquery flusher function
jQuery.fn.flash = function (color, duration) {
var current = this.css('backgroundColor');
this.animate({ backgroundColor: 'rgb(' + color + ')' }, duration / 2)
.animate({ backgroundColor: current }, duration / 2);
};
Error Uncaught ReferenceError: $row is not defined
Jquery is defined in my html page as well.
EDIT
The jQuery documentation about the animate() function specifies :
For example, width, height, or left can be animated but background-color cannot be, unless the jQuery.Color plugin is used
I'd recommand to use CSS3 for thins kind of animation.
Still, here are to ways of flashing.
(function($) {
$.fn.blink = function(options) {
var defaults = {
delay: 500
};
var options = $.extend(defaults, options);
return this.each(function() {
var obj = $(this);
var blink = false;
setInterval(function() {
if (blink) {
$(obj).css('background', options.from);
} else {
$(obj).css('background', options.to);
}
blink = !blink;
}, options.delay);
});
}
}(jQuery))
$('#purejQuery').blink({
delay: 500,
from: "red",
to: "blue"
});
/* The animation code */
#keyframes blinking {
0%{
background-color: red;
}
50%{
background-color: red;
}
51%{
background-color: blue;
}
100%{
background-color: blue;
}
}
#pureCSS {
width: 100px;
height: 100px;
animation: blinking 1s infinite;
}
#purejQuery {
width: 100px;
height: 100px;
background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="pureCSS">Done by CSS</div>
<div id="purejQuery">Done by jQuery</div>
Related
Tread sofly, I've just started and couldn't find a similar problem... at least what I think would be the solution ;)
So I've got a robot written in HTML and CSS and I want to animate its lips on click. The idea is to make it like a kiss shape, so I need to scale it to a tiny size(1) and then put it back to normal (2). For now I don't really know how to do it. I tried just changing the width and height size but it didn't work. My guess is I need to do something with the transfort scaleX and scaleY but no idea what and how.
This is what I've already got:
var lips = document.getElementById("lips");
lips.addEventListener("click", kiss);
function kiss(e) {
var partRobo = e.target;
var sizeX= 1;
var sizeY= 1;
var id = setInterval(action, 20);
function action() {
partRobo.style.transform = scale(sizeX, sizeY);
sizeX-0.1;
sizeY-0.1;
if (sizeX === 0 && sizeY=== 0) {
clearInterval(id);
}
}
}
There are many ways to do this, and here is one of them
document.querySelector("div").addEventListener("click", function () {
this.style.transform = "scale(1.2)";
setTimeout(()=>{
this.style.transform = "scale(1)";
},500)
});
div {
width: 100px;
height: 100px;
background-color: red;
transition: cubic-bezier(0, 2.28, 0.95, 0.69) 0.5s;
}
<div></div>
You can use a CSS animation, JS would be needed only for triggering the animation. Of course you can change the duration, easing function and other params of the animation.
#lips {
height: 50px;
width: 100px;
background: red;
cursor: pointer;
}
.kiss {
animation: kiss 4s;
}
#keyframes kiss {
from {
transform: scale(0);
}
to {
transform: scale(1);
}
}
<div id="lips" onclick="this.classList.add('kiss')"></div>
I would make a css rule along the lines of
.lips-kiss {
transform: scale(0.6);
}
and then in the function kiss, apply and remove the class. So your code would look like,
var lips = document.getElementById("lips");
lips.addEventListener("click", kiss);
function kiss() {
lips.classList.add('lips-kiss');
setTimeout(() => {
lips.classList.remove('lips-kiss');
}, 20);
}
I am trying to use JS to switch images, the code does what it is supposed to and switches the images, however, I want a fade out-fade in effect to the image transition. I tried to declare a CSS Transition for opacity and change the opacity first, which didn't work, then I tried to change the opacity with plain JS, however that didn't work either, what would be the best way to achieve this?
My Poorly Designed Image Change Code:
image = [
"image_1.png",
"image_2.png",
"image_3.jpeg"
];
updateImg = async() => {
console.log("Pulling Image Change")
var img = document.getElementById("img-pan");
console.log(`Got ${img} with current src ${img.src}`)
var exi_bool = false;
for(i = 0; i < image.length - 1; i++) {
if(img.src.endsWith(image[i])) { exi_bool = true; console.log(`Found current src to == image[${i}]`) ;break; }
}
if(!exi_bool) {
img.src = image[0];
}else {
if(i < image.length - 1) { i++ }else { i = 0 }
img.src = image[i];
}
}
If I understood well, before you replace the image add a class that define the opacity to 0.3 for example.
document.getElementById("MyElement").classList.add('MyClass');
when the image change you remove the class.
document.getElementById("MyElement").classList.remove('MyClass');
Note that your image has to be set on css as opacity: 1 and transition x seconds.
Will use css style animation, just change class name, is simple to use and build.
but when css animation start to change css property,no way could change same property but other css animation.
let imgArray = [
'https://fakeimg.pl/100x100/f00',
'https://fakeimg.pl/100x100/0f0',
'https://fakeimg.pl/100x100/00f'
];
let img = document.getElementsByTagName('img')[0];
//only two function
async function fadeOut(element) {
element.className = 'fade-out';
}
async function fadeIn(element) {
element.className = 'fade-in';
}
//
let i = 0;
function loop() {
img.src = imgArray[i % 3];
i++;
fadeIn(img).then(res => {
setTimeout(() => {
fadeOut(img).then(res => {
setTimeout(() => {
loop();
}, 1000);
})
}, 1000);
})
}
loop();
img {
position: relative;
left: 0; /* or use transform */
opacity: 1;
transition: 1s;
width: 100px;
display: block;
margin: auto;
}
.fade-in {
animation: fade-in 1s;
}
#keyframes fade-in {
0% {
left: 100px; /* or use transform */
opacity: 0;
}
100% {
left: 0; /* or use transform */
opacity: 1;
}
}
.fade-out {
animation: fade-out 1s both;
}
#keyframes fade-out {
0% {
left: 0; /* or use transform */
opacity: 1;
}
100% {
left: -100px; /* or use transform */
opacity: 0;
}
}
<img src="https://fakeimg.pl/100x100/#f00">
Official older link for Owl 1 progress bar doesn't even work anymore but I have found working example but also for Owl 1.
I have tried to use the code but I am not able to set it to work with Owl 2
http://codepen.io/anon/pen/GrgEaG
$(document).ready(function() {
var time = 7; // time in seconds
var $progressBar,
$bar,
$elem,
isPause,
tick,
percentTime;
//Init the carousel
$("#owl-demo").owlCarousel({
items: 1,
initialized : progressBar,
translate : moved,
drag : pauseOnDragging
});
//Init progressBar where elem is $("#owl-demo")
function progressBar(elem){
$elem = elem;
//build progress bar elements
buildProgressBar();
//start counting
start();
}
//create div#progressBar and div#bar then prepend to $("#owl-demo")
function buildProgressBar(){
$progressBar = $("<div>",{
id:"progressBar"
});
$bar = $("<div>",{
id:"bar"
});
$progressBar.append($bar).prependTo($elem);
}
function start() {
//reset timer
percentTime = 0;
isPause = false;
//run interval every 0.01 second
tick = setInterval(interval, 10);
};
function interval() {
if(isPause === false){
percentTime += 1 / time;
$bar.css({
width: percentTime+"%"
});
//if percentTime is equal or greater than 100
if(percentTime >= 100){
//slide to next item
$elem.trigger('owl.next')
}
}
}
//pause while dragging
function pauseOnDragging(){
isPause = true;
}
//moved callback
function moved(){
//clear interval
clearTimeout(tick);
//start again
start();
}
//uncomment this to make pause on mouseover
// $elem.on('mouseover',function(){
// isPause = true;
// })
// $elem.on('mouseout',function(){
// isPause = false;
// })
});
#bar{
width: 0%;
max-width: 100%;
height: 4px;
background: #7fc242;
}
#progressBar{
width: 100%;
background: #EDEDED;
}
the callback functions are not being fired because you're calling them on events that don't exist in owlCarousel 2. The events are prefixed with 'on'.
So if you call them like this:
$("#owl-demo").owlCarousel({
items: 1,
onInitialized : progressBar,
onTranslate : moved,
onDrag : pauseOnDragging
});
The functions will be called. Check the owlCarousel event docs here.
Check out this CodePen for an example progressbar in OwlCarousel using CSS transitions.
After running into the need for a progress bar I stumbled across this question, as well as the example of a progress bar with owl-carousel v1.
Using v2.3.3 I came up with the following js/css-animation based solution:
javascript:
const $slider = $('.my-slider')
const SLIDER_TIMEOUT = 10000
$slider.owlCarousel({
items: 1,
nav: false,
dots: false,
autoplay: true,
autoplayTimeout: SLIDER_TIMEOUT,
autoplayHoverPause: true,
loop: true,
onInitialized: ({target}) => {
const animationStyle = `-webkit-animation-duration:${SLIDER_TIMEOUT}ms;animation-duration:${SLIDER_TIMEOUT}ms`
const progressBar = $(
`<div class="slider-progress-bar"><span class="progress" style="${animationStyle}"></span></div>`
)
$(target).append(progressBar)
},
onChanged: ({type, target}) => {
if (type === 'changed') {
const $progressBar = $(target).find('.slider-progress-bar')
const clonedProgressBar = $progressBar.clone(true)
$progressBar.remove()
$(target).append(clonedProgressBar)
}
}
})
scss
.slider-progress-bar {
/* your progress bar styles here */
.progress {
height: 4px;
background: red;
animation: sliderProgressBar ease;
}
}
.my-slider:hover {
.slider-progress-bar .progress {
animation-play-state: paused;
}
}
#keyframes sliderProgressBar {
0% {
width: 0%;
}
100% {
width: 100%;
}
}
This codepen shows my problem: http://codepen.io/PiotrBerebecki/pen/pNvpdG
When the user clicks on the big button the css opacity is reduced to 0. Since I've applied the following rule: transition: opacity 0.5s ease-in-out; the fade out animation is smooth.
I would like to achieve the same smooth transition when the next button fades in.
However for some reason the next button appears suddenly without any transition.
Would you know what causes the issue and how to fix it?
console.clear();
(function() {
// Data for the app
const model = {
buttons: ['tomato', 'blue'],
currentButton: -1
};
// Logic for the app
const controller = {
init: function() {
view.init();
},
getButtonName: function() {
model.currentButton = (model.currentButton + 1) % model.buttons.length;
return model.buttons[model.currentButton];
}
};
// View for the app
const view = {
init: function() {
this.root = document.getElementById('root');
this.showNext();
},
animationDelay: 500,
showNext: function() {
// Get next button name
const buttonName = controller.getButtonName();
// Create button DOM element
const buttonElement = document.createElement('div');
buttonElement.className = 'button';
buttonElement.id = buttonName;
buttonElement.textContent = buttonName;
buttonElement.style.opacity = 0;
// Add event listender for the button
buttonElement.addEventListener('click', event => {
// Reduce opacity
buttonElement.style.opacity = 0;
// Remove the button from DOM
setTimeout(() => {
this.root.removeChild(buttonElement);
}, this.animationDelay + 10);
// Start the function to show next button
setTimeout(() => {
this.showNext();
}, this.animationDelay + 20);
});
// Add button to DOM
this.root.appendChild(buttonElement);
// Show button by increasing opacity
buttonElement.style.opacity = 1;
}
};
// Start the app
controller.init();
}());
#tomato {
background: tomato;
}
#blue {
background: DeepSkyBlue;
}
.button {
transition: opacity 0.5s ease-in-out;
width: 100%;
height: 50vh;
border: solid 3px black;
cursor: pointer;
}
<div id="root"></div>
This should work , Code pen link: http://codepen.io/saa93/pen/gLbvmQ
You would need to add this instead of directly setting opacity to 1
// Show button by increasing opacity
buttonElement.style.opacity = 0;
setTimeout(() => {
buttonElement.style.opacity = 1;
}, this.animationDelay + 20);
Add a class (in the Snippet is .active) add the following:
CSS
.button {
opacity: 0;
transition: opacity 0.5s ease-in-out;
width: 100%;
height: 50vh;
border: solid 3px black;
cursor: pointer;
}
.button.active {
opacity: 1;
transition: opacity 0.5s ease-in-out;
}
JavaScript
...
// Reduce opacity
buttonElement.classList.toggle('active');
buttonElement.style.opacity = 0;
...
// Show button by increasing opacity
buttonElement.classList.toggle('active');
buttonElement.style.opacity = 1;
SNIPPET
console.clear();
(function() {
// Data for the app
const model = {
buttons: ['tomato', 'blue'],
currentButton: -1
};
// Logig for the app
const controller = {
init: function() {
view.init();
},
getButtonName: function() {
model.currentButton = (model.currentButton + 1) % model.buttons.length;
return model.buttons[model.currentButton];
}
};
// View for the app
const view = {
init: function() {
this.root = document.getElementById('root');
this.showNext();
},
animationDelay: 500,
showNext: function() {
// Get next button name
const buttonName = controller.getButtonName();
// Create button DOM element
const buttonElement = document.createElement('div');
buttonElement.className = 'button';
buttonElement.id = buttonName;
buttonElement.textContent = buttonName;
buttonElement.style.opacity = 0;
// Add event listender for the button
buttonElement.addEventListener('click', event => {
// Reduce opacity
buttonElement.classList.toggle('active');
buttonElement.style.opacity = 0;
// Remove the button from DOM
setTimeout(() => {
this.root.removeChild(buttonElement);
}, this.animationDelay + 10);
// Start the function to show next button
setTimeout(() => {
this.showNext();
}, this.animationDelay + 20);
});
// Add button to DOM
this.root.appendChild(buttonElement);
// Show button by increasing opacity
buttonElement.classList.toggle('active');
buttonElement.style.opacity = 1;
}
};
// Start the app
controller.init();
}());
#tomato {
background: tomato;
}
#blue {
background: DeepSkyBlue;
}
.button {
opacity: 0;
transition: opacity 0.5s ease-in-out;
width: 100%;
height: 50vh;
border: solid 3px black;
cursor: pointer;
}
.button.active {
opacity: 1;
transition: opacity 0.5s ease-in-out;
}
<div id="root"></div>
after this.root.appendChild(buttonElement);
you should set opacity to 0 and let the browser time to render before buttonElement.style.opacity = 1;
BTW I think removing and adding the element of not a good way to do this
.button {
width: 100%;
height: 50vh;
border: solid 3px black;
cursor: pointer;
animation-name: example;
animation-duration:3.5s;
}
#keyframes example {
0% {opacity:1}
50% {opacity:0}
100% {opacity:1}
}
What U really want is to use animation like this:JSFIDDLE EXAMPLE
This way the animation does all this timing and opacity back and forth using the css only
I tried the CSS route but all new to me and learning still but cannot seem to work it out. My JS below switches the background position to show a new image in the sprite every 1 second but wondering if anyone knew how I can kind of give it a small scale effects so when it changes grows a little then back to normal size before change to the next background position?
JS:
// Avatar animations
var avatarInterval;
function startAvatarAnimation() {
var i = 0;
var avatarSpeed = 500;
var avatarCount= 11;
var avatarHeight = 250;
var avatarTotalHeight = 2750;
avatarInterval = setInterval(function(){
i++;
if(i > 11){
i = 0;
}
$(".avatars").css({'background-position' : '0 -' + (i*avatarHeight) + 'px' });
$(".avatars").toggleClass('scaleIn', 'scaleOut');
}, avatarSpeed);
return false;
}
function stopAvatarAnimation(){
clearInterval(avatarInterval);
$(".avatars").css({'background-position' : '0 0' });
return false;
}
JS below switches the background position to show a new image in the
sprite every 1 second but wondering if anyone knew how i can kind of
give it a small scale effects so when it changes grows a little then
back to normal size before change to the next background position?
Try utilizing transition at css , setting duration to half of avatarSpeed or half of total duration of background-position effect ; setting transitionend event at .one() to prevent recursive call to transitionend handler , .removeClass() , .addClass() to toggle scale effect defined at css
css
.avatars {
transition: transform 500ms ease-in-out;
width: 100px;
height: 100px;
background-image: url(/path/to/background-image);
}
.avatars.scaleIn {
transform: scale(1.1, 1.1);
}
.avatars.scaleOut {
transform: scale(1.0, 1.0);
}
js
// Avatar animations
var avatarInterval;
function startAvatarAnimation() {
var i = 0;
var avatarSpeed = 500;
var avatarCount= 11;
var avatarHeight = 250;
var avatarTotalHeight = 2750;
avatarInterval = setInterval(function(){
i++;
if(i > 11){
i = 0;
}
$(".avatars").css({'background-position' : '0 -' + (i*avatarHeight) + 'px' })
.removeClass("scaleOut").addClass("scaleIn")
.one("transitionend", function() {
$(this).removeClass("scaleIn").addClass("scaleOut");
});
}, avatarSpeed);
return false;
}
$(".avatars").on("click", function() {
$(this).removeClass("scaleOut").addClass("scaleIn")
.one("transitionend", function() {
$(this).removeClass("scaleIn").addClass("scaleOut");
})
})
.avatars {
transition: transform 500ms ease-in-out;
width: 100px;
height: 100px;
background-image: url(http://lorempixel.com/100/100/nature);
}
.avatars.scaleIn {
transform: scale(1.1, 1.1);
}
.avatars.scaleOut {
transform: scale(1.0, 1.0);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div class="avatars"></div>