Search code examples
javascriptjqueryhtmlcssslide

slide an image left or right


How do you slide an image left/right using javascript? I want an image to slowly slide to the right. Do you use javascript's setTimeout function to gradually change element style's "left" value? Maybe jQuery has a function for that?


Solution

  • jQuery sure does :)

    There's a built in .animate() function: http://api.jquery.com/animate/

    Code example (slightly modified from the jQuery) is below and I've made a working jsFiddle: http://jsfiddle.net/Damien_at_SF/HRBkN/

    CSS:

    img.block {
      position:absolute;
      left:50px;
      top:50px;
      margin:5px;
    }
    

    HTML:

    <button id="left">left</button> <button id="right">right</button>
    <img src="http://jsfiddle.net/img/logo.png" class="block" />
    

    JS for absolute positioned img:

    $("#right").click(function(){
      $(".block").animate({"left": "+=50px"}, "slow");
    });
    
    $("#left").click(function(){
      $(".block").animate({"left": "-=50px"}, "slow");
    });
    

    JS for relative/static positioned img:

    $("#right").click(function(){
      $(".block").animate({"margin-left": "+=50px"}, "slow");
    });
    
    $("#left").click(function(){
      $(".block").animate({"margin-left": "-=50px"}, "slow");
    });
    

    Hope that helps:)