How to add OWL Carousel slider in HTML

  8 months ago     Views:  2596  


Slider is important part in the homepage in commercial and business website. It creates impressive user experience and provides user latest updates in the websites set by the site admin. Creating slider by self needs time to make animated and responsive. So it is recommended to use direct plugin which makes slider easily and responsive. There are so many plugin available to create slider. One of the popular plugin is Owl Carousel.

OWL Carousel is simple jQuery plugin which lets you create beautiful responsive and touch enabled carousel slider. It is simple to use in any website. Owl has many animtion effects in the slider. Owl can be also customised by passing different options for that. Owl also handles custom events and callbacks.

In this article, we will use Owl Carousel slider in homepage of the website. Please go through step by step to add Owl Carousel slider in your website.

Installation

First download the package from the GitHub. THen include two css files in the <head> tag. 

<link rel="stylesheet" href="owlcarousel/owl.carousel.min.css">
<link rel="stylesheet" href="owlcarousel/owl.theme.default.min.css">

owl.carousel.min.css is the main file and it is required to include before any javascript files. owl.theme.default.min.css file is theme file for navigation controls like arrow, dot etc.

And then include bellow javascript file before closing </body> tag.

<script src="jquery.min.js"></script>
<script src="owlcarousel/owl.carousel.min.js"></script>

Note: If you don't want to manually download the package, then you can directly load Owl Carousel CDN files. Put the bellow lines instead of CSS and Javascript tags.

<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.0.0-beta.3/assets/owl.carousel.min.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.0.0-beta.3/assets/owl.theme.default.min.css">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.0.0-beta.3/owl.carousel.min.js"></script>

Now wrap all slider <div> or <img> in one container <div class="owl-carousel">. class owl-carousel is required to apply proper css styles. Also if you want to use default navigation controls, you must also include the owl-theme class in the same <div> tag.

<div class="owl-carousel owl-theme">
    <div>First lider</div>
    <div>Second lider</div>
    <div>Third lider</div>
    <div>Forth lider</div>
    <div>Fifth lider</div>
    <div>Sixth lider</div>
</div>

Now include the bellow javascript after all javascript to initialise the slider.

<script type="text/javascript">
    $(document).ready(function() {
        ('.owl-carousel').owlCarousel();
    });
</script>

Options

You can also pass options to change the behaviour. Here is the list of the options you can pass.

Name Type Default Description
items Number 3 The number of items you want to see on the screen
margin Number 0 margin-right(px) on item
loop Boolean false Infinite loop
center Boolean false Center item, even an odd number of items
mouseDrag Boolean true Can change the item with mouse drag
touchDrag Boolean true Can change the item with touch
pullDrag Boolean true Stage pull to edge
freeDrag Boolean false Item pull to edge
stagePadding Number 0 Padding left and right on stage
merge Boolean true Fit merged items if screen is smaller than items value
mergeFit Boolean true Fit merged items if screen is smaller than items value
autoWidth Boolean false Set non grid content. Try using width style on divs
startPosition Number/String 0 Start position or URL Hash string like '#id'
URLhashListener Boolean false Listen to url hash changes, data-hash on items is required
nav Boolean false Show next/prev buttons
rewind Boolean true Go backwards when the boundary has reached
navText Array ['next','prev'] HTML allowed
navElement String div DOM element type for a single directional navigation link
slideBy Number/String 1 Navigation slide by no. of page string can be set to slide by page
slideTransition String `` You can define the transition for the stage you want to use eg. linear
dots Boolean true Show dots navigation
dotsEach Number/Boolean false Show dots each no. of item
dotsData Boolean false Used by data-dot content
lazyLoad Boolean false Lazy load images. data-src and data-src-retina for highres. Also load images into background inline style if element is not img
lazyLoadEager Number 0 Eagerly pre-loads images to the right based on how many items you want to preload
autoplay Boolean false Autoplay
autoplayTimeout Number 5000 Autoplay interval timeout
autoplayHoverPause Boolean false Pause on mouse hover
smartSpeed Number 250 Speed Calculate, More info to come
fluidSpeed Boolean Number Speed Calculate, More info to come
autoplaySpeed Number/Boolean false autoplay speed
navSpeed Number/Boolean false Navigation speed
dotsSpeed Boolean Number/Boolean Pagination speed
dragEndSpeed Number/Boolean false Drag end speed
callbacks Boolean true Enable callback events
responsive Object empty object Object containing responsive options, Can be set to false to remove responsive capabilities
responsiveRefreshRate Number 200 Responsive refresh rate
responsiveBaseElement DOM element window Set on any DOM element, If you care about non responsive browser then use it on main wrapper
video Boolean false Enable fetching YouTube/Vimeo/Vzaar videos
videoHeight Number/Boolean false Set height for videos
videoWidth Number/Boolean false Set width for videos
animateOut String/Boolean false Class for CSS3 animation out
animateIn String/Boolean false Class for CSS3 animation in
fallbackEasing String swing Easing for CSS2 $.animate
info Function false Callback to retrieve basic information. Info function second parameter is Owl DOM object reference
nestedItemSelector String/Class false Use it if owl items are deep nested inside some generated content. Don't use dot before class name
itemElement String div DOM element type for owl-item
stageElement String div DOM element type for owl-stage
navContainer String/Class/ID/Boolean false Set your own container for nav
dotsContainer String/Class/ID/Boolean false Set your own container for nav
checkVisible Boolean true If you know the carousel will always be visible you can set `checkVisibility` to `false` to prevent the expensive browser layout forced reflow the $element.is(':visible') does

