Daumantas Jakas
Daumantas Jakas

Reputation: 143

CSS transitions and javascript

here's the situation: i've got a hidden popup, want to show it on click with javascript and animate it with css transition.

What i've noticed is that if my popup handler looks like this one below it has no transition - it flashes in immediately.

$('.popup-link').on('click', function(){
    $('.popup').show().addClass('popup-visible');
});

But if i add a timeout - doesnt matter is it 1 ms or 1000 ms then it's all good.

$('.popup-link').on('click', function(){
    $('.popup').show();

    /* if we don't use the timeout it has no transition */

    window.setTimeout(function(){
       $('.popup').addClass('popup-visible');
    },1)    

});

jsfiddle link here: https://jsfiddle.net/ueggj9hu/

So i've got two questions here: why is that happening and is it okay to use this method or is there a cleaner way?

edit: i don't take jQuery animate function as 'cleaner' way because it is slower than css animation.

Upvotes: 1

Views: 73

Answers (2)

Lucian
Lucian

Reputation: 644

All you need to do is to remove display: none; from .popup and then just add the class with jQuery:

$('.popup-link').on('click', function(){
    $('.popup').addClass('popup-visible');  
});

Fiddle: https://jsfiddle.net/ueggj9hu/5/

Upvotes: 0

EugenSunic
EugenSunic

Reputation: 13693

fiddle url: https://jsfiddle.net/ueggj9hu/1/

This will work (without need of a timer function) just adjust your time to your needs you want it to show in the middle:

 $('.popup-link').on('click', function(){
    $('.popup').show().animate({
        top: "50%",
        marginTop: "-100px",
        opacity: 1
    },2000);  
});

Upvotes: 1

Related Questions