1

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.

0

2 Answers 2

2
$('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();
  });  
});    
Sign up to request clarification or add additional context in comments.

9 Comments

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.
@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.
I edited the code to how everyone would be set up and how I think it should be. jsfiddle.net/3c7Gy/24
@Andrew Manson Give me 2 minutes
@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.
|
0

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

Well, most of the time I just use the following.
$('.more-link').click(function(){ $(this).animate(...)}; }, function({ $(this).animate(...)}); });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.