Search code examples
jqueryarraysbackgroundposition

jquery array of background positions with set links


Okay I've been working on this fiddle. Basically it is four buttons which control the background image position but going from position to position is isn't smooth. Would there be a better way of doing the samething?

Here is my Code:

html:

<div id="container">
    <div id="content">
        <ul>
            <li id="btn-0">button-1</li>
            <li id="btn-1">button-2</li>
            <li id="btn-2">button-3</li>
            <li id="btn-3">button-4</li>
        </ul>
    </div>
</div>

Javascript:

$(document).ready(function () {
    $('li').click(function () {
        currClick = $(this).index();
        bgPos = [{
            'background-position-x': '0px',
                'background-position-y': '0px'
        }, // 0
        {
            'background-position-x': '-50px',
                'background-position-y': '-150px'
        }, // 1
        {
            'background-position-x': '150px',
                'background-position-y': '-20px'
        }, // 2
        {
            'background-position-x': '-200px',
                'background-position-y': '-250px'
        } // 3
        ];
        $('#container').animate(bgPos[currClick], 1500, 'swing');
    });
});

CSS:

#container {
    height:500px;
    width:500px;
    background-image:url("http://postmediawindsorstar.files.wordpress.com/2013/01/cat_shot_by_arrow-1.jpg");
}
#content {
    position:absolute;
    margin-left:-250px;
    left:50%;
    height:300px;
    width:300px;
    border:1px solid #FFF;
}
li {
    color:#FFF;
}

Also if you spam click the buttons, it does not stop its current animation before moving to the next position.


Solution

  • CSS Animations are much quicker than js in the browser. I would look into them:

    http://css3.bradshawenterprises.com/blog/jquery-vs-css3-transitions/