For example, if I want to create a jQuery function on a click for a css class "more-link", however have multiple instances of "more-link" on the page, how can I force jQuery to only run the animation on the clicked class, and not other ones.
2 Answers
$('element').click(function(){
$(this).animate({
//scope is ONLY the element clicked
});
$('element').animate({
//this wi ll animate ALL elements matching the selector. Not what you want.
});
});
For anyone who finds this answer, the author actually wanted this.
$('.read-more').click(function(){
var me = $(this);
$(this).prev('p').animate({
height: '100%'
}, function(){
//lost $(this) scope...me still holds it, we use it below for a reason.
$(me).fadeOut(400);
$(me).next('.hide_post-content').delay(400).fadeIn();
});
});
9 Comments
Andrew Manson
The only problem for this is, if I have multiple classes labeled 'more-link' then I click on, for example, the third from the first, only the first one will be animated.
Ohgodwhy
@Andrew Manson No. I'm sorry, but that's not true to any extent. See the previous link for an example, Ignore the callback function I created to resize the element when I'm done with it.
Andrew Manson
I edited the code to how everyone would be set up and how I think it should be. jsfiddle.net/3c7Gy/24
Ohgodwhy
@Andrew Manson Give me 2 minutes
Ohgodwhy
@Andrew Manson Here's how this should actually be setup. Once again, you weren't referencing $(this)...as I stated in my answer. In a callback function, you lose reference to $(this), and need to declare it within the function, which is why I use
var me = $(this); in my jsfiddle response. There you go. |
In jQuery, $(this) refers to the element that was clicked:
$('.more-link').on('click', function() {
$(this).animate(...);
});
Were you using $('.more-link') by accident?
2 Comments
Andrew Manson
Well, most of the time I just use the following.
Andrew Manson
$('.more-link').click(function(){ $(this).animate(...)}; }, function({ $(this).animate(...)}); });