Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Add (or remove) .class when on 50% right of screen

I'm trying to create an effect where some item move slowly scrolling from left to right and the idea is they 'go through' a machine that adds colour to them. I will be using .svg images and plan to do this by adding a class to them along with nth number to give different colours.

Example example image

The problem I'm having is how to add the class when it is on the right side on the viewport. I'm sure there is a javascript way so any help would be superb. Many thanks.

Sul

3 Answers

If you are using Jquery you could use this

    if( $(".BLOCK_CLASSNAME").offset().left > $(document).width()/2 ){
      $(".BLOCK_CLASSNAME").addClass("COLORED_BLOCK_CLASSNAME")
    }

But you still need something to trigger it (e.g. an Intervall)

I tried this, not sure if I going about this wrong

http://codepen.io/Sulcalibur/pen/QjRrjB

Like Daniel said, you will need to use setInterval() to repeatedly execute this logic every few milliseconds. You also need to animate your dots so they are moving across the window.

So basically, here is the process you need:

every x amount of milliseconds 
   move dots x amount of pixels to the right
   test if each dot is greater than 50% across the window
   if the dot IS greater than 50% across the window, AND hasn't already been changed color
      then change the dot's color.

Since you have more than one icon that needs to be checked you should use the each method.

$('.icon').each(function() { 
  if ($(this).offset().left > $(document).width() / 2) 
  { 
    $(this).addClass('made');
  }
});

You can use .className to add a class to an element using vanilla javascript. Or if you are using jQuery, you can use the .addClass() method.

Thanks guys, I'm still a bit flaky when it comes to these thing so thank you very much!

For other folks, you can see the code here on Codepen