kawnah
kawnah

Reputation: 3414

.owlCarousel() is not a function

I'm aware of the already hundreds of questions that exist on this topic, but after close review of dozens of questions they're all including script tags in the wrong order. Mine is correct.

As per the documentation:

<link rel="stylesheet" href="/vendor/owl.carousel.min.css">
<link rel="stylesheet" href="/stylesheets/styles.css">
...
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/owl.carousel.min.js"></script>
<script type="text/javascript" src="/javascripts/scripts.min.js"></script>
...
<div class="homepage-slider">
  ...
</div>

In scripts.min.js I have my init so:

$(function() {
  $(".homepage-slider").owlCarousel();
});

This order throws:

r(...).owlCarousel is not a function

Everything seems to be in the right order. Is there some sort of jQuery quirk that is breaking it? I did try:

$.noConflict();
$(function() {
  $(".homepage-slider").owlCarousel();
});

But it did not resolve the issue.

EXTRA DETAILS:

I'm bundling my JS into a single minified file. I'm doing it like this:

...
import {homepageCarousel} from './modules/homepage-carousel';
...

There are 8 import statements (they are all snippets of jQuery code). The carousel import is second from the top.

Upvotes: 1

Views: 12030

Answers (2)

kawnah
kawnah

Reputation: 3414

Ok:

I was bundling jquery directly into my scripts.min.js file from the NPM package.

In every import, I had:

var $ = require('jquery');

I deleted that line, and directly included jQuery from the CDN:

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

And it fixed my issue.

Upvotes: 0

Stuart
Stuart

Reputation: 6780

If you are including your scripts.min.js in the head of the page, then there's a great chance that the DOM element doesn't even exist yet.

Move your <script type="text/javascript" src="/javascripts/scripts.min.js"></script> down to just before the closing </body> tag, and you might fins it works.

This way, the DOM element will already exist, and so owlCarousel will be able to find that element and do its thing.

Upvotes: 3

Related Questions