Question

I have a clickable bar, that once clicked moves three separate boxes using the .animate function of Jquery.

I need the same button to reverse the animations when clicked again. I'm still a noob with Jquery, so I'm sure this is a simple scope issue, but I can't figure it out.

Jquery:

// Show More Copy
$('.copy-more').click(function(){

    var _toggle = 0;

    var _header;
    var _sum;
    var _full;
    var _opacity;
    var _text;

    if ( _toggle === 0) {

        _header = 120;
        _sum = 150;
        _full = 220;
        _opacity = 1;
        _text = "Read Less";

        _toggle = 1;
    }
    else {
        _header = 310;
        _sum = 345;
        _full = 420;
        _opacity = 0;
        _text = "Read More";

        _toggle = 0;
    }

    $('.slide-header').animate({'top': _header}, 150);
    $('.copy-sum').animate({'top': _sum}, 250);
    $('.copy-full').animate({'top': _full, 'opacity': _opacity}, 500);
    $('.copy-more').animate({'opacity': 0}, 500, function () {
        $(this).text(_text);
         }).animate({'opacity': 1}, 500);
});
Was it helpful?

Solution

_toggle is defined inside the .click scope. It needs to be scoped further up for this to work:

// Move _toggle to here
var _toggle = 0;
$('.copy-more').click(function(){

    var _header;
    var _sum;
    var _full;
    var _opacity;
    var _text;

    if ( _toggle === 0) {

        _header = 120;
        _sum = 150;
        _full = 220;
        _opacity = 1;
        _text = "Read Less";

        _toggle = 1;
    }
    else {
        _header = 310;
        _sum = 345;
        _full = 420;
        _opacity = 0;
        _text = "Read More";

        _toggle = 0;
    }

    $('.slide-header').animate({'top': _header}, 150);
    $('.copy-sum').animate({'top': _sum}, 250);
    $('.copy-full').animate({'top': _full, 'opacity': _opacity}, 500);
    $('.copy-more').animate({'opacity': 0}, 500, function () {
        $(this).text(_text);
         }).animate({'opacity': 1}, 500);
});

However, you should look into .toggleClass and CSS3 animations instead - much cleaner

OTHER TIPS

Jquery toggle() will do just what you are asking for. There will be no need for you to check any flags on using .toggle().

$('#target').toggle(function() {
  alert('First handler for .toggle() called.');
}, function() {
  alert('Second handler for .toggle() called.');
});

Take a look at this jsfiddle demo. Also see this documentation for further reference.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top