How do I re-trigger a WebKit CSS animation via JavaScript? - javascript

So, I've got this -webkit-animation rule:
#-webkit-keyframes shake {
0% {
left: 0;
}
25% {
left: 12px;
}
50% {
left: 0;
}
75% {
left: -12px;
}
100% {
left:0;
}
}
And some CSS defining some of the animation rules on my box:
#box{
-webkit-animation-duration: .02s;
-webkit-animation-iteration-count: 10;
-webkit-animation-timing-function: linear;
}
I can shake the #box like this:
document.getElementById("box").style.webkitAnimationName = "shake";
But I can't shake it again later.
This only shakes the box once:
someElem.onclick = function(){
document.getElementById("box").style.webkitAnimationName = "shake";
}
How can I re-trigger a CSS animation via JavaScript without using timeouts or multiple animations?

I found the answer based on the source code and examples at the CSS3 transition tests github page.
Basically, CSS animations have an animationEnd event that is fired when the animation completes.
For webkit browsers this event is named “webkitAnimationEnd”. So, in order to reset an animation after it has been called you need to add an event-listener to the element for the animationEnd event.
In plain vanilla javascript:
var element = document.getElementById('box');
element.addEventListener('webkitAnimationEnd', function(){
this.style.webkitAnimationName = '';
}, false);
document.getElementById('button').onclick = function(){
element.style.webkitAnimationName = 'shake';
// you'll probably want to preventDefault here.
};
and with jQuery:
var $element = $('#box').bind('webkitAnimationEnd', function(){
this.style.webkitAnimationName = '';
});
$('#button').click(function(){
$element.css('webkitAnimationName', 'shake');
// you'll probably want to preventDefault here.
});
The source code for CSS3 transition tests (mentioned above) has the following support object which may be helpful for cross-browser CSS transitions, transforms, and animations.
Here is the support code (re-formatted):
var css3AnimationSupport = (function(){
var div = document.createElement('div'),
divStyle = div.style,
// you'll probably be better off using a `switch` instead of theses ternary ops
support = {
transition:
divStyle.MozTransition === ''? {name: 'MozTransition' , end: 'transitionend'} :
// Will ms add a prefix to the transitionend event?
(divStyle.MsTransition === ''? {name: 'MsTransition' , end: 'msTransitionend'} :
(divStyle.WebkitTransition === ''? {name: 'WebkitTransition', end: 'webkitTransitionEnd'} :
(divStyle.OTransition === ''? {name: 'OTransition' , end: 'oTransitionEnd'} :
(divStyle.transition === ''? {name: 'transition' , end: 'transitionend'} :
false)))),
transform:
divStyle.MozTransform === '' ? 'MozTransform' :
(divStyle.MsTransform === '' ? 'MsTransform' :
(divStyle.WebkitTransform === '' ? 'WebkitTransform' :
(divStyle.OTransform === '' ? 'OTransform' :
(divStyle.transform === '' ? 'transform' :
false))))
//, animation: ...
};
support.transformProp = support.transform.name.replace(/([A-Z])/g, '-$1').toLowerCase();
return support;
}());
I have not added the code to detect “animation” properties for each browser. I’ve made this answer “community wiki” and leave that to you. :-)

You have to first remove the animation, then add it again. Eg:
document.getElementById("box").style.webkitAnimationName = "";
setTimeout(function ()
{
document.getElementById("box").style.webkitAnimationName = "shake";
}, 0);
To do this without setTimeout remove the animation during onmousedown, and add it during onclick:
someElem.onmousedown = function()
{
document.getElementById("box").style.webkitAnimationName = "";
}
someElem.onclick = function()
{
document.getElementById("box").style.webkitAnimationName = "shake";
}

Following the suggestion from https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Animations/Tips, remove and then add the animation class, using requestAnimationFrame to ensure that the rendering engine processes both changes. I think this is cleaner than using setTimeout, and handles replaying an animation before the previous play has completed.
$('#shake-the-box').click(function(){
$('#box').removeClass("trigger");
window.requestAnimationFrame(function(time) {
window.requestAnimationFrame(function(time) {
$('#box').addClass("trigger");
});
});
});
http://jsfiddle.net/gcmwyr14/5/

