{"id":3191,"date":"2013-08-21T23:01:58","date_gmt":"2013-08-22T06:01:58","guid":{"rendered":"http:\/\/g-liu.com\/blog\/?p=3191"},"modified":"2015-05-01T23:08:28","modified_gmt":"2015-05-02T06:08:28","slug":"tutorial-basic-carouselslideshow-with-javascript","status":"publish","type":"post","link":"https:\/\/g-liu.com\/blog\/2013\/08\/tutorial-basic-carouselslideshow-with-javascript\/","title":{"rendered":"Tutorial: Basic carousel\/slideshow with JavaScript"},"content":{"rendered":"<p>Slideshows and carousels can add a lot to your website. They can be used in headers, blog posts, image showcases and more.<\/p>\n<p>Today, we&#8217;ll learn how to create your own slideshow from scratch with Javascript and a little HTML.<br \/>\n<!--more--><\/p>\n<h1>Getting started<\/h1>\n<p>From a pseudocode standpoint, we&#8217;ll need to use the following:<\/p>\n<ol>\n<li>Buttons that, when pressed, take the user to the next or previous slide<\/li>\n<li>A collection of items to display<\/li>\n<li>A way to make it such that only one item shows up at a time.<\/li>\n<li>For automatic slideshows, a timer that switches the slide every so often<\/li>\n<\/ol>\n<p>The first item is easy. JavaScript provides a <code>setInterval(event, time)<\/code> function, which can trigger events every X milliseconds. The second item could be an <code>&lt;input type=\"button\" onclick=\"advance()\"... \/&gt;<\/code> which changes the item displayed. The third item can be an unordered list, and the fourth will rely on CSS&#8217;s <a href=\"http:\/\/www.w3schools.com\/cssref\/pr_class_display.asp\" target=\"_blank\"><code>display<\/code> property<\/a>.<\/p>\n<h1>Step 1: Getting our items together<\/h1>\n<p>Clearly, we can&#8217;t have a slideshow or carousel without text, images, or other media. Let&#8217;s display the media in an unordered list as such:<\/p>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">&lt;\/pre&gt;\r\n&lt;ul style=&quot;list-style-type: none; margin-left: -2em;&quot;&gt;\r\n\t&lt;li id=&quot;1&quot; class=&quot;hideable&quot; style=&quot;display: block;&quot;&gt;&lt;!-- YOUR CONTENT HERE --&gt;&lt;\/li&gt;\r\n\t&lt;li id=&quot;2&quot; class=&quot;hideable&quot;&gt;&lt;!-- YOUR CONTENT HERE --&gt;&lt;\/li&gt;\r\n\t&lt;li id=&quot;3&quot; class=&quot;hideable&quot;&gt;&lt;!-- YOUR CONTENT HERE --&gt;&lt;\/li&gt;\r\n&lt;!-- ... and so on --&gt;&lt;\/ul&gt;\r\n&lt;pre&gt;\r\n&lt;!-- Buttons to go back and forth between slides. --&gt;&lt;\/pre&gt;\r\n&lt;form&gt;\r\n&lt;input type=&quot;button&quot; value=&quot;Back&quot; \/&gt;\r\n&lt;input type=&quot;button&quot; value=&quot;Forward&quot; \/&gt;\r\n&lt;\/form&gt;\r\n&lt;pre&gt;\r\n<\/pre>\n<p>CSS:<\/p>\n<pre class=\"brush: css; title: ; notranslate\" title=\"\">\r\n.hideable {\r\n    display: none;\r\n}\r\n<\/pre>\n<p><i>Notes: For each successive <code>LI<\/code>, the id increases by 1. On one and only one <code>LI<\/code>, <code>style=\"display: block;\"<\/code> must be added as an attribute. This is the list-item that will show up by default when the user loads the slideshow.<\/i><\/p>\n<h1>Step 2: The JavaScript<\/h1>\n[note color=&#8221;#FFCC00&#8243;]Place all your JavaScript within the head tags<\/code>[\/note]\nNow, we can write the JavaScript that makes the slideshow work. We have three options here: a manual slideshow where users must press buttons to navigate between slides, an automatic slideshow that displays each slide for X milliseconds, or a combination of both (along with a Pause button).<\/p>\n<h2>Option 1: Manual navigation<\/h2>\n<p>When we made our buttons in Step 1, we specified that they would call a JS Function <code>toggleSlide()<\/code> when clicked. Now, let&#8217;s make that function.<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n\/\/ direction = boolean value: true or false. If true, go to NEXT slide; otherwise go to PREV slide\r\nfunction toggleSlide(direction) {\r\n    var elements = document.getElementsByClassName(&quot;hideable&quot;); \/\/ gets all the &quot;slides&quot; in our slideshow\r\n\r\n    \/\/ Find the LI that's currently displayed\r\n    var visibleID = getVisible(elements);\r\n\r\n    elements&#x5B;visibleID].style.display = &quot;none&quot;; \/\/ hide the currently visible LI\r\n    if(!direction) {\r\n        var makeVisible = prev(visibleID, elements.length); \/\/ get the previous slide\r\n    } else {\r\n        var makeVisible = next(visibleID, elements.length); \/\/ get the next slide\r\n    }\r\n    elements&#x5B;makeVisible].style.display = &quot;block&quot;; \/\/ show the previous or next slide\r\n}\r\n\r\nfunction getVisible(elements) {\r\n    var visibleID = -1;\r\n    for(var i = 0; i &lt; elements.length; i++) {\r\n        if(elements&#x5B;i].style.display == &quot;block&quot;) {\r\n            visibleID = i;\r\n        }\r\n    }\r\n    return visibleID;\r\n}\r\n\r\nfunction prev(num, arrayLength) {\r\n    if(num == 0) return arrayLength-1;\r\n    else return num-1;\r\n}\r\n\r\nfunction next(num, arrayLength) {\r\n    if(num == arrayLength-1) return 0;\r\n    else return num+1;\r\n}\r\n<\/pre>\n<h2>Option 2: Adding a timer for automatic navigation<\/h2>\n<p>Instead of making the user click buttons to change slides, we can have a timer to do it automatically.<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nvar interval = 3500; \/\/ You can change this value to your desired speed. The value is in milliseconds, so if you want to advance a slide every 5 seconds, set this to 5000.\r\nvar switching = setInterval(&quot;toggleSlide(true)&quot;, interval);\r\n<\/pre>\n<p>That&#8217;s it! Add this to the top of the JavaScript in Option 1.<\/p>\n<h2>Option 3: Combining the two<\/h2>\n<p>Of course, if you want the slideshow to advance automatically AND have buttons for the user to navigate between slides, you can simply add the code in Option 2 to Option 1, and leave everything else alone.<\/p>\n<p>But what if the user wants to pause?<\/p>\n<p>This is very simple. In the HTML, add the following button between Prev and Next:<\/p>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">\r\n&lt;input id=&quot;pauseButton&quot; type=&quot;button&quot; value=&quot;Pause&quot; \/&gt;\r\n<\/pre>\n<p>In the JavaScript:<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nwindow.paused = false;\r\n\r\nfunction toggleInterval() {\r\n    var button = document.getElementById(&quot;pauseButton&quot;);\r\n    if(!window.paused) {\r\n        clearInterval(switching);\r\n        button.value = &quot;Resume&quot;;\r\n    } else {\r\n        switching = setInterval(&quot;toggleSlide(true)&quot;, interval);\r\n        button.value = &quot;Pause&quot;;\r\n    }\r\n    window.paused = !(window.paused);\r\n}\r\n<\/pre>\n<h1>Extras<\/h1>\n<h2>First and last buttons<\/h2>\n<p>We can add buttons to go to the first or last item in the slideshow.<\/p>\n<p>Add these buttons somewhere in the form:<\/p>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">\r\n&lt;input id=&quot;firstButton&quot; type=&quot;button&quot; value=&quot;First&quot; \/&gt;\r\n&lt;input id=&quot;lastButton&quot; type=&quot;button&quot; value=&quot;Last&quot; \/&gt;\r\n<\/pre>\n<p>JavaScript:<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n\/\/ where = boolean. false =&gt; go to first item, true =&gt; go to last item.\r\nfunction goToEdge(where) {\r\n    var elements = document.getElementsByClassName(&quot;hideable&quot;);\r\n    var visibleID = getVisible(elements);\r\n    var firstButton = document.getElementById(&quot;firstButton&quot;);\r\n    var lastButton = document.getElementById(&quot;lastButton&quot;);\r\n\r\n    elements&#x5B;visibleID].style.display = &quot;none&quot;; \/\/hides the currently visible item\r\n    if(!where) {\r\n        elements&#x5B;0].style.display = &quot;block&quot;; \/\/shows the first item\r\n    } else {\r\n        elements&#x5B;elements.length-1].style.display = &quot;block&quot;; \/\/shows the last item\r\n    }\r\n}\r\n<\/pre>\n<h2>Display current item number<\/h2>\n<p>On some slideshows, there is a text hint, like &#8220;Slide 2 of 7&#8221; or &#8220;Page 4&#8221;. We can add this to our slideshow.<\/p>\n<p>In the HTML, where you want to display the text, paste this code. I have placed this right above the navigation buttons.<\/p>\n<pre class=\"brush: xml; title: ; notranslate\" title=\"\">\r\nSlide &lt;!-- you can change &quot;Slide&quot; to Page, Item, etc. --&gt;\r\n&lt;span id=&quot;slideNumber&quot;&gt;\r\n&lt;script type=&quot;text\/javascript&quot;&gt;\r\nvar elements = document.getElementsByClassName(&quot;hideable&quot;);\r\nvar vis = getVisible(elements) + 1;\r\ndocument.write(vis);\r\n&lt;\/script&gt;\r\n&lt;\/span&gt;\r\nof &lt;!-- Or use &quot;\/&quot;, as in Page 3\/7 --&gt;\r\n&lt;script type=&quot;text\/javascript&quot;&gt;\r\n\/\/ Write the number of slides to HTML. Dynamically changes as you add or remove slides.\r\ndocument.write(document.getElementsByClassName(&quot;hideable&quot;).length);\r\n&lt;\/script&gt;\r\n<\/pre>\n<p>Now, we need to go into the JS and make some modifications.<\/p>\n<p>On the <code>toggleSlide()<\/code> function, add this before the final closing bracket:<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nvar sn = document.getElementById(&quot;slideNumber&quot;);\r\nsn.innerHTML = (makeVisible + 1);\r\n<\/pre>\n<p>On <code>goToEdge()<\/code>, modify the <code>if ... else<\/code> clause as such:<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nif(!where) {\r\n    elements&#x5B;0].style.display = &quot;block&quot;;\r\n    sn.innerHTML = 1;\r\n} else {\r\n    elements&#x5B;elements.length-1].style.display = &quot;block&quot;;\r\n    sn.innerHTML = elements.length;\r\n}\r\n<\/pre>\n<p><!--\n\n\n\n<h2>Change speed of slideshow<\/h2>\n\n\nWith a simple number input form, you can let the user set his own speed for the slideshow.\n\nAdd this button within the form:\n\n[code lang=\"javascript\"]\n&lt;!-- NB: You can change the value attribute to another default value of your choice --&gt;\n&lt;label for=&quot;slideSpeed&quot;&gt;Change every&lt;\/label&gt;\n&lt;input type=&quot;number&quot; id=&quot;slideSpeed&quot; min=&quot;0&quot; value=&quot;3.5&quot; onchange=&quot;changeInterval(this)&quot; \/&gt;\n&lt;label for=&quot;slideSpeed&quot;&gt;seconds&lt;\/label&gt;\n[\/code]\n\nJavaScript:\n\n[code lang=\"javascript\"]\nfunction changeInterval(speedSetter) {\n    \/\/ make sure the user enters a number &gt; 0\n    if(isNaN(newSpeed) || newSpeed &lt; 0) {\n        alert(&quot;Not a valid number!&quot;);\n        speedSetter.value = &quot;3.5&quot;;\n    }\n    else {\n        interval = speedSetter.value * 1000; \/\/remember, interval is in milliseconds.\n    }\n}\n[\/code]\n\n--><\/p>\n<h1>Demo<\/h1>\n<p>You can see a working demo at <a href=\"http:\/\/g-liu.github.io\/slideshow\/\">http:\/\/g-liu.github.io\/slideshow\/<\/a>. I&#8217;ve set the timer to one second per slide to demonstrate better the automatic slide advancing.<\/p>\n<p>The source code can be <a href=\"https:\/\/github.com\/g-liu\/slideshow\/tree\/master\">downloaded on GitHub<\/a>.<\/p>\n<h1>Additional notes<\/h1>\n<p>If your slideshow must be created with <code>div<\/code>s (or similar), you can get rid of the <code>&lt;ul&gt;<\/code> tags and replace all the <code>&lt;li&gt;<\/code> with <code>&lt;div&gt;<\/code> or whatever tag you&#8217;re using.<\/p>\n<!-- AddThis Advanced Settings generic via filter on the_content --><!-- AddThis Share Buttons generic via filter on the_content --><!-- AddThis Related Posts generic via filter on the_content -->","protected":false},"excerpt":{"rendered":"<p>Slideshows and carousels can add a lot to your website. They can be used in headers, blog posts, image showcases and more. Today, we&#8217;ll learn how to create your own slideshow from scratch with Javascript and a little HTML.<!-- AddThis Advanced Settings generic via filter on wp_trim_excerpt --><!-- AddThis Share Buttons generic via filter on wp_trim_excerpt --><!-- AddThis Related Posts generic via filter on wp_trim_excerpt --><\/p>\n","protected":false},"author":2,"featured_media":5258,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"footnotes":"","jetpack_publicize_message":"#Tutorial: Basic carousel\/slideshow with JavaScript http:\/\/wp.me\/p2Zt3y-Pt #webdesign #javascript","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","enabled":false}}},"categories":[830],"tags":[],"jetpack_publicize_connections":[],"aioseo_notices":[],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"https:\/\/g-liu.com\/blog\/wp-content\/uploads\/2013\/08\/carousel.jpg","jetpack_shortlink":"https:\/\/wp.me\/p2Zt3y-Pt","_links":{"self":[{"href":"https:\/\/g-liu.com\/blog\/wp-json\/wp\/v2\/posts\/3191"}],"collection":[{"href":"https:\/\/g-liu.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/g-liu.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/g-liu.com\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/g-liu.com\/blog\/wp-json\/wp\/v2\/comments?post=3191"}],"version-history":[{"count":25,"href":"https:\/\/g-liu.com\/blog\/wp-json\/wp\/v2\/posts\/3191\/revisions"}],"predecessor-version":[{"id":5259,"href":"https:\/\/g-liu.com\/blog\/wp-json\/wp\/v2\/posts\/3191\/revisions\/5259"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/g-liu.com\/blog\/wp-json\/wp\/v2\/media\/5258"}],"wp:attachment":[{"href":"https:\/\/g-liu.com\/blog\/wp-json\/wp\/v2\/media?parent=3191"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/g-liu.com\/blog\/wp-json\/wp\/v2\/categories?post=3191"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/g-liu.com\/blog\/wp-json\/wp\/v2\/tags?post=3191"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}