appendChild method in a simple carousel with pure JavaScript -
i trying make simple javascript carousel scratch.
css
#wrapper{ position: relative; width: 450px; height: 150px; margin: 0 auto; overflow: hidden; } #container{ position: absolute; width: 450px; height: 150px; } .child{ width: 150px; height: 150px; padding-top: 35px; float: left; text-align: center; font-size: 60px; } #a{ background: #ff0000; } #b{ background: #ffff00; } #c{ background: #00ffff; }
html
<div id="wrapper"> <div id="container"> <div id="a" class="child">a</div> <div id="b" class="child">b</div> <div id="c" class="child">c</div> </div> </div>
js
var firstval = 0; function carousel(){ firstval += 2; parent = document.getelementbyid( 'container' ); parent.style.left = "-" + firstval + "px"; if( !( firstval % 150 ) ){ settimeout(carousel, 3000); firstval = 0; var firstchild = parent.firstchild; parent.removechild( firstchild ); parent.appendchild( firstchild ); return; } runcarousel = settimeout(carousel, 20); } carousel();
till now, cycles this:
a b c b c - c - b -
i think there wrong append , timing.
question
what doing wrong? should use appendchild
, removechild
method in way?
change line:
var firstchild = parent.firstchild;
… this:
var firstchild = parent.firstelementchild;
otherwise, you'll grabbing whitespace text nodes.
you don't need following code, because appendchild
automatically move firstchild
:
parent.removechild( firstchild );
finally, reset container's left 0 here:
parent.appendchild(firstchild); parent.style.left= 0;
otherwise, -150px
offset cause second child disappear offscreen when first appended parent.
Comments
Post a Comment