Can't disable animation in JQuery [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 2 years ago.
Improve this question
I want disable animation after user checked on checkbox, but I can't get it to work.
function onChangeTarget(num) {
updateCounter();
if (num != 0) {
targetHideAnimation = parseInt(num);
$('div.plus-point.plus-point' + num + '').css("display", "block");
$('div#wrap-' + num + ' img').css("filter", "grayscale(1)");
if (targetHideAnimation != 0) {
$('div#wrap-' + num + '').stop();
}
}
}
Here my full source code :
https://jsfiddle.net/ninhnguyen2208/o4htr5xj/
Please tell me what am I missing.

Looking at your fiddle, the issue isn't with the .stop(), it's with the .animate, specifically the callback:
function upDown() {
for (var i = 1; i <= QTY_TARGETS; i++) {
...
wrap.animate({ 'top': '' + moveTop + 'px' }, {
duration: duration,
complete: function () {
wrap.animate({ top: '' + moveTopRepeat + '' },
{
duration: duration,
// this line here
complete: upDown
});
}
});
}
}
The complete:upDown restarts upDown, but is called form within every target and calls the outer upDownAll.
Separate upDown to upDownAll and an inner upDownTarget then on the individual target complete reset just for that target:
function upDown() {
for (var i = 1; i <= QTY_TARGETS; i++) {
upDownTarget(i)
}
}
function upDownTarget(i)
{
...
wrap.animate({ 'top': '' + moveTop + 'px' }, {
duration: duration,
complete: function () {
wrap.animate({ top: '' + moveTopRepeat + '' },
{
duration: duration,
// only restart this one target
complete: function() { upDownTarget(i) }
});
}
});
}
Updated fiddle: https://jsfiddle.net/29hntbve/
As an extra, you also might like to stop the animations when the player loses:
res.text('You lose');
$(".wrap").stop();

Related

