0

I'm new to javascript and jquery, so I tried to make a sliding background and the only way I made it work is:

$('.mainTitles').click(function() {
    var self = $(this);

    if (!self.hasClass('toggled')) {

        setTimeout(function func() {
            self.css({
                'background-position-y': '20%'
            });
        }, 25);
        setTimeout(function func() {
            self.css({
                'background-position-y': '40%'
            });
        }, 50);
        setTimeout(function func() {
            self.css({
                'background-position-y': '60%'
            });
        }, 75);
        setTimeout(function func() {
            self.css({
                'background-position-y': '80%'
            });
        }, 100);
        setTimeout(function func() {
            self.css({
                'background-position-y': '100%'
            });
        }, 125);

        self.addClass('toggled');

    } else {

        setTimeout(function func() {
            self.css({
                'background-position-y': '80%'
            });
        }, 25);
        setTimeout(function func() {
            self.css({
                'background-position-y': '60%'
            });
        }, 50);
        setTimeout(function func() {
            self.css({
                'background-position-y': '40%'
            });
        }, 75);
        setTimeout(function func() {
            self.css({
                'background-position-y': '20%'
            });
        }, 100);
        setTimeout(function fun() {
            self.css({
                'background-position-y': '0'
            });
        }, 125);

        self.removeClass('toggled');
    }

});

I kind of tried to nest setTimeout in loop but with no result. Could someone mention the right way to do this without that bunch of stupid code. Thanks! BTW, jquery animate didn't work for me because I want it to change in steps not smoothly.

Anjith K P
  • 2,158
  • 27
  • 35
zogby
  • 462
  • 4
  • 15

2 Answers2

1

You can use the step-callback from jQuery.fn.animate to animate the background-position. Then use jQuery.fn.toggleClass to add/remove the state-class. Depending on this you can animate your background:

$("body").click(function() {
    var $self = $(this).toggleClass("toggled");
    var toggled = $self.hasClass("toggled");
    var pos = toggled ? 0 : 100;

    $({bg: pos}).animate({bg: 100 - pos}, {
        step: function(now){
            $self[0].style.backgroundPosition = "0 " + now + "%";
        }
    });
});

http://fiddle.jshell.net/69PrJ/

yckart
  • 32,460
  • 9
  • 122
  • 129
0

Here is stack overflow answer to similar question.

And here are three pens with similar effect using TweenMax

Community
  • 1
  • 1
Chris Panayotoff
  • 1,744
  • 21
  • 24