Timothy Timothy - 3 months ago 11
Javascript Question

Slide div in and out on timed loop

I need some help please. I trying to get my div "hello" to slide in and out on a timed loop. Like the following below.

  • Slide IN (pause) for: 5 seconds

  • Slide OUT (pause) for: 12 seconds


  • Slide IN (pause) for: 5 seconds

  • Slide OUT (pause) for: 12 seconds


  • Just keep on doing that!

    Here's an example on JSFiddle
    https://jsfiddle.net/08nr9ya5/

    <div id="hello">
    Hello World!
    </div>

    function show() {
    setTimeout(function() {
    $('#hello')
    .css('margin-right', -$(this).width())
    .animate({
    marginLeft: -1500
    }, 900);
    }, 2000);
    hide();
    }

    function hide() {
    setTimeout(function() {
    $('#hello')
    .css('margin-right', -$(this).width())
    .animate({
    marginLeft: 0
    }, 900);
    }, 5000);
    }

    show();

    Answer

    Actually I missed that you called hide() from the show() function without a timeout. And your timeouts were around the code to change the div, not for starting the next function.

    I've cleaned it up a bit, you don't need 3 timeouts, only two. I also swapped around the code in the functions - the show function now actually has the code in it to make the div slide in, and the hide function to slide it out. Before you had the opposite, just wrapped in timeouts...

    function show() {
       // slide in immediatly when show() is called
       $('#hello')
            .css('margin-right', -$(this).width())
            .animate({
              marginLeft: 0
        }, 900);
        // calls hide() after 5 seconds
        setTimeOut(function(){
            hide();
        }, 5000);
    }
    
    function hide() {
        // slide out immediatly when hide() is called
        $('#hello')
          .css('margin-right', -$(this).width())
          .animate({
            marginLeft: -1500
          }, 900);
        // calls show() after 12 seconds
        setTimeout(function(){
            show();
        }, 12000);
    }
    
    hide();
    

    https://jsfiddle.net/08nr9ya5/2/

    Comments