Michael Stum
Michael Stum

Reputation: 180924

JQuery hover only applies to the last element?

I have a little trouble understanding scope and lifetime using javaScript and jQuery. I have a function that takes an array of custom objects (gps is an array of groups)

var currentGroup;
for(var index = 0, length = gps.length; index < length; ++index)
{
    currentGroup = gps[index];
    var newGroup = $('<li id="groupno-' + currentGroup.getID() + '"><span class="group">Group ' + currentGroup.getID() +'</span></li>');

    newGroup.hover(
        function() {newGroup.find("span.group").append(GetGroupActionsContainer(currentGroup.getID()));},
        function() {newGroup.find("span.group > .GroupActionsContainer").remove();}
    );

    gl.append(newGroup);
    gl.treeview({
        add: newGroup
    });
}

So this looks through gps and retreives the currentGroup as an object. Then it creates a new object (confusingly named newGroup at the moment, going to rename it) which is a jQuery object holding a li.

gl is a <ul> on the page.

The problem: This function correctly adds new <li> to the <ul> represented by gl - my list shows all elements. But the hover only applies to the last element: if I have 2+ items and I hover over any of them, I see the icons created by the hover function on the last <li>.

Does anyone know what could be wrong here? I'm guessing that somehow, .hover doesn't apply to the object but to some reference that gets updated while iterating through the loop, but that's pure guessing.

Upvotes: 2

Views: 705

Answers (1)

tvanfosson
tvanfosson

Reputation: 532435

The newGroup being captured in your hover functions references the last one created in the loop. Use $(this) inside your hover function to reference the hovered element.

newGroup.hover(
    function() {
        var $this = $(this);
        var groupID = $this.attr('id').replace( /groupno-/, '');
        $this.find("span.group").append(GetGroupActionsContainer(groupID));
    },
    function() { $(this).find("span.group > .GroupActionsContainer").remove(); }
);

Upvotes: 4

Related Questions