Code not running when using ".remove()" function - javascript

I'm writing this jquery code :
$('form').after('<p id="suc"></p>');
$('#suc').html('success !');
$('#suc').show(700);
setTimeout(function(){$('#suc').hide('slow')},2500);
$('#suc').remove();
When i remove $('#suc').remove(); like this :
$('form').after('<p id="suc"></p>');
$('#suc').html('success !');
$('#suc').show(700);
setTimeout(function(){$('#suc').hide('slow')},2500);
The code run succefuly, but when i put it, it dosen't run !!
What the problem with that ?
it's illegal to but $('#suc').remove(); here ?

The setTimeout call doesn't wait for the callback to run before the code continues, so you will be removing the element immediately. When the code in the callback tries to hide the element, it's not there.
Remove the element in the complete callback of the hide method:
setTimeout(function(){
$('#suc').hide('slow', function(){
$('#suc').remove();
});
},2500);

As you're using hide you're also safe to use delay, so:
$('#suc').show(700).delay(2500).hide('slow', function () {
$(this).remove();
});
will suffice.
demo: http://jsbin.com/isediz/2/
Also, as a bit of clarification, regarding:
The code run succefuly, but when i put it, it dosen't run !!
Actually the code runs (in a sense), the problem is that your remove will not wait for the two asynchrones events (setTimeout and .hide('slow')). So it will get executed way before those two are done doing what they should do.

You need to put the remove() inside of the setTimeout and in the callback for the hide() function:
$('form').after('<p id="suc"></p>');
$('#suc').html('success !');
$('#suc').show(700);
setTimeout(function() {
$('#suc').hide('slow', function() { $(this).remove(); })
}, 2500);

You are using the element setTimout callback which you have already removed with the statement just after setTimout. The call back of setTimeout will execute after the statement removing element with id #suc by the next statement of setTimeout. Remove #suc in hide callback so that it is not accessed by script after removal.
$('form').after('<p id="suc"></p>');
$('#suc').html('success !');
$('#suc').show(700);
setTimeout(function(){
$('#suc').hide('slow',
function(){$(this).remove();
});
},2500);

Related

Callback function / Run a function after adding a class with .addClass

I'm trying to run a function on the selector that addClass was just ran on after addClass is completed.
This way made sense to me, but it doesn't seem to be working:
$('.focused').addClass('fadeOutDown', function(){ $(this).remove(); });
How can I run a function after I've ran the addClass function on the same selector?
Chaining runs it at the same time and I haven't tried a set-timeout, but that seem inefficient.
Try to do this way :
$('.focused').addClass('fadeOutDown');
setTimeout(function() {
$('.focused').remove();
}, 2000);
// make sure you provide appropriate time i.e after you get the effect

myWait(ms) in jQuery?

I want to extend the $.fn object in order to have a delay between my jquery commands :
like this working (and quite long) code :
$('.d').delay(1000).queue(
function ()
{
$(this).css('background-color', 'green');
$(this).dequeue();
}).delay(1000).queue(function ()
{
$(this).css('background-color', 'red');
$(this).dequeue();
});
a working sample is here : JSBIN
So I tried this :
My code at jsbin
$.fn.myWait = function (ms)
{
return this.queue(
function ()
{
var _self = this;
setTimeout(function ()
{
$(_self).dequeue();
}, ms);
})
};
invoking :
$('.d').myWait(1000).css('background-color', 'red').myWait(1000).css('background-color', 'green');
But it doesnt work.
What am I doing wrong ?
p.s.
I did read this similar solution, but if I remove the animation part and use only css , it also doesnt work.
The .css() does not get queued on the animation queue by itself, that's why you needed to put it in a callback in your first snippet. In the second snippet, it is called immediately (even though there's timeout waiting in the queue - just as like you called .delay()). Instead, you would need to use an .animate() call with a zero-duration.
For allowing the syntax which you wanted, you will need to take a step further. Have a look at the jQuery timing plugin and how their magic works.
I doubt you can do it in this way. You need to defer execution of those attribute changes, which means you shall store said code in individual functions.

jQuery toggle class with delay works only once

