SHOW:
|
|
- or go back to the newest paste.
| 1 | // This is an improved version of https://stackoverflow.com/a/5835533/1175714 | |
| 2 | ||
| 3 | function slideLoop(currMarg, selector){
| |
| 4 | let contStyle = document.querySelector(selector).style; | |
| 5 | ||
| 6 | return function(){
| |
| 7 | currMarg = (currMarg == 1800) ? (0) : (currMarg + 600); | |
| 8 | contStyle.marginLeft = "-%dpx".replace("%d", curMarg);
| |
| 9 | } | |
| 10 | } | |
| 11 | ||
| 12 | function slide() {
| |
| 13 | return setInterval(slideLoop(0, "#container"), 3000); | |
| 14 | } | |
| 15 | ||
| 16 | ||
| 17 | // Notes: | |
| 18 | // Use document.querySelector(css_selector) instead of document.getElementById(id) | |
| 19 | // Always track setInterval(fn, interval)'s return value so it can later be closed with clearInterval(interval_id) | |
| 20 | // Put the interval's callback into its own formal function for readability and maintainability | |
| 21 | // If state is kept with the callback, the callback should be returned from another function (slideLoop) to form a closure. | |
| 22 | // Use proper whitespace. Logical blocks that do different things should be separated by one empty line | |
| 23 | // Avoid "string" + value + "string" + ... Make a format function or use String.prototype.replace(string/regex, new_string) | |
| 24 | // Always surround the arguments of your ternary expressions with parens. It aids readability and prevents bugs. |