jQuery Image Carousel

Free JavaScript & jQuery Tutorial

Delve into this comprehensive JavaScript and jQuery tutorial that covers topics like linking to plugin files, creating and customizing carousels, adding custom prev and next buttons, controlling visible items at various screen sizes, and lazy loading content.

This exercise is excerpted from Noble Desktop’s past JavaScript training materials. Noble Desktop now teaches JavaScript and the MERN Stack in our Full Stack Development Certificate. To learn current skills in web development, check out our coding bootcamps in NYC and live online.

Note: These materials are provided to give prospective students a sense of how we structure our class exercises and supplementary materials. During the course, you will get access to the accompanying class files, live instructor demonstrations, and hands-on instruction.

Topics covered in this JavaScript & jQuery tutorial:

Linking to the plugin files, Creating & customizing the carousel, Adding prev & next buttons, Adding custom prev & next buttons, Controlling how many items are visible at various screen sizes, Lazy loading content

Exercise Preview

carousel done

Full-Stack Web Development Certificate: Live & Hands-on, In NYC or Online, 0% Financing, 1-on-1 Mentoring, Free Retake, Job Prep. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

Exercise Overview

Carousels are one way to present a series of images and/or text for users to scroll through. The free Owl Carousel plugin makes creating these easy.

Linking to the Plugin Files

  1. Open your code editor if it isn’t already open.

  2. Close any files you may have open.

  3. For this exercise we’ll be working with the Carousel folder located in Desktop > Class Files > yourname-JavaScript jQuery Class. You may want to open that folder in your code editor if it allows you to (like Visual Studio Code does).

  4. Open index.html from the Carousel folder.

  5. To save you some time, we’ve already linked to jQuery and main.js for you, but you need to link to the Owl Carousel script. Near the bottom, add the bold link as show below:

    <script src="js/vendor/jquery-3.5.0.min.js"></script>
    <script src="js/vendor/owl-carousel/owl.carousel.min.js"></script>
    <script src="js/main.js"></script>
    </body>
    

    NOTE: We’ve included the Owl Carousel files with the class files, but to download future updates, view examples, and read documentation, you can visit owlcarousel2.github.io/OwlCarousel2

  6. The JS file will create the carousel functionality, but we also need some CSS to style it. Scroll up to the top of the code.

  7. After the link to normalize.css, add the following bold code:

       <link rel="stylesheet" href="css/normalize.css">
       <link rel="stylesheet" href="js/vendor/owl-carousel/assets/owl.carousel.css">
       <link rel="stylesheet" href="js/vendor/owl-carousel/assets/owl.theme.default.css">
       <link rel="stylesheet" href="css/main.css">
    </head>
    
  8. Save the file.

Creating & Customizing the Carousel

A carousel displays multiple items. Each item can have any content you like (images, text, etc.) but you want to wrap all the content for an item in a div tag. All of the item div tags should be wrapped in a parent div tag with a class of owl-carousel. Here’s a simple example of what we mean:

<div class="owl-carousel">
   <div> Your Content </div>
   <div> Your Content </div>
</div>
  1. We’ve already coded up lots of items to save you time. Find the div with a class of moreNews and look at all the divs inside it. Notice the following:

    • Each div contains an image and a heading.
    • The content in each div is wrapped in a link. In our example files, we have not built all the linked pages, but that won’t matter for building the carousel. (Just don’t bother clicking any of those links in a browser because you’d get a missing page error.)
  2. Preview index.html in a browser.

    Scroll down to the More News heading. Currently, all the items are large and you have to scroll down to see them all. This is the content for our carousel.

  3. Leave the page open in the browser so we can come back to it later.

  4. Switch back to your code editor.

  5. Any div that is used for an Owl Carousel must have an owl-carousel class, so it will get some styling (such as hiding the carousel to avoid a flash of unstyled content). Find the div with the moreNews class and add the bold class:

    <div class="moreNews owl-carousel">
    
  6. Save the file.

  7. Switch to the browser and reload index.html.

    Scroll down to the More News heading. Notice that the content is hidden! Don’t worry, once we get the carousel working it will come back!

  8. Switch back to your code editor.

  9. From the js folder open main.js.

  10. To initialize the Owl Carousel, add the following bold code:

    $(document).ready(function() {
    
       // Carousel
       $('.moreNews').owlCarousel();
    
    });
    
  11. Save the file.

  12. Switch to the browser and reload index.html.

    We have a working carousel! Try the following:

    • Drag directly on the carousel content (images or text) to move around. Not only does dragging work on mobile devices, it works on desktops too. Cool!
    • Resize the window and notice there will always be 3 items displayed, which get scaled to fit the content area. Soon we’ll see how to customize how many items are visible at various screen sizes.
    • Notice there are no previous or next buttons or any visible controls, which would be nice.
  13. Switch to index.html in your code editor.

  14. Find the moreNews div and add the bold class:

    <div class="moreNews owl-carousel owl-theme">
    

    NOTE: This indicates that we want to use the default theme, which we linked to with owl.theme.default.css.

  15. Save the file.

  16. Switch to the browser and reload index.html.

    • Gray dots should now be visible below the carousel.
    • Click the gray dot to switch sections.
  17. Let’s add some space between the carousel items using a built in setting for that. Switch to main.js in your code editor.

  18. Place your cursor in between the parentheses of owlCarousel() and add the following bold code. Don’t miss the curly braces {} on the opening and closing lines!

    $('.moreNews').owlCarousel({
       margin: 10
    });
    
  19. Save the file and preview index.html in a browser.

    Notice that there’s now a bit of white space between each carousel item.