Classes

This is an example of how HTML is rendered.

<div class="owl-carousel owl-theme owl-loaded">
    <div class="owl-stage-outer">
        <div class="owl-stage">
            <div class="owl-item">...</div>
            <div class="owl-item">...</div>
            <div class="owl-item">...</div>
        </div>
    </div>
    <div class="owl-nav">
        <div class="owl-prev">prev</div>
        <div class="owl-next">next</div>
    </div>
    <div class="owl-dots">
        <div class="owl-dot active"><span></span></div>
        <div class="owl-dot"><span></span></div>
        <div class="owl-dot"><span></span></div>
    </div>
</div>

You can also changes the class name of the items with following options.

Name Type Default Description
refreshClass String owl-refresh Class during refresh
loadingClass String owl-loading Class during load
loadedClass String owl-loaded Class after load
rtlClass String owl-rtl Class for right to left mode
dragClass String owl-drag Class for mouse drag mode
grabClass String owl-grab Class during mouse drag
stageClass String owl-stage Stage class
stageOuterClass String owl-stage-outer Stage outer class
navContainerClass String owl-nav Navigation container class
navClass Array ['owl-prev','owl-next'] Navigation buttons classes
dotClass String owl-dot Dot Class
dotsClass String owl-dots Dots container class
autoHeightClass String owl-height Auto height class
responsiveClass String|Boolean false Optional helper class. Add '-' class to main element. Can be used to stylize content on given breakpoint

Events

Owl Carousel is also supports event calls on certain movements. With that you can change and modify with certain events.
You can listen for events.

var owl = $('.owl-carousel');
owl.owlCarousel();
// Listen to owl events:
owl.on('changed.owl.carousel', function(event) {
    // your code goes here...
})

You can also trigger events and handle the Owl carousel.

var owl = $('.owl-carousel');
owl.owlCarousel();
// Go to the next item
$('.customNextBtn').click(function() {
    owl.trigger('next.owl.carousel');
})
// Go to the previous item
$('.customPrevBtn').click(function() {
    // With optional speed parameter
    // Parameters has to be in square bracket '[]'
    owl.trigger('prev.owl.carousel', [300]);
});

Callbacks

You can also add a callback to the options of Owl Carousel.

$('.owl-carousel').owlCarousel({
    onDragged: callbackFunction
});
function callbackFunction(event) {
    // your code goes here...
}

Data

Each event passes very useful information within the event object. Based on the example above:

function callback(event) {
    // Provided by the core
    var element   = event.target;         // DOM element, in this example .owl-carousel
    var name      = event.type;           // Name of the event, in this example dragged
    var namespace = event.namespace;      // Namespace of the event, in this example owl.carousel
    var items     = event.item.count;     // Number of items
    var item      = event.item.index;     // Position of the current item
    // Provided by the navigation plugin
    var pages     = event.page.count;     // Number of pages
    var page      = event.page.index;     // Position of the current page
    var size      = event.page.size;      // Number of items per page
}

Carousel

Name Type Callback Parameter Description
initialize.owl.carousel attachable onInitialize   When the plugin initializes
initialized.owl.carousel attachable onInitialized   When the plugin has initialized
resize.owl.carousel attachable onResize   When the plugin gets resized
resized.owl.carousel attachable onResized   When the plugin has resized
refresh.owl.carousel attachable, cancelable, triggerable onRefresh [event, speed] When the internal state of the plugin needs update
refreshed.owl.carousel attachable onRefreshed   When the internal state of the plugin has updated
drag.owl.carousel attachable onDrag   When the dragging of an item is started
dragged.owl.carousel attachable onDragged   When the dragging of an item has finished
translate.owl.carousel attachable onTranslate   When the translation of the stage starts
translated.owl.carousel attachable onTranslated   When the translation of the stage has finished
change.owl.carousel attachable onChange property When a property is going to change its value
changed.owl.carousel attachable onChanged property When a property has changed its value
next.owl.carousel triggerable   [speed] Goes to next item
prev.owl.carousel triggerable   [speed] Goes to previous item
to.owl.carousel triggerable   [position, speed] Goes to position
destroy.owl.carousel triggerable     Destroys carousel
replace.owl.carousel triggerable   data Removes current content and add a new one passed in the parameter
add.owl.carousel triggerable   [data, position] Adds a new item on a given position
remove.owl.carousel triggerable   position Removes an item from a given position

Lazy

Name Type Callback Description
load.owl.lazy attachable onLoadLazy When lazy image loads
loaded.owl.lazy attachable onLoadedLazy When lazy image has loaded

Autoplay

Name Type Parameter Description
play.owl.autoplay triggerable [timeout, speed] Runs autoplay
stop.owl.autoplay triggerable   Stops autoplay

Video

Name Type Callback Description
stop.owl.video attachable onStopVideo When video has unloaded
play.owl.video attachable onPlayVideo When video has loaded.

This way you can add beautiful and simple slider.


Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

OR

No Comments