2

Im trying to create a function in javascript/jquery that creates a cool animation to the selected object. Problem is, when I add more objects too it, it acts pretty weird.

I understand that this is because if i for example add 4 objects too it, the code runs 4 times. How do I change this so it only goes of once on all the selected objects?

The code:

function showPress(name) {
    var top = "15";
    var bottom = "20";

    $(name).hide();

    $(name).show(150, function() {
        $(name).animate( {
            "margin-top": "+="+top+"px",
            "margin-left": "+="+bottom+"px"
        }, 150, function() {
            $(name).animate({
                "margin-top": "-="+top+"px",
                "margin-left": "-="+bottom+"px"
            });
        });
    });
}

showPress("h1");

TL;DR: What is going on here and how can I fix it? (I've tried but failed)

http://jsfiddle.net/LWRAj/

talemyn
  • 7,822
  • 4
  • 31
  • 52
Jacob
  • 1,933
  • 2
  • 20
  • 30
  • `$(name).first()` comes to mind ? – adeneo Apr 22 '14 at 21:05
  • Then the function work on the first h1 but still goes crazy off the screen. – Jacob Apr 22 '14 at 21:05
  • The animate callback gets called once for each element selected. Here's a question that solves that in two different ways. http://stackoverflow.com/questions/8790752/callback-of-animate-gets-called-twice-jquery – Kevin B Apr 22 '14 at 21:06
  • 1
    What do you mean selected objects? In this case selected objects are all of your h1 tags. – milagvoniduak Apr 22 '14 at 21:07

1 Answers1

6

Change the internal references of name for this:

$(name).show(150, function () {

    $(this).animate({

        "margin-top": "+="+top+"px",
        "margin-left": "+="+bottom+"px"

    }, 150, function () {

        $(this).animate({

            "margin-top": "-="+top+"px",
            "margin-left": "-="+bottom+"px"

        });
    });
});

JSFiddle

DarkAjax
  • 15,955
  • 11
  • 53
  • 65