I am clearly missing something fundamental when it comes to jQuery, anonymous functions, and delays.
The following code works only ONCE per page load (it will add the class, then remove it after 1 second, and if i click again, it will add the class, but will NEVER remove the class for the duration of the page, unless I reload the page):
var jElement = $(currElem);
jElement.addClass("highlight")
.delay(1000)
.queue(function(){
$(this).removeClass("highlight");
});
HOWEVER,
if I add the (non-existant) function call as a parameter, AND I call it in my anonymous function, then the add/remove class combination will work indefinitely.
var jElement = $(currElem);
jElement.addClass("highlight")
.delay(1000)
.queue(function(randomFunction){
$(this).removeClass("highlight");
randomFunction(); //this makes it seemingly 'miraculously' work??
});
Side Note:
var jElement = $(currElem);
jElement.addClass("highlight")
.delay(1000)
.queue(function(randomFunction){
$(this).removeClass("highlight");
// this does NOT work; if I dont actually call the 'randomFunction'
// so that function, even though it does nothing; must somehow cause
// the implicit call of 'dequeue()' ??
});
There is no miracle there. This behavior it's written in the documentation of .queue().
Note that when adding a function with .queue(), we should ensure that .dequeue() is eventually called so that the next function in line executes.
$('#foo').slideUp().queue(function() {
alert('Animation complete.');
$(this).dequeue();
});
As of jQuery 1.4, the function that's called is passed another function as the first argument. When called, this automatically dequeues the next item and keeps the queue moving. We use it as follows:
$("#test").queue(function(next) {
// Do some stuff...
next();
});
the randomFunction is actually referred to as next and references the .dequeue method. Calling it causes the queue to continue on to the next item in the queue.
http://api.jquery.com/queue/

In JQuery, Is it possible to get callback function after setting new css rule?

I have $('.element').css("color","yellow") and I need that next event was only after this one, something looks like $('.element').css("color","yellow",function(){ alert(1); })
I need this because:
$('.element').css("color","yellow");
alert(1);
events are happen at one time almost, and this moment call the bug in animation effect (alert(1) is just here for example, in real module it's animation)
you can use promise
$('.element').css("color","yellow").promise().done(function(){
alert( 'color is yellow!' );
});
http://codepen.io/onikiienko/pen/wBJyLP
Callbacks are only necessary for asynchronous functions. The css function will always complete before code execution continues, so a callback is not required. In the code:
$('.element').css('color', 'yellow');
alert(1);
The color will be changed before the alert is fired. You can confirm this by running:
$('.element').css('color', 'yellow');
alert($('.element').css('color'));
In other words, if you wanted to use a callback, just execute it after the css function:
$('.element').css('color', 'yellow');
cb();
You can use setTimeout to increase the sleep time between the alert and the css like this:
function afterCss() {
alert(1);
}
$('.element').css("color","yellow");
setTimeout(afterCss, 1000);
This will make the alert appear 1 second after the css changes were committed.
This answer is outdated, so you might want to use promises from ES6 like the answer above.
$('.element').css("color", "yellow").promise().done(function(){
// The context here is done() and not $('.element'),
// be careful when using the "this" variable
alert(1);
});
There's no callback for jquery css function. However, we can go around, it's not a good practice, but it works.
If you call it right after you make the change
$('.element').css('color','yellow');
alert('DONE');
If you want this function has only been called right after the change, make an interval loop.
$('.element').css('color','yellow');
var detectChange = setInterval(function(){
var myColor = $('.element').css('color');
if (myColor == 'yellow') {
alert('DONE');
clearInterval(detectChange); //Stop the loop
}
},10);
To avoid an infinite loop, set a limit
var current = 0;
$('.element').css('color','yellow');
current++;
var detectChange = setInterval(function(){
var myColor = $('.element').css('color');
if (myColor == 'yellow' || current >= 100) {
alert('DONE');
clearInterval(detectChange); //Stop the loop
}
},10);
Or using settimeout as mentioned above/
use jquery promise,
$('.element').css("color","yellow").promise().done(function(){alert(1)});

Function is undefined?

I'm struggling to find out why the setTimeout function cannot find my radio button tagging function when trying to run.
this is my code...
var radioButtonTagging = (function(){
console.log('run');
$("span.radio").each(function(i, ele){
$(ele).addClass('radio'+i);
});
$(".radio1").click(function(){
console.log('fired');
$('#expandQuestion1').css('display','block');
});
});
if($('span.radio').length){
console.log('run');
radioButtonTagging();
} else {
console.log('trying to run timer');
setTimeout("radioButtonTagging()",2000);
}
http://pastebin.com/nvacxZGS
I'm basically just looking for spans with a class radio and adding a further class with radio plus the index.
The reason why I'm using the setInterval is because when it tries to fire the first time the span's are not in place as they are being inserted via jquery.. so are not finished during doc.ready..
Any help would be great
You are passing a string to setInterval, so it is evaled in a different scope. Since the function you are looking for is scoped locally, it can't find it.
Don't pass strings to setInterval, pass functions.
try this
setTimeout(function(){ radioButtonTagging() },2000);
Try:
setTimeout(radioButtonTagging, 2000);
See here:
http://jsfiddle.net/qUAZf/

Categories

Resources