Majid Nayyeri
Majid Nayyeri

Reputation: 444

addClass just for specific element without specific class or ID

How's goin' on bros ?

I have code that want to add a class to the element when user scrolls the page to the element position and I use this code :

  $(window).on('scroll',function(){
    Scroll = $(this).scrollTop();
        if(Scroll >= $('img').position().top)
        $('img').addClass('rotate');
  });

And my html code is this :

<div class="some-class">
  <img src="http://blog.majidkn.com/wp-content/themes/majidkn2/images/mkn.png" class="feature-size">
</div>

<div class="some-class">
  <img src="http://blog.majidkn.com/wp-content/themes/majidkn2/images/mkn.png" class="feature-size">
</div>

<div class="some-class">
  <img src="http://blog.majidkn.com/wp-content/themes/majidkn2/images/mkn.png" class="feature-size">
</div>

Now, when I run the code, the rotate class applies to all the img tags. but I wanna add the rotate class just to the element that have the conditions that I said in my js if sentence !

What can I do now about it ? you can also see the jsfiddle !

Upvotes: 0

Views: 92

Answers (4)

jackarms
jackarms

Reputation: 1333

You can use jQuery's filter to get only the image tags that suits your requirement, like:

Scroll = $(this).scrollTop();
$('img').filter(function(index, el) {
    return Scroll >= el.position.top();
}).addClass('rotate');

Upvotes: 3

guradio
guradio

Reputation: 15555

$(window).on('scroll', function() {
  Scroll = $(this).scrollTop();
  $('img').each(function() {
    if (Scroll >= $(this).position().top)
      $(this).addClass('rotate');
  })


});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="some-class">
  <img src="http://blog.majidkn.com/wp-content/themes/majidkn2/images/mkn.png" class="feature-size">
</div>

<div class="some-class">
  <img src="http://blog.majidkn.com/wp-content/themes/majidkn2/images/mkn.png" class="feature-size">
</div>

<div class="some-class">
  <img src="http://blog.majidkn.com/wp-content/themes/majidkn2/images/mkn.png" class="feature-size">
</div>

Iterate through each image then use this context to tell the current image

Upvotes: 0

CM Azwar
CM Azwar

Reputation: 23

replace your if statement with this

$('img').each(function(index) {
 if(Scroll >= $(this).position().top)
    $(this).addClass('rotate');

});

Upvotes: 0

Amar Singh
Amar Singh

Reputation: 5622

Loop into all the img and use $(this) to add class

$(window).on('scroll',function(){
    Scroll = $(this).scrollTop();
    $('img').each(function(){
    if(Scroll >= $(this).position().top)
        $(this).addClass('rotate');


      });

});

Upvotes: 3

Related Questions