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

click and animation

Hi everyone! The following code is working fine on the first click but on the second it does not and I cant figure why. Here is the code:

<body>
  <div class="container"></div>         
  <button>click</button> 
</body>

<style>
  .container{
        background-color: black;
        height: 50%;
        width: 20%;
        position: absolute;
        top: 30%;               
    }       
</style>
<script>
$(document).ready(function(){                
    $( "button" ).click(function(){ 

             screenWidth = $("html").width() /2;
         positionLeft = Math.round($(".container").offset().left)   

        if ( positionLeft < screenWidth) {      
                   $(".container").animate({
            left: "50%"
            }, 1000);
        } else if (positionLeft = screenWidth) {                    
            $(".container").animate({
            right: "50%"
            }, 1000);   
        }
    }); 
});
</script>

4 Answers

I found the answer, going to post it in case it will help anybody:

Since you are already walking in one direction, you have to turn around... If you want to position an element, you can declare only the offset from "the same sides" (top-left / bottom-right). Just reset the opposite with the auto-value.

    if ( positionLeft < screenWidth) {
      $(".container").css('right', 'auto');
      $(".container").animate({
        left: "50%"
      }, 1000);
    } else if (positionLeft == screenWidth) {
      $(".container").css('left', 'auto');
      $(".container").animate({
        right: "50%"
      }, 1000);
    }

Thanks for posting this. I struggled with this for a while on a small project and ended up just using left for horizontal movement.

Hi cesarguido,

You could use the .toggle() function for that. The .click() function runs only once when its clicked and the script finishes.

<script>
$(document).ready(function(){                
    $( "button" ).click(function(){ 
        $(this).toggle(function() {

             screenWidth = $("html").width() /2;
         positionLeft = Math.round($(".container").offset().left)   

        if ( positionLeft < screenWidth) {      
                   $(".container").animate({
            left: "50%"
            }, 1000);
        } else if (positionLeft = screenWidth) {                    
            $(".container").animate({
            right: "50%"
            }, 1000);   
        }
       });
    }); 
});
</script>

For explenation check this jQuery .toggle (The API Documentation)

Hope this helps.

I know I can use toggle and thx for the reply but I want to know why my code is not working in case I have more than 2 options where to move the container.

Hi cesarguido,

There are a couple lines I had to change in order to get your code to work.

// the conditional here is trying an assignment operation instead of checking for equality
} else if (positionLeft = screenWidth) {

// for reasons I don't yet understand, animate does not work with the CSS property right. Need to use left.
right: "50%"

After changing those lines, and some other Web page boilerplate code, here is the working version:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .container{
            background-color: black;
            height: 50%;
            width: 20%;
            position: absolute;
            top: 30%;               
        }       
    </style>
</head>
<body>
    <div class="container"></div>         
    <button>click</button>      

    <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>

    <script>
        $(document).ready(function(){                
            $("button").click(function(){ 
                screenWidth = $("html").width() /2;
                positionLeft = Math.round($(".container").offset().left)

                if (positionLeft < screenWidth) {      
                    $(".container").animate({
                        left: "50%"
                    }, 1000);
                } else if (positionLeft == screenWidth) {                    
                    $(".container").animate({
                        left: "0%"
                    }, 1000);   
                }
            });
        });
    </script>
</body>
</html>

Kind Regards

Well first i want to say thx very much for the answer, but I need to do it with the right in case of screen size changes (when the start point is not 0) do you think this is a bug? it is common to find such an errors on jquery? or maybe the code is wrong somewhere? im just asking so i don't use this kind a method in the future. I am still a noob in this area.

You should be able to accomplish what you want using only left. Think of it as an amount from the left edge of the parent container. If right were a valid property, the same effect can be achieved by inverting the values.

left: "40%"

// would be the same thing as

right: "60%"

// from the right edge, move 60% of the parent container's width

left can be set to any value, positive or negative. Therefore, you can set or animate to a position off-screen on either side.

left: "-100%"

// or

left: "150%"

Slight correction: since the element has an absolute position, left: 0% can either mean parent container (if the parent has a relative position) or root container (the html element).

I just happened to stumble upon this example using the CSS right property for animating in jQuery. Just wanted to pass this along that I'm wrong and it's possible to use right.

Kind Regards

Thx Robert, but is not about left and right. if you switch right and left words in my code, then the problem will be with the left. I am giving up on this. I already found another solutions but this is driving my nuts and I guess I just have to let it go. so far you have the best answer. I am going to wait a couple of days in case some genius might show up with an explanation.