Adding Prev & Next Buttons

  1. Let’s add next and previous buttons. Switch to main.js in your code editor.

  2. Place your cursor in between the parentheses of owlCarousel() and add the following bold code. Don’t miss the comma at the end of the previous line!

    $('.moreNews').owlCarousel({
       margin: 10,
       nav: true
    });
    
  3. Save the file and preview index.html in a browser. Notice the following:

    • Try out the tiny prev and next buttons below the carousel (above the gray dots).
    • Click the next arrow to see it moves the carousel one item per click. That requires people to click a lot to view the remaining items, and many won’t bother. We think it should advance to a whole new section of items (however many are currently displayed).
    • This was an easy way to add nav buttons, but our design calls for these buttons to be on top of the carousel, to the far right of the More News line. That means we’ll need to create custom buttons.
  4. Switch back to main.js in your code editor.

  5. Let’s make the carousel scroll through the items faster. Add the following option shown below in bold, and don’t miss the comma at the end of the previous line!

    $('.moreNews').owlCarousel({
       margin: 10,
       nav: true,
       slideBy: 3
    });
    
  6. Save the file.

  7. Switch to the browser and reload index.html.

    Try out the prev and next buttons again. This time they should move one whole group of items at a time, instead of one at a time. Much better!

Adding Custom Prev & Next Buttons

The default prev and next buttons are placed below the carousel, but our design calls for them to be above the images (and aligned to the right). For that we’ll need to define a custom nav.

  1. First we need to code up the buttons. Switch back to your code editor.

  2. To save you some typing, we’ve provided you with the code. From the snippets folder, open carousel-custom-nav.html.

  3. Select and copy all the code.

  4. Switch to index.html.

  5. Find the start of the moreNews div.

  6. Between that and the h2 above, paste the code. You should end up with:

    <h2>More News</h2>
    <div class="customNav">
       <button class="customPrev">Previous</button>
       <button class="customNext">Next</button>
    </div> 
    <div class="moreNews owl-carousel owl-theme">
    

    NOTE: These are standard HTML buttons that can be placed anywhere, which means you can style them however you like. Take note of the classes we have added. These are not special to Owl Carousel (we created them), but we’ll need to target them later in our JS code. We’ve also created CSS (in main.css) using the classes to make them match our page design.

  7. Notice that we’re also using button tags, instead of links (the a tag). Buttons can be nice when you don’t need an href, because the user isn’t going anywhere. While span or div tags could also work, they require us to add CSS to prevent text selection.
  8. Save the file.
  9. Switch to main.js.
  10. The first thing we need to do is remove the original prev/next buttons. Remove the nav: true, line so you end up with the following code:

    $('.moreNews').owlCarousel({
       margin: 10,
       slideBy: 3
    });
    
  11. To programmatically control this carousel, we need to be able to refer to it. Let’s store a reference to it in a variable by adding the following bold code:

    var moreNewsCarousel = $('.moreNews').owlCarousel({
    
  12. Now we have to look for when the next and previous buttons are clicked. Add the following bold code:

       var moreNewsCarousel = $(".moreNews").owlCarousel({
          margin: 10,
          slideBy: 3
       });
    
       $('.customNext').click(function(){
    
       });
       $('.customPrev').click(function(){
    
       });
    
    });
    
  13. Owl Carousel provides events for next and previous. We can use jQuery’s trigger() method to trigger those events. Add the following bold code to trigger the appropriate event on our carousel:

    $('.customNext').click(function(){
       moreNewsCarousel.trigger('next.owl.carousel');
    });
    $('.customPrev').click(function(){
       moreNewsCarousel.trigger('prev.owl.carousel');
    });
    
  14. Save the file.
  15. Switch to the browser and reload index.html.

    • To the far right of the More News heading you should now see nice looking Previous and Next buttons.
    • Click the Previous and Next buttons to see that they work!

Controlling How Many Items Are Visible at Various Screen Sizes