A simple but effective alternative:
HTML:
<div id="box"></div>
<button id="shake-the-box">Shake it!</button>​
css:
#box{
background: blue;
margin:30px;
height:50px;
width:50px;
position:relative;
-moz-animation:shake .2s 0 linear 1;
-webkit-animation:shake .2s 0 linear 1;
}
#box.trigger{
display:table;
}
#-webkit-keyframes shake {
0% {
left: 0;
}
25% {
left: 12px;
}
50% {
left: 0;
}
75% {
left: -12px;
}
100% {
left:0;
}
}
#-moz-keyframes shake {
0% {
left: 0;
}
25% {
left: 12px;
}
50% {
left: 0;
}
75% {
left: -12px;
}
100% {
left:0;
}
}​
jQuery:
$('#shake-the-box').click(function(){
$('#box').toggleClass('trigger');
});​
Demo:
http://jsfiddle.net/5832R/2/
Issues:
I don't know if it works on Firefox, because the animation doesn't seem to work there...

Clone works pretty good on paused Karaoke:
On IE11 had to force a reflow (R. Krupiński's shorter version).
$('#lyrics').text("Why does it hurt when I pee?");
changeLyrics('3s');
function changeLyrics(sec) {
str = 'lyrics '+ sec + ' linear 1';
$('#lyrics').css( 'animation', str);
$('#lyrics').css( 'animation-play-state', 'running' );
$('#lyrics').replaceWith($('#lyrics').clone(true));
}
or you can use the following:
function resetAnimation(elm) {
$('#'+elm).replaceWith($('#'+elm).clone(true));
}

Reset the value first. Use reflow to apply the change without using timeout:
function shake() {
var box = document.getElementById("box");
box.style.animationName = null;
box.offsetHeight; /* trigger reflow */
box.style.animationName = "shake";
}
#keyframes shake {
0% { left: 0; }
25% { left: 12px; }
50% { left: 0; }
75% { left: -12px; }
100% { left: 0; }
}
#box {
position: absolute;
width: 75px; height: 75px;
background-color: black;
animation-duration: .02s;
animation-iteration-count: 10;
animation-timing-function: linear;
}
button {
position: absolute;
top: 100px;
}
<div id="box"></div>
<button onclick="shake()">Shake</button>
In contrast to the accepted answer that recommends animationEnd, this method resets the animation even when it's still in progress. This might be or might be not what you want.
An alternative would be to create a duplicate #keyframes animation and switch between the two:
function shake() {
var box = document.getElementById("box");
if (box.style.animationName === "shake")
box.style.animationName = "shake2";
else
box.style.animationName = "shake";
}
#keyframes shake {
0% { left: 0; }
25% { left: 12px; }
50% { left: 0; }
75% { left: -12px; }
100% { left: 0; }
}
#keyframes shake2 {
0% { left: 0; }
25% { left: 12px; }
50% { left: 0; }
75% { left: -12px; }
100% { left: 0; }
}
#box {
position: absolute;
width: 75px; height: 75px;
background-color: black;
animation-duration: .02s;
animation-iteration-count: 10;
animation-timing-function: linear;
}
button {
position: absolute;
top: 100px;
}
<div id="box"></div>
<button onclick="shake()">Shake</button>

Is there an issue with using setTimeout() to remove the class and then read it 5ms later?
svg.classList.remove('animate');
setTimeout(function() {
svg.classList.add('animate');
}, 10);

With your javascript, you could also add (and then remove) a CSS class in which the animation is declared. See what I mean ?
#cart p.anim {
animation: demo 1s 1; // Fire once the "demo" animation which last 1s
}

1) Add animation name to the #box.trigger in css
#box.trigger{
display:table;
animation:shake .2s 0 linear 1;
-moz-animation:shake .2s 0 linear 1;
-webkit-animation:shake .2s 0 linear 1;
}
2) In java-script you cannot remove the class trigger.
3) Remove the the class name by using setTimeOut method.
$(document).ready(function(){
$('#shake-the-box').click(function(){
$('#box').addClass('trigger');
setTimeout(function(){
$("#box").removeClass("trigger")},500)
});
});
4) Here is the DEMO.