jQuery replace click() with document.ready() [closed]

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 6 years ago.
Improve this question
SO I found this jquery function: http://codepen.io/niklas-r/pen/HsjEv
html:
<p id="el">0%</p>
<button id="startCount">Count</button>
JS:
$("#startCount").on("click", function (evt) {
var $el = $("#el"),
value = 56.4;
evt.preventDefault();
$({percentage: 0}).stop(true).animate({percentage: value}, {
duration : 2000,
easing: "easeOutExpo",
step: function () {
// percentage with 1 decimal;
var percentageVal = Math.round(this.percentage * 10) / 10;
$el.text(percentageVal + '%');
}
}).promise().done(function () {
// hard set the value after animation is done to be
// sure the value is correct
$el.text(value + "%");
});
});
It increment numbers with animation. It doesnt work though, when I replace click with document.ready(). How do I make it work?
on document.ready there is no event so you can't do evt.preventDefault().
Here is a working example on document ready:
$(function() {
var $el = $("#el"),value = 56.4;
$({percentage: 0}).stop(true).animate({percentage: value}, {
duration : 2000,
easing: "easeOutExpo",
step: function () {
// percentage with 1 decimal;
var percentageVal = Math.round(this.percentage * 10) / 10;
$el.text(percentageVal + '%');
}
}).promise().done(function () {
// hard set the value after animation is done to be
// sure the value is correct
$el.text(value + "%");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>
<p id="el">0%</p>
Try using like this,
$(document).ready(function(){
$(document).on("click", "#startCount", function (evt) {
var $el = $("#el"),
value = 56.4;
$({percentage: 0}).stop(true).animate({percentage: value}, {
duration : 2000,
easing: "easeOutExpo",
step: function () {
// percentage with 1 decimal;
var percentageVal = Math.round(this.percentage * 10) / 10;
$el.text(percentageVal + '%');
}
}).promise().done(function () {
// hard set the value after animation is done to be
// sure the value is correct
$el.text(value + "%");
});
});
});
Include all of your code in $(document).ready to prevent script execution before page loading
$(document).ready(function(){
$("#startCount").on("click", function (evt) {
...
});
});
To activate on ready and on button click:
var cnt = function() {
var $el = $("#el"),value = 56.4;
$({percentage: 0}).stop(true).animate({percentage: value}, {
duration : 2000,
easing: "easeOutExpo",
step: function () {
// percentage with 1 decimal;
var percentageVal = Math.round(this.percentage * 10) / 10;
$el.text(percentageVal + '%');
}
}).promise().done(function () {
// hard set the value after animation is done to be
// sure the value is correct
$el.text(value + "%");
});
};
$(cnt);
$("#startCount").on("click", cnt);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>
<p id="el">0%</p>
<button id="startCount">Count</button>

Stop jQuery animate function within setInterval and assign css opacity to 0

I have a problem setting opacity to 0 after animate function in jQuery finished changing opacity value from 0 to 1. Any help would be appreciated.
var i = -1;
var interval = setInterval($.proxy(function () {
i++;
if (i >= this.options.slices) {
clearInterval(interval);
this.$element.children("[class='" + this.options.clonesClass + "']" ).css("opacity", 0);
} else {
this.$element.children("[data-index='" + i + "']").stop().animate({ opacity: 1 }, 1000);
}
}, this), 50)
Take a look in animate docs. If what you want to achieve is performing an action after animate completes, then pass a function performing that action as a last argument to animate.
So basically this
this.$element.children("[data-index='" + i + "']").stop().animate({ opacity: 1 }, 1000)
should become something like
this.$element.children("[data-index='" + i + "']").stop().animate({ opacity: 1 }, 1000, function(){
$element.css({opacity:0});
})
Edit:
Working with intervals is not really required with jQuery. Assumming the element you want to animate is $element, just execute
$element.stop().animate({ opacity: 1 }, 1000, function(){
$element.css({opacity:0});
})
Edit:
To achieve what you describe in a comment you need to chain animate calls in a sequence. I would recommend a recursive construct like this (pseudo code):
function myAnimate(elementsArray, num) {
if (num < elementsArray.size) {
$(elementsArray[num]).animate({ opacity: 1 }, 1000, function(){
myAnimate(elementsArray, num + 1);
})
} else {
for each el in elementsArray {
$(el).css({opacity:0});
}
// do other things, like prepare for next iteration
// then maybe call myAnimate(elementsArray, 0)
// to start all over again
}
}
then call it like this
myAnimate($('div.toBeAnimated'), 0)
This is the only way I managed to achieve the result I wanted.
var t = this;
t.$element.children( "[class='" + t.options.clonesClass + "']" ).each( $.proxy( function () {
setTimeout( $.proxy( function () {
i++;
if ( i < t.options.slices ) {
$( this ).animate( { opacity: 1 }, 1000 )
} else {
$( this ).animate( { opacity: 1 }, 1000, function () {
t.$element.children( "[class='" + t.options.clonesClass + "']" ).css( "opacity", 0 );
} );
}
}, this ), timeBuffer );
timeBuffer += 50;
} ), this );

Properties unavailable on my player ship object [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
please help to fix the script.
js:
//--- PLUGIN kalininHuyak IMPLEMENTATION ---
function KalininHuyak(options){
// --- properties ---
var huyakWrap = options.huyakWrap,
playerOffset = 10,
player = document.getElementById('player'),
xPosition = 200,
yPosition = 500;
// --- methods ----
playerShip = {
createPlayer: function (){
var player = $('<div />',
{
class: 'player',
id: 'player'
}
);
return player;
},
appendPlayer: function ( player, xPosition, yPosition){
player.appendTo('#huyakWrap');
player.attr('style', 'left: ' + xPosition + 'px; top: ' +
yPosition + 'px'
);
},
movePlayer: function (direction, offset){
var playerPositionX = player.style.left,
currentOffset = parseInt(playerPositionX, 10),
preCurrentOffset = currentOffset + (offset * direction);
if(preCurrentOffset < 0){
preCurrentOffset = 0;
}
else
if(preCurrentOffset > 920){
preCurrentOffset = 920;
}
player.style.left = preCurrentOffset + 'px';
}
}
// --- init ---
playerShip.appendPlayer(playerShip.createPlayer(), xPosition, yPosition );
// --- handlers ---
function onKeypress(keyCode){
var direction;
if(keyCode == 49){
direction = -1;
}
else
if(keyCode == 50){
direction = 1;
};
playerShip.movePlayer(direction, playerOffset);
}
// --- events ---
$(window).keypress( function(e)
{
onKeypress(e.which);
}
);
};
var kalininHuyak = new KalininHuyak(
{
huyakWrap: document.getElementById('huyakWrap')
}
);
html:
<div id="huyakWrap" class="huyak_wrap">
</div>
the problem appears after pressing 1, 2. said console that is specified property player. but this property is defined as
player = document.getElementById ('player')
it is accessible to any method.
is a living demo http://prozaik.16mb.com/js3/huYak2/
JSFiddle here: http://jsfiddle.net/fjdC9/1/
appendPlayer: function (player, xPosition, yPosition){
player.appendTo('#huyakWrap');
player.attr('style', 'left: ' + xPosition + 'px; top: ' + yPosition + 'px');
$player = $('#player');
},
Once I figured out the actual problem, it was simply a case of you trying to find the element before it exists (as the first step of your KalininHuyak method/class).
I moved the selector into the append (for now). You simply need to find the player object after it has been appended.

Stop timeOut and animation on mouseenter and continue on mouseleave

I wanted to get rid of a slider-plugin, so i tried to build my own,
everything works nice but i´m stuck to stop the whole thing on hover and restart it again on mouseleave,
here is my js :
function startPslider(val) {
if (!val) {
val = 0;
}
var holder = 'slideHolder';
var text = 'slideText';
startInterval(holder, text, val);
}
function startInterval(holder, text, val) {
var t;
var i = val;
if (i > 2) {
i = 0
}
$('#' + holder + i).animate({
opacity: 1,
}, function () {
$(this).addClass('active')
$('.' + text + i).animate({
opacity: 1,
left: 0
}, 1200);
t = setTimeout(function () {
$('.' + text + i).animate({
opacity: 0,
left: '-400px'
}, 1200);
$('#' + holder + i).animate({
opacity: 0,
}, 2200).removeClass('active');
startPslider(i + 1);
}, 4000)
});
// Here´s the not working hover-function
$('#hpCanvas').hover(function () {
clearTimeout(t);
}, function () {
var id = $('.active').attr('id');
var slide = id.substring(11, 22);
console.log(slide)
startPslider(slide);
});
}
$(function () {
startPslider();
});
tryed to solve this with adding class 'active' to the current holder and at hover-out try to catch the current-slide number (val) and restart it again, starting on the correct slide, but it´s not working as I wish,
have a look at this fiddle, http://jsfiddle.net/zDh76/ you will find html and css there, as you see everything works fine as long you do not hover.
Maybe anyone has a helping hint how to stop the animation, clear the timer and go on with the correct slide on mouseleave?
UPDATE
i separated start and end-interval
function startPslider(i) {
if(!i){
i=0;
}
if(i >2){
i=0
}
console.log('started Slider with slide:'+i)
var holder = 'slideHolder';
var text = 'slideText';
startInterval(holder, text, i);
}
function startInterval(holder,text,i) {
var t;
var v;
console.log('started Interval with slide:'+i);
$('#'+holder+i).animate({
opacity:1,
}, function(){
$('.'+text+i).animate({
opacity:1,
left:0
},1200);
t= setTimeout(function(){endInterval(holder,text,i); },4000);
});
}
function endInterval(holder,text,i,cont){
console.log('end Interval with slide:'+i);
$('.'+text+i).animate({
opacity:0,
left:'-400px'
},1200);
$('#'+holder+i).animate({
opacity:0,
},2200, function(){
$('.slideHolder').css('opacity',0);
i = i+1;
startPslider(i);
});
}
I found it out myself,
i needed to unbind the hover event on #hpCanvas inside the mouseleave function like
$('#hpCanvas').hover(function(){
$('.slideHolder, .slideText').stop(true,true);
clearTimeout(t)
},function(){
endInterval(holder,text,i);
$('#hpCanvas').unbind('mouseenter mouseleave')
})
as the next call to bind it with hover event is inside the mouseleave-part of the first hover event.
thanks anyway for everyone reading this

jQuery - this.option becomes undefined in load function

I'm trying to alter a Plugin a little bit, here's the Prototype function, I've marked what lines I've added.
OK, so my problem happens inside the img-load function I've added. I've surrounded the old code with one to assure that the script waits until the image has loaded.
The problem is, that "this" inside the load-function is not connected with the one outside. I've tried giving the load function a parameter but apparently it's not working or I'm doing something wrong.
Do you know an easy way to sort-of inherit "this"? I don'T really know what else to do.
Plugin.prototype._fade = function(number) {
var $element, currentSlide, next, slidesControl, value,
_this = this;
$element = $(this.element);
this.data = $.data(this);
if (!this.data.animating && number !== this.data.current + 1) {
$.data(this, "animating", true);
currentSlide = this.data.current;
if (number) {
number = number - 1;
value = number > currentSlide ? 1 : -1;
next = number;
} else {
value = this.data.direction === "next" ? 1 : -1;
next = currentSlide + value;
}
if (next === -1) {
next = this.data.total - 1;
}
if (next === this.data.total) {
next = 0;
}
this._setActive(next);
slidesControl = $(".slidesjs-control", $element);
var nxtImg = $(slidesControl.children(":eq(" + next + ")")).find("img:eq(0)"); // added
if ( nxtImg.attr("longdesc") !== undefined ) { // added
nxtImg.attr("src", nxtImg.attr("longdesc")); // added
nxtImg.removeAttr("longdesc"); // added
} // added
nxtImg.load(function(){ // added
slidesControl.children(":eq(" + next + ")").css({
display: "block",
left: 0,
zIndex: 0
});
this.options.callback.start(currentSlide + 1);
if (this.options.effect.fade.crossfade) {
return slidesControl.children(":eq(" + this.data.current + ")").stop().fadeOut(this.options.effect.fade.speed, (function() {
slidesControl.children(":eq(" + next + ")").css({
zIndex: 10
});
$.data(_this, "animating", false);
$.data(_this, "current", next);
return _this.options.callback.complete(next + 1);
}));
} else {
slidesControl.children(":eq(" + next + ")").css({
display: "none"
});
return slidesControl.children(":eq(" + currentSlide + ")").stop().fadeOut(this.options.effect.fade.speed, (function() {
slidesControl.children(":eq(" + next + ")").stop().fadeIn(_this.options.effect.fade.speed).css({
zIndex: 10
});
$.data(_this, "animating", false);
$.data(_this, "current", next);
return _this.options.callback.complete(next + 1);
}));
}
}); // added
}
};
You're capturing the this in a closure variable "_this". Isn't that working?

Categories