2

So I am very very new to JavaScript and unfortunately I don't know the basics too well also.

I was working on a code to make an element hidden after clicking it and again reversing back the effect by clicking the same button but I am unable to do so. Please help me here is the code:

$(function() {
    $('#boxclose').click(function(){
        $('#md-share-window').animate({'bottom':'-90px'},500,function(){});
    });
});

2 Answers 2

1

You can use a class to identify the state of the element you are animating.

Here's an example: http://jsfiddle.net/FgDaq/

$('#boxclose').click(function() {
    var c = 'on',
        el = '#md-share-window',
        duration = 500;

    if ($(el).hasClass(c)) {
        $(el).animate({'bottom': 0}, duration)
            .removeClass(c);
    } else {
        $(el).animate({'bottom': '-90px'}, duration)
            .addClass(c);
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Can I please know why duration = 500; was added ??
@user2414789 just as a good practice. Makes the code more maintainable and less prone to human-errors. If you ever want to change the animation durration, you have to change it only at one place.
1

You'll need to get the initial position (or hard code it) and keep track of whether you are in the initial or updated position:

$(function() {
    var shareWindow = $('#md-share-window');
    var initialPosition = shareWindow.css('bottom'); //get initial position
    var atInitialPos = true; //whether this is the initial or updated position

    $('#boxclose').on('click', function(){
        var newPosition = atInitialPos ? '-90px' : initialPosition; //determines new position
        shareWindow.animate({'bottom': newPosition}, 500);
        atInitialPos = !atInitialPos; //toggle initial position boolean
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.