Related

Wobble effect on letters

jQuery(function ($) {
var target = $("#target");
target.html(target.text().replace(/./g, "<span>$&</span>"));
setTimeout(runAnimation, 250);
function runAnimation() {
var index, spans;
index = 0;
spans = target.children();
doOne();
function doOne() {
var span = $(spans[index]);
if (!$.trim(span.text())) {
// Skip blanks
next();
return;
}
// Do this one
span.css({
position: "relative",
})
.animate(
{
top: "-20",
},
"fast"
)
.animate(
{
top: "0",
},
"fast",
function () {
span.css("position", "");
next();
}
);
}
function next() {
++index;
if (index < spans.length) {
doOne();
} else {
setTimeout(runAnimation, 500);
}
}
}
});
.title {
margin: auto;
width: 50%;
color: black;
text-align: right;
}
#target:hover {
color: rgb(21, 121, 252);
animation-name: bounce;
animation-duration: 2s;
}
#keyframes bounce {
0% { transform: translateY(0); }
50% { transform: translateY(-50px); }
100% { transform: translateY(0); }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="title">
<p style="font-size: 45px;"><span id="target">I</span><span id="target">'</span><span id="target">m</span><span>
</span><span id="target">K</span><span id="target">r</span><span id="target">i</span><span id="target">s</span>
</p>
</div>
I'm trying to add a wobble effect on each letter but I can't get it to work, I would like the letters to get a bit bigger while hovering them and making the effect run. I'm just learning javascript so I'm not really good at it, the snippet doesn't work and I don't know what's the problem with it.
I found this code for the wobble effect but it's not working, can someone help ? Thanks
Instead of manually typing the letters in individual span blocks, let JavaScript do it. This will be much more flexible.
Other than that, you do not need to use JavaScript for the animation, do it with CSS instead. That will be much simpler and handleable.
const animatedElements = document.getElementsByClassName('animate');
[...animatedElements].forEach(elm => {
let text = elm.innerText.split(''); // Split the text into letters and store them in an array
elm.innerText = ''; // Clear the text in the div
// Add the letters one by one, this time inside a <span>
text.forEach(letter => {
const span = document.createElement('span');
span.innerText = letter;
elm.appendChild(span);
})
})
.animate>span {
display: inline-block; /* Changing display from the default `inline` to `inline-block` so that `transform` rules apply */
white-space: break-spaces; /* This is necessary so that the `inline-block` does not collapse the "spaces" */
transition: transform 200ms ease-in-out;
}
.animate>span:hover {
transform: translateY(-10px);
}
/* The following rules are just to format the embedded result */
.animate {
margin: 40px;
font-size: 40px;
}
<div class="animate">
I'm Kris
</div>

Jquery slidetoggle code to vanilla Javascript that ahndle multiple elements toggle

