Magento 2.0.7 – How to Call Owl Slider

javascriptmagento-2.0.7slidertheme

If we want to add Owl Slider in Magento 1.X then we follow the below steps.

  1. Copy owl.carousel.min.js and owl.carousel.js and paste into skin/frontend/pakage_name/theme_name/js
  2. Copy owl.carousel.css and paste into skin/frontend/pakage_name/theme_name/css
  3. Goto app/design/frontend/pakage_name/theme_name/layout/page.xml and call js and CSS

And we can use Owl Slider anywhere in Magento 1.X site.

So in Magento 2 how we can call Owl slider and it should be called everywhere in the site so I can use whenever I want.

For this problem, I have referred this link but it's not up to the mark and it's not working.

Right now I have placed Owl slider js in app/design/frontend/pakage_name/theme_name/Magento_Catalog/web/js but it's not working.

Any help would be appreciated.

Best Answer

You have to created one requirejs-config.js file inside your theme like,

First Add owlcarousel.js file inside,

app/design/frontend/pakage_name/theme_name/Magento_Catalog/web/js

Add your css inside,

app/design/frontend/pakage_name/theme_name/Magento_Catalog/web/css

call css inside your tempalte file using,

<link rel="stylesheet" type="text/css" href="<?php echo $block->getViewFileUrl('Magento_Catalog::css/owlcarousel.css')?>">

or call css inside a layout file (best practice), depending on your needs :

  • whole site : default.xml for example app/design/frontend/pakage_name/theme_name/Magento_Catalog/layout/default.xml
  • Home page : cms_index_index.xml
<page ...>
<head>
     <css src="Magento_Catalog::css/owlcarousel.css"/>
</head>
<body>...</body> </page>

Now create requirejs-config.js file

Magento_Catalog/requirejs-config.js

Define your slider,

var config = {
    paths: {            
            'owlcarousel': "Magento_Catalog/js/owlcarousel"
        },   
    shim: {
        'owlcarousel': {
            deps: ['jquery']
        }
    }
};

Now you can use owlcarousel under any phtml file,

<div id="owlslider" class="products list items product-items">
   <ul>
     <li>1</li>
     <li>2</li>
     <li>3</li>
     <li>4</li>
     <li>5</li>       
  </ul>
</div>
    <script>
    (function  () {
        require(["jquery","owlcarousel"],function($) {
            $(document).ready(function() {
                $("#owlslider").owlCarousel({
                    navigation : true, // Show next and prev buttons
                    autoPlay: false, //Set AutoPlay to 3 seconds 
                    items : 5
                });
            });
        });
    })();
    </script>

Remove pub/static folder content and run php bin/magento setup:static-content:deploy command.

Related Topic