webwrks
webwrks

Reputation: 11918

jQuery create function and call it on each separately

Hey guys I'm trying to create a function and call it inside another each loop. I got it to work, but the each loop is not working. So I tried to add an extra $(this) and it didn't work either...any help is appreciated.

.moveClass {
position:relative;
}

$(function() {

$('.a_projectLoad').each(function(evt){
    $(this).hover(function(){
        $(this).slideRight();
    });
});

});

function slideRight () {
    $('.img_rightArrow')
        .addClass('moveClass')
        .animate({"left": "+=50px"}, "fast");
}

<table>
             <tr>
                <td><a href="#" class="a_projectLoad">Title Goes Here</a></td>
                <td ><img src="images/btn_loadProject.png" class="img_rightArrow"/></td>
              </tr>
              <tr>
                <td><a href="#" class="a_projectLoad">Title Goes Here</a></td>
                <td><img src="images/btn_loadProject.png" class="img_rightArrow"/></td>
              </tr>
</table>

Upvotes: 2

Views: 8927

Answers (2)

lsuarez
lsuarez

Reputation: 4992

Add the position: relative attribute to your images directly as part of the markup rather than programmatically via JavaScript. This will not alter its initial rendering and therefore should not be done in code.

Next, bind a custom slideRight event and invoke it on hover as follows:

$(function() {

    // Bind a custom slideRight event to each image
    $('img.img_rightArrow').bind({
        slideRight: function () {
            $(this).stop(true, true).animate({"left": "+=50px"}, "fast");
        },
        slideLeft: function () {
            $(this).stop(true, true).animate({"left": "-=50px"}, "fast");
        }
    });

    $('a.a_projectLoad').hover(function () {
        // Traverse DOM to find nearby arrow image
        $(this).closest("tr").find("img.img_rightArrow").trigger("slideRight");
    }, function () {
        $(this).closest("tr").find("img.img_rightArrow").trigger("slideLeft");
    });

});

FYI: your images are missing the img_rightArrow class in the sample markup.

You could probably use a second functional parameter to .hover() to bind to the mouseout event. Check out the documentation for more information. I assume in your example it might be something of the sort of a trigger to a slideLeft event. Just a thought however.

Upvotes: 1

Gowri
Gowri

Reputation: 16835

Are you looking for this ?

$('.a_projectLoad').each(function(evt){
        $(this).hover(slideRight);
    });

function slideRight () {

    $('.img_rightArrow')
        .addClass('moveClass')
        .animate({"left": "+=50px"}, "fast");
}


});

It works me

Upvotes: 0

Related Questions