I have few elements I need to slide, but I don't want to attach whole jQ lib. I like jQ a lot, but whole lib is just overkill in this example.
How to convert jq slideUp/slideDown/toggle to vanilla JS with support of multiple elements passed to function?
JQ code:
var $context = getContext(context);
$($context).on('click', '.menu', function () {
$('.nav').slideToggle();
});
JS code:
var list = document.getElementsByClassName("class1", "class2", "class3");
//or
var list = document.querySelectorAll("class1", "class2", "class3");
var slideUp = function(targets, duration){
// execution
};
slideUp(list, 500);
SO wizards make it happen! :)
I wasn't happy with the last solution I gave you it was rushed and buggy totally unacceptable, Hope you can forgive me...so this is a better version with the clicks of each item working too
const clicker = document.getElementsByClassName("clicker")[0];
clicker.addEventListener("click", function() {
process(document.querySelectorAll(".js-toggle"));
});
[...document.querySelectorAll(".js-toggle")].forEach((element) =>
element.addEventListener("click", function() {
process(this)
})
)
const container = [];
function process(linkToggle) {
container.length = 0
if (linkToggle.length > 0) {
for (let i = 0; i < linkToggle.length; i++) {
container.push(
document.getElementById(linkToggle[i].dataset.container))
animate(container[i])
}
} else {
container.push(
document.getElementById(linkToggle.dataset.container))
animate(container[0])
}
}
function animate(element) {
if (!element.classList.contains("active")) {
element.classList.add("active");
element.style.height = "auto";
let height = parseInt(element.clientHeight || 0)
element.style.height = "0px";
setTimeout(function() {
for (let t = 0; t < container.length; t++) {
do {
container[t].style.height =
parseInt(container[t].style.height || height) +
1 + 'px'
} while (parseInt(container[t].style.height || height) < height);
}
}, 0);
} else {
element.style.height = "0px";
element.addEventListener(
"transitionend",
function() {
element.classList.remove("active");
}, {
once: true
}
);
}
}
.clicker {
cursor: pointer;
background: red;
}
.box {
width: 300px;
border: 1px solid #000;
margin: 10px;
cursor: pointer;
}
.toggle-container {
transition: height 0.35s ease-in-out;
overflow: hidden;
}
.toggle-container:not(.active) {
display: none;
}
<div class="clicker">CLICK ME</div>
<div class="box">
<div class="js-toggle" data-container="toggle-1">Click1</div>
<div class="toggle-container" id="toggle-1">I have an accordion and am animating the the height for a show reveal - the issue is the height which i need to set to auto as the information is different lengths.<br><br> I have an accordion and am animating the the height fferent lengths.
</div>
</div>
<div class="box">
<div class="js-toggle" data-container="toggle-2">Click2</div>
<div class="toggle-container open" id="toggle-2">I have an accordion and am animating the the height for a show reveal - the issue is the height which i need to set to auto as the information is different lengths.<br><br> I have an accordion and am animating the the height fferent lengths.
</div>
</div>
<div class="box">
<div class="js-toggle" data-container="toggle-3">Click3</div>
<div class="toggle-container" id="toggle-3">I have an accordion and am animating the the height for a show reveal - the issue is the height which i need to set to auto as the information is different lengths.<br><br> I have an accordion and am animating the the height fferent lengths.
</div>
</div>
I hope this helps
you could just use css like so ( wasn't sure witch way you wanted to slid but this gives you an idea of how to do it):
var $slider = document.getElementById('slider');
var $toggle = document.getElementById('toggle');
$toggle.addEventListener('click', function() {
var isOpen = $slider.classList.contains('slide-in');
$slider.setAttribute('class', isOpen ? 'slide-out' : 'slide-in');
});
#slider {
position: absolute;
width: 100px;
height: 100px;
background: blue;
transform: translateX(-100%);
-webkit-transform: translateX(-100%);
}
.slide-in {
animation: slide-in 0.5s forwards;
-webkit-animation: slide-in 0.5s forwards;
}
.slide-out {
animation: slide-out 0.5s forwards;
-webkit-animation: slide-out 0.5s forwards;
}
#keyframes slide-in {
100% {
transform: translateX(0%);
}
}
#-webkit-keyframes slide-in {
100% {
-webkit-transform: translateX(0%);
}
}
#keyframes slide-out {
0% {
transform: translateX(0%);
}
100% {
transform: translateX(-100%);
}
}
#-webkit-keyframes slide-out {
0% {
-webkit-transform: translateX(0%);
}
100% {
-webkit-transform: translateX(-100%);
}
}
<div id="slider" class="slide-in">
<ul>
<li>Lorem</li>
<li>Ipsum</li>
<li>Dolor</li>
</ul>
</div>
<button id="toggle" style="position:absolute; top: 120px;">Toggle</button>
I can't take credit for this its lifted from:
CSS 3 slide-in from left transition
I hope this helps
Could you not simply include the css in the page header so wouldn't need to edit any style sheets, well in any case then how about this:
function SlideDown() {
const element = document.getElementById("slider");
let top = 0;
const up = setInterval(MoveDown, 10);
function MoveDown() {
if (top == 50) {
clearInterval(up);
} else {
top++;
element.style.top = top + '%';
}
}
}
function SlideUp() {
const element = document.getElementById("slider");
let top = parseInt(element.style.top);
const down = setInterval(MoveUp, 10);
function MoveUp() {
if (top == -100) {
clearInterval(down);
} else {
top--;
element.style.top = top + '%';
}
}
}
<!DOCTYPE html>
<html>
<body>
<div id="slider" style="position:absolute; top: -100px;">
<ul>
<li>Lorem</li>
<li>Ipsum</li>
<li>Dolor</li>
</ul>
</div>
<button onclick="SlideDown()">Slide Down</button>
<button onclick="SlideUp()">Slide Up</button>
</body>
</html>
I hope this helps

