How to animate the list?

This is my JSFiddle

As you can see from the script, there is a list that scrolls with the arrows. So I want to enliven this transition when the list is visible and hidden.

I do not know about animation. I saw a lot of examples and tried to tweak them using my example, but it doesn’t work ... How to get a list for animation?

$(document).ready(function(){ var code=''; for(var i=1;i<=20;i++) { code+="<li>list Item "+i+"</li>"; } $('#list-items').html(code); }); var list_items = []; var index = 0; var list_length = 0; function getAllListItems() { var temp = document.getElementsByTagName('li'); for (i = 0; i < temp.length; i++) { list_items.push(temp[i]); } list_length = temp.length; } getAllListItems(); function move(dir) { if (dir == left) { list_items[index].style.display = 'block'; index--; if (index < 0) { index = 0; } } else if (dir == right) { list_items[index].style.display = 'none'; if (index >= ((list_length) - 1)) { index = (list_length) - 1; } else { index++; } } else {} } 
 * { box-sizing: border-box; } ul { float:left; height:50px; width: 600px; overflow: hidden; } ul li { text-align: center; border: 2px solid black; width: 100px; height: 50px; float: left; list-style-type: none; background-color: aquamarine; } ul li:first-child { display: block; } #left, #right { float:left; height:50px; background-color:aqua; font-size:2em; padding-left: 20px; padding-right:20px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body onload='getAllListItems()'> <div id='t'></div> <button id='left' onClick="move(left)"> <</button> <ul id='list-items'> </ul> <button id='right' onClick='move(right)'>></button> </body> 
+7
javascript jquery html css
source share
1 answer

You can easily just replace your lines:

 list_items[index].style.display = 'block'; list_items[index].style.display = 'none'; 

with jQuery show() and hide() functions:

 $(list_items[index]).show("slow"); $(list_items[index]).hide("slow"); 

As shown in my updated version of Fiddle

For different transitions, you can use the animate() function, which allows you to tell which css properties are affected. In addition to numeric values, jQuery also supports the special values ​​of 'show' , 'hide' and 'toggle' (which, by the way, will show, hide or switch the show / hide status of an element using this property). For example, if you want to compress them only horizontally and leave the vertical alone, you can change the calls to .show() and .hide() to:

 $(list_items[index]).animate({width:'show'}, 600); $(list_items[index]).animate({width:'hide'}, 600); 

I demonstrated this in another updated Fiddle

+11
source share

All Articles