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

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

Posted by: admin November 30, 2017 Leave a comment

Questions:

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)

Answers:

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();

Questions:
Answers:

you can use promise

$('.element').css("color","yellow").promise().done(function(){
    alert( 'color is yellow!' );
});

http://codepen.io/onikiienko/pen/wBJyLP

Questions:
Answers:

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);
});

Questions:
Answers:

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/