Javascript Fading out/in on mouse movement

I want to have a fixed nav which fades out when the mouse isn't moving and fades back in when it does.
I've came across this other post which does the job but the problem is that it uses visibility and I want to use opacity that way I can make it fade in and out with a transition transition: all .4s ease-in-out;
$("#fp-nav").style.opacity = "0";
$("html").mousemove(function(event) {
$("#fp-nav").style.opacity = "1";
myStopFunction();
myFunction();
});
function myFunction() {
myVar = setTimeout(function() {
$("#fp-nav").style.opacity = "0";
}, 1000);
}
function myStopFunction() {
if (typeof myVar != 'undefined') {
clearTimeout(myVar);
}
}
#fp-nav {
position: fixed;
z-index: 100;
top: 50%;
opacity: 1;
-webkit-transform: translate3d(0, 0, 0);
transition: all .4s ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="fp-nav">
Hello world Hello world Hello world Hello world
</div>
Or am I supposed to use fp-nav.style.opacity = "0"; instead of $("#fp-nav").style.opacity = "0";
You can replace .hide() and .show() by your own css code to visually hide the bar: hide becomes css("opacity", 0) and show becomes css("opacity", 1).
Then, you add a transition to your bar:
.navbar {
transition: opacity 1000ms ease-in-out;
};
$("div").css("opacity", 0);
$("html").mousemove(function( event ) {
$("div").css("opacity", 1);
myStopFunction();
myFunction();
});
function myFunction() {
myVar = setTimeout(function(){
$("div").css("opacity", 0);
}, 1000);
}
function myStopFunction() {
if(typeof myVar != 'undefined'){
clearTimeout(myVar);
}
}
div {
transition: opacity 1000ms ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>navbar</div>
It might be nice to let the css define how you want to hide/show via an additional class. You can then, for example, use addClass("is-hidden") and removeClass("is-hidden"):
var hiddenClass = "is-hidden";
var customHide = function($el) {
$el.addClass(hiddenClass);
}
var customShow = function($el) {
$el.removeClass(hiddenClass);
}
customHide($("div"));
$("html").mousemove(function( event ) {
customShow($("div"));
myStopFunction();
myFunction();
});
function myFunction() {
myVar = setTimeout(function(){
customHide($("div"));
}, 1000);
}
function myStopFunction() {
if(typeof myVar != 'undefined'){
clearTimeout(myVar);
}
}
/* CSS now determines how we want to hide our bar */
div {
position: relative;
background: green;
transition: transform 500ms ease-in-out;
}
div.is-hidden {
transform: translateY(-160%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>navbar</div>
$(document).on('mousemove', function(){
$('#nav').addClass('shown');
setTimeout(function(){
$('#nav').removeClass('shown');
}, 5000);
});
#nav {
opacity: 0;
transition: opacity 1s ease-in-out;
background: black;
width: 300px;
height: 100px;
}
#nav.shown {
opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="nav">
</div>
Here's my go:
Obviously, edit the timings and opacity as needed. The animations themselves are pure CSS, and JS is just used to add/remove a class from the nav.

Change img on swap (three varient)

I have 2 button (the unsmile and smile).
1. When i click to unsmile the img "flies" to left side.
2. When i click to smile the img is "flies" to right side.
But i need to do the following:
When i click on the img and drag it to the left, the img + description should "fly" to the left side and show a js alert - "You don't like this".
When i click on the img and drag it to right, the img + description should "fly" to the right side and show an alert - "You like this".
When i click on the img and drag it under the img, the img + description should "fly" down and show an alert - "You add this to favorite".
This should be done in javascript/html5/css.
It will be compiled using intelXDK to android platform.
HTML
<div id="food"></div>
<div id="control">
<div class="button no">
</div>
<div class="button yes">
</div>
</div>
</div>
JS Code
$('a[href*=#]').click(function(){
return false;
});
var animationEndEvent = "webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend";
var Food = {
wrap: $('#food'),
selectFood: [
{
name: 'Hamburger',
locaction: 'Poland, Warsaw, FoocCap',
img: "images/photo/1.jpg"
},
{
name: 'Chiness something',
locaction: 'Poland, Warsaw, FoocKnajp',
img: "images/photo/2.jpg"
},
{
name: 'Nuggets',
locaction: 'Japan, Tokyo, Yorazowa',
img: "images/photo/3.jpg"
},
{
name: 'Burger',
locaction: 'Japan, Nagasaki, Nogoiau',
img: "images/photo/4.jpg"
},
{
name: 'Chicken pice',
locaction: 'Russia, Moskow, Karmino',
img: "images/photo/5.jpg"
}
],
add: function(){
var random = this.selectFood[Math.floor(Math.random() * this.selectFood.length)];
this.wrap.append("<div class='foodChoose'><img alt='" + random.name + "' src='" + random.img + "' /><span><strong>" + random.name + "</strong>, " + random.locaction + "</span></div>");
}
}
var App = {
yesButton: $('.button.yes .trigger'),
noButton: $('.button.no .trigger'),
blocked: false,
like: function(liked){
var animate = liked ? 'animateYes' : 'animateNo';
var self = this;
if (!this.blocked) {
this.blocked = true;
$('.foodChoose').eq(0).addClass(animate).one(animationEndEvent, function() {
$(this).remove();
Food.add();
self.blocked = false;
});
}
}
};
App.yesButton.on('mousedown', function() {
App.like(true);
});
App.noButton.on('mousedown', function() {
App.like(false);
});
$(document).ready(function() {
Food.add();
});
CSS
#keyframes yes {
0% {
transform: scale(1) rotateZ(0deg);
left: 0;
}
30% {
transform: scale(1.05) rotateZ(0deg);
left: 0;
}
100% {
transform: rotateZ(45deg);
left: 400px;
}
}
.animateYes {
animation-fill-mode: both;
animation: yes 0.6s linear;
}
#keyframes no {
0% {
transform: rotateZ(360deg);
right: 0;
}
30% {
transform: scale(1.05) rotateZ(360deg);
right: 0;
}
100% {
transform: rotateZ(315deg);
right: 400px;
}
}
.animateNo {
animation-fill-mode: both;
animation: no 0.6s linear;
}
#control {
position: relative;
margin: 0 auto;
width: 250px;
top: -55%;
}
#control .button {
width: 65px;
height: 65px;
background: #fff;
position: absolute;
top: 5px;
border-radius: 50%;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
}
#control .button .trigger:active {
transform: translateY(-50%) scale(0.75);
transition: all .05s linear;
}
#control .button .trigger:before {
position: absolute;
top: 50%;
left: 50%;
transform: translateY(-50%) translateX(-50%);
font-family: 'FontAwesome';
}
#control .no {
left: 38px;
}
#control .no .trigger:before {
content: "\2639";
font-size: 40px;
color: #c33;
}
#control .yes {
right: 38px;
}
#control .yes .trigger:before {
content: "\263A";
font-size: 40px;
color: #3b7;
}
Current working version can be found here.
It's beed a while since I worked with jquery- let me know if it's a bad way to handle it so I can update/delete it?
You have already implemented an animationEnd handler
var App = {
yesButton: $('.button.yes .trigger'),
noButton: $('.button.no .trigger'),
blocked: false,
like: function(liked){
var animate = liked ? 'animateYes' : 'animateNo';
var self = this;
if (!this.blocked) {
this.blocked = true;
$('.foodChoose').eq(0).addClass(animate).one(animationEndEvent, function() {
$(this).remove();
Food.add();
self.blocked = false;
});
}
}
};
just pass the required arguments to your handler, e.g.
$('.foodChoose').eq(0).addClass(animate).one(animationEndEvent,
function(e) {
function(liked) {
$(this).remove();
alert(liked);
Food.add();
self.blocked = false;
}.bind(e.target, liked);
}
);
I'm passing the jquery custom event target here which should be identical to $('.foodChoose').eq(0)
^^ this means you will not need the original event and can remove the outer function like:
$('.foodChoose').eq(0).addClass(animate).one(animationEndEvent,
function(liked) {
$(this).remove();
alert(liked);
Food.add();
self.blocked = false;
}.bind($('.foodChoose').eq(0), liked);
);
added a fiddle including the code: https://jsfiddle.net/jLugv92t/1/ - slightly modified to bind to App. Thiy way we get rid of
var self = this;