By default the carousel displays 3 items. We can customize how many items are displayed at specific screens sizes using a responsive option. We can use this to override the defaults and set exactly how many items are displayed at any window size.

  1. Switch back to main.js in your code editor.

  2. Add the responsive option as shown below in bold. Don’t miss the comma at the end of the previous line!

    var moreNewsCarousel = $('.moreNews').owlCarousel({
       margin: 10,
       responsive: {
          0: {
             items: 4
          }
       }
    });
    

    NOTE: This means that screens 0 pixels and wider should display 4 items.

  3. Save the file.

  4. Switch to the browser and reload index.html. You should now see 4 items at a time.

  5. Switch back to main.js in your code editor.

  6. Change the number of responsive items from 4 to 1, as shown below in bold:

    var moreNewsCarousel = $('.moreNews').owlCarousel({
       margin: 10,
       slideBy: 3,
       responsive: {
          0: {
             items: 1
          }
       }
    });
    
  7. Delete the slideBy line of code so you end up with the following:

    var moreNewsCarousel = $('.moreNews').owlCarousel({
       margin: 10,
       responsive: {
          0: {
             items: 1
          }
       }
    });
    
  8. Add the slideBy into the responsive section, so you end up with the following. Don’t miss the comma at the end of the previous line!

    var moreNewsCarousel = $('.moreNews').owlCarousel({
       margin: 10,
       responsive: {
          0: {
             items: 1,
             slideBy: 1
          }
       }
    });
    
  9. Add two more breakpoints for screens starting at 450px and 600px, as shown below in bold:

    var moreNewsCarousel = $('.moreNews').owlCarousel({
       margin: 10,
       responsive: {
          0: {
             items: 1,
             slideBy: 1
          },
          450: {
            items: 2,
            slideBy: 2
          },
          600: {
            items: 3,
            slideBy: 3
          }
       }
    });
    
  10. Save the file.

  11. Switch to the browser and reload index.html.

    Resize the browser window to see the carousel change the number of items displayed from 1 on small screens, to 2, and then 3 as you make the window wider.

    NOTE: When working on responsive sites that change the number of items displayed, be careful of your image sizes. Be sure they are made for the widest possible width, so they will only scale down and not up (which can pixelate them).

Optional Bonus: Lazy Loading Content

Images are typically the largest files in a webpage. They slow down page loading, especially on mobile devices. Currently, all the photos in our carousel are loaded, even if they are not visible! Owl Carousel has an option called lazy loading, which will only load the hidden images if the user clicks the next or previous button (or swipes, etc. to view additional items). If a user doesn’t interact with the carousel, the extra (hidden) images will never be loaded. Let’s see how to add lazy loading.

  1. Switch to main.js in your code editor.
  2. Add the following bold code to enable lazy loading:

    var moreNewsCarousel = $('.moreNews').owlCarousel({
       margin: 10,
       lazyLoad: true,
       responsive: {
    
  3. Save the file.

    There’s one more thing we must do. As long as the img tags in our HTML have a src attribute, those images will still be downloaded. We need to change this into something HTML won’t load, and then Owl Carousel will use JavaScript to load the images intelligently.

  4. Switch to index.html in your code editor.

  5. For every image in the moreNews div, you must change src into data-src and add a owl-lazy class. Below is an example of what the final code should look like, with the changes shown in bold. Make this same change to all eight images in the moreNews div.

    <img class="owl-lazy" data-src="img/duck.jpg" alt="Ducks. One has a raised leg.">
    

    TIP: If your code editor allows you to place multiple cursors, that would come in handy. For example, in Visual Studio Code you can hold Option (Mac) or Alt (Windows) and click to place multiple cursors. Another approach that works in Visual Studio Code is to highlight the first img src= and then hit Cmd–D (Mac) or Ctrl–D (Windows) to select the following ones (stop after it selects the last one). You can then use your Arrow keys to position the text cursor as needed and make the desired change.

  6. Save the file.

  7. Preview index.html in Chrome. (We’ll be using its DevTools.)

  8. Hit Cmd–Opt–J (Mac) or Ctrl–Shift–J (Windows) to bring up the Console.

  9. Click on the Sources tab.

  10. On the left, expand the img folder. If you don’t see the img folder, expand top, then go into file:// and expand the folder inside. Now you should see the img folder and can expand it.

  11. There should 4 or less .jpg files listed (ignore the .gif and .png files). 1–3 JPEGs (depending on your window size) are from our carousel, and the 4th JPEG is from our page’s header photo.

  12. Keeping the DevTools open, scroll down the page so you can see the carousel.

  13. While keeping an eye on the list of images, click the carousel’s Next button. Depending on how fast the images load, you may notice the spinning loader icon appears before the images are loaded.

  14. You should see that more images were added to the list! That proves they weren’t loaded until required. This way, users will enjoy a faster loading page.

    NOTE: If you want to refer to our final code example, go to Desktop > Class Files > yourname-JavaScript jQuery Class > Done-Files > Carousel.

How to Learn Coding

Master coding with hands-on training. Learning how to code in JavaScript, Python, and other popular languages can pave the way to a job in tech, such as web development, data science & analytics, or software engineering.

Yelp Facebook LinkedIn YouTube Twitter Instagram