benhowdle89
benhowdle89

Reputation: 37474

Using .animate and .css or just one in jQuery

I have this jQuery code:

var help;
    $('.helpPin').click(function(){

        if(help == true){
            var cssObj = {
                'position' : 'absolute',
                'bottom' : '0'
            };
            $('#help').css(cssObj);
            help = false;
        } else {
            var cssObj = {
                'position' : 'absolute',
                'bottom' : '-206px'
            };
            $('#help').css(cssObj);
            help = true;
        }
    });

That basically just swaps css for an element, how can i introduce animate effects to so its not too jerky? Can you use .css inside .animate?

Upvotes: 0

Views: 67

Answers (4)

Prisoner ZERO
Prisoner ZERO

Reputation: 14176

You should set the position using CSS, in the meantime......

var help;
$('.helpPin').click(function () {

     var bottom = (help) ? '0' : '-206px';

     $('#help')
          .css({ 'position': 'absolute' });
          .animate({ 'bottom': bottom });

     help = !help;
}); 

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337610

First of all, addinga/amending CSS properties directly in jQuery is considered bad practice. All you need to do is set the position on the element in your CSS:

CSS

#help {
    position: absolute;
}

You can then refactor your jQuery code to cut it down drastically, and also animate your element as required:

var help;

$('.helpPin').click(function(){
    var bottom = help ? '0' : '-206px';
    $("#help").animate({ 'bottom' : bottom });
    help = !help;
});

Upvotes: 3

rahul
rahul

Reputation: 187070

A working demo

#help
{
    position: absolute;
}

$('.helpPin').click(function(){
        if(help == true){
            $('#help').animate({"bottom": '0'});
            help = false;
        } else {
            $('#help').animate({"bottom": '-206px'});
            help = true;
        }
    });

Upvotes: 2

Hamza Waqas
Hamza Waqas

Reputation: 629

Try to code less and more efficient way.

var help;
    $('.helpPin').click(function(){

        if(help == true){               
            $('#help').css({
                'position' : 'absolute',
                'bottom' : '0'
            }).animate();
            help = false;
        } else {
            $('#help').css({
                'position' : 'absolute',
                'bottom' : '-206px'
            }).animate();
            help = true;
        }
    });

Hope, you'are looking for the same.

Upvotes: 0

Related Questions