Implementing a loading spinning wheel in javascript

In my web site I need to pop up a dummy 'loading' spinning wheel when click a button and vanish after some time. It's just a dummy page. I would be much obliged if anyone can explain how to do such a thing. Can I do this with javascript or jQuery?
Thanx in advance
Have a div/image in the right place you need, hide it first time the page loaded. like
<input type="button" id="button"/>
<div id="load"><img src="http://jimpunk.net/Loading/wp-content/uploads/loading1.gif"/>
</div>
and in your jquery, set a handler for the click event of button to show or hide the div
$(document).ready(function(){
$('#button').click(function(){
$('#load').show();
setTimeout(function() {$('#load').hide()}, 2000);
});
});
setTimout can be used to hide the div after some time.
check the workign example here
you can do it by ajax or simply jquery.
here is the ajax way
$.ajax({
type: "POST",
data: serializedDataofthisform,
dataType: "html", /* or json */
url: "your url",
/* ajax magic here */
beforeSend: function() {
$('#loaderImg').show(); /*showing a div with spinning image */
},
/* after success */
success: function(response) {
/* simply hide the image */
$('#loaderImg').hide();
/* your code here */
}
});
html
<div id="loaderImg"><img src="path" alt=""/></div>
Javascript
by time out function :- setTimeout()
Here's another example that doesn't use an image.
// Author: Jared Goodwin
// showLoading() - Display loading wheel.
// removeLoading() - Remove loading wheel.
// Requires ECMAScript 6 (any modern browser).
function showLoading() {
if (document.getElementById("divLoadingFrame") != null) {
return;
}
var style = document.createElement("style");
style.id = "styleLoadingWindow";
style.innerHTML = `
.loading-frame {
position: fixed;
background-color: rgba(0, 0, 0, 0.8);
left: 0;
top: 0;
right: 0;
bottom: 0;
z-index: 4;
}
.loading-track {
height: 50px;
display: inline-block;
position: absolute;
top: calc(50% - 50px);
left: 50%;
}
.loading-dot {
height: 5px;
width: 5px;
background-color: white;
border-radius: 100%;
opacity: 0;
}
.loading-dot-animated {
animation-name: loading-dot-animated;
animation-direction: alternate;
animation-duration: .75s;
animation-iteration-count: infinite;
animation-timing-function: ease-in-out;
}
#keyframes loading-dot-animated {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
`
document.body.appendChild(style);
var frame = document.createElement("div");
frame.id = "divLoadingFrame";
frame.classList.add("loading-frame");
for (var i = 0; i < 10; i++) {
var track = document.createElement("div");
track.classList.add("loading-track");
var dot = document.createElement("div");
dot.classList.add("loading-dot");
track.style.transform = "rotate(" + String(i * 36) + "deg)";
track.appendChild(dot);
frame.appendChild(track);
}
document.body.appendChild(frame);
var wait = 0;
var dots = document.getElementsByClassName("loading-dot");
for (var i = 0; i < dots.length; i++) {
window.setTimeout(function(dot) {
dot.classList.add("loading-dot-animated");
}, wait, dots[i]);
wait += 150;
}
};
function removeLoading() {
document.body.removeChild(document.getElementById("divLoadingFrame"));
document.body.removeChild(document.getElementById("styleLoadingWindow"));
};
document.addEventListener('keydown', function(e) {
if (e.keyCode === 27) {
removeLoading();
}
}, false);
<html>
<button onclick="showLoading()">Click me</button>
<p>Press Escape to stop animation.</p>
</html>

Categories

Resources