Tips for implementing owl carousel in Nuxt.REACT_UNITS_CODIFY

Is there a way to make the script function on every page without the need for these pages to be reloaded? I have the Owl Carousel script in my static folder, and I have already included it in nuxt.config.js as shown below:

head: {
    title: 'title',
    htmlAttrs: {
        lang: 'en'
    },
    meta: [
        { charset: 'utf-8' },
        { name: 'viewport', content: 'width=device-width, initial-scale=1' },
        { hid: 'description', name: 'description', content: '' },
        { name: 'format-detection', content: 'telephone=no' }
    ],
    link: [
        { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ],
    script: [{
            src: process.env.BASE_URL_ROOT + "/jquery-3.3.1.min.js",
            type: "text/javascript"
        },
        {
            src: process.env.BASE_URL_ROOT + "/owl.carousel.min.js",
            type: "text/javascript"
        },
        {
            src: process.env.BASE_URL_ROOT + "/main-script.js",
            type: "text/javascript"
        }
    ]
},

Here is the script from my main-script.js file:

$(document).ready(function() {

$('.owl-menu').owlCarousel({
    loop: true,
    responsiveClass: true,
    center: true,
    items: 6,
    nav: true,
    dots: false,
    autoWidth: true,
    responsive: {
        600: {
            items: 6,
            nav: true,
            autoWidth: true,
            center: true,
            loop: true
        },
    }
})

$('.owl-video').owlCarousel({
    loop: true,
    center: true,
    items: 3,
    margin: 10,
    nav: true,
    dots: true,
    responsive: {
        600: {
            items: 3,
            margin: 12,
        },
    },
    navContainer: "#nav-conte",
    navText: [
        '<i class="far fa-arrow-alt-circle-left" aria-hidden="true" style="color: rgba(0,0,0,0.67843);"></i>',
        '<i class="far fa-arrow-alt-circle-right" aria-hidden="true" style="color: rgba(0,0,0,0.67843);"></i>'
    ]
})
})

The carousel works fine on the page if the page is loaded directly, but when navigating through nuxt, the carousel script stops working.


I found a solution by using MutationObserver to monitor DOM changes in my main-script.js:

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

var observer = new MutationObserver(function(mutations, observer) {
    // my owl carousel script
});

observer.observe(document, {
    subtree: true,
    attributes: true
});

Answer №1

In this example, the code is utilizing jQuery for DOM manipulation. However, modern front-end frameworks prefer managing the DOM in a different way, relying more on state or refs rather than querySelector.

I would suggest exploring Vue packages to achieve similar features instead of attempting to adapt this jQuery code. Using a Vue package can offer a lighter bundle size, easier integration with your Nuxt app, and avoid any potentially unreliable or messy behavior.

You can find a variety of Carousel options in this list: https://github.com/vuejs/awesome-vue#carousel

Personally, I recommend using vue-awesome-swiper, despite being slightly heavier, it offers comprehensive functionality.


Considering you are already using Vue in your project, having jQuery alongside might not be necessary. If you still wish to integrate jQuery into your Nuxt app cleanly, you can refer to my other answer here:


An additional note, even owl carousel is deprecating itself, as evidenced by this screenshot: https://i.stack.imgur.com/ZRZ9O.png

Answer №2

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

var observer = new MutationObserver(function(mutations, observer) {
    // custom carousel script
    
   $('.owl-menu').owlCarousel({
    loop: true,
    responsiveClass: true,
    center: true,
    items: 6,
    nav: true,
    dots: false,
    autoWidth: true,
    responsive: {
        600: {
            items: 6,
            nav: true,
            autoWidth: true,
            center: true,
            loop: true
        },
    }
})

$('.owl-video').owlCarousel({
    loop: true,
    center: true,
    items: 3,
    margin: 10,
    nav: true,
    dots: true,
    responsive: {
        600: {
            items: 3,
            margin: 12,
        },
    },
    navContainer: "#nav-conte",
    navText: [
        '<i class="far fa-arrow-alt-circle-left" aria-hidden="true" style="color: rgba(0,0,0,0.67843);"></i>',
        '<i class="far fa-arrow-alt-circle-right" aria-hidden="true" style="color: rgba(0,0,0,0.67843);"></i>'
    ]
})

});

observer.observe(document, {
    subtree: true,
    attributes: true
});

I found this solution effective. You might want to give it a try. Visit the link for more details

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting 404 Error When Using Axios Put Request in Vue.js

I'm trying to update the status of an order using Axios and the Woocommerce REST API, but I keep getting a 404 error. Here's my first attempt: axios.put('https://staging/wp-json/wc/v3/orders/1977?consumer_key=123&consumer_secret=456&apos ...

Enhance the CSS styling for the React-Calendly integration in a React project

I am trying to customize the CSS of an Inline Widget called React Calendly. I have attempted to use React Styled Component Wrapper, Frame React Component, and DOM javascript but unfortunately, the design changes are not reflecting as desired. Specifically, ...

Using Typescript to typecast in D3.js

Utilizing the D3 graph example available here. I've defined my data object as shown below: interface ID3Data { age: string, population: number } const data: ID3Data[] = [ { age: "<5", population: 2704659 }, { age: "5-13", population: 4499 ...

Maximizing jQuery DataTables performance with single column filtering options and a vast amount of data rows

My current project involves a table with unique column select drop-downs provided by an amazing jQuery plug-in. The performance is excellent with about 1000 rows. However, the client just informed me that the data could increase to 40000 rows within a mont ...

"Enhance user experience with jQuery's text expansion and collapse

Figuring out how to collapse and expand text with a button click has been challenging for me. I managed to make the text collapse when the button is clicked, but now I also need it to expand back again. The goal is to have the text initially hidden, then e ...

Vertically animating an image using jQuery

I have been experimenting with trying to make an image appear as if it is floating by using jQuery to animate it vertically. After some research, I stumbled upon this thread: Animating a div up and down repeatedly which seems to have the solution I need. H ...

What is causing this code to break when using ajax's `data` parameter?

I'm relatively new to JavaScript, and I've been working on some code that seems to be properly formatted. However, whenever I add the data elements, it breaks the code. I've checked the jQuery documentation and as far as I can tell, I'm ...

Create an array mapping of locations and convert each location to its corresponding language

With Next.js, I have successfully retrieved the current locale and all available locales for a language selection menu: const {currentLocale, availableLocales} = useContext(LangContext); // currentLocale = "en-US" // availableLocales = ["en- ...

Is there a way to detect when the browser's back button is clicked?

As I work on supporting an e-commerce app that deals with creating and submitting orders, a user recently discovered a loophole wherein they could trigger an error condition by quickly pressing the back button after submitting their order. To address this ...

Avoiding code execution by injections in Javascript/Jquery

Currently, I'm fetching JSON data for a .getJSON function in Jquery. To ensure the data's security, I am considering using .text (I believe this is the correct approach). The JSON has been successfully validated. Below is the script that I am cu ...

What could be the reason why the AngularJS form is set to read-only

Explaining the setup of my app in HTML: <div ng-app="md-app"> <div id="general"> <ng-include src="template1" ng-controller="GeneralCtrl"></ng-include> </div> </div> The JavaScript function to fetch a pe ...

Utilizing a promise instead of making a jQuery ajax request

A scenario I am facing involves a function that is set to execute jquery.ajax and return it as a promise for future processing. However, in certain cases, the function possesses enough information to proceed synchronously without triggering the ajax call. ...

What should we name this particular style of navigation tab menu?

What is the name of this tab menu that includes options for next and previous buttons? Additionally, is there a material-ui component available for it? ...

Is it possible to merge upload file and text input code using AJAX?

For my form submissions using jQuery and Ajax, I'm trying to figure out how to send both data and files together. Currently, I have the following code: $("#save-sm").bind("click", function(event) { var url = "sm.input.php"; var v_name_sm = $(&ap ...

The v-html command displays unprocessed HTML code on the webpage

This is a visual representation of my component: <template> <div v-html="someHtml"></div> </template> <script> export default { name: "test", props: { someHtml: String, }, } </script&g ...

Tips for running code extracted from a JSON payload

I have a JSON string that contains HTML and JavaScript code. I want to display this code on a page in my React app, but instead of just showing it as a string, I want the HTML and JavaScript to be executed as if it were hard coded. Currently, the code is ...

Is there a way to retrieve the value from an input box?

<td class="stockQuantity"> <input class="form-control" id="Cart1" name="qty_req" required="required" type="text" value=""><br> <button type="button" o ...

Extracting the name from a JSON key/value pair and then adding it to a TextField

Here is a sample JSON data: { "Id": 1, "Title": "Information on Jane Smith", "Comments": "Additional details here", "UpdatedBy": "Jane Smith", "UpdateDate": "May ...

Tips for injecting scripts into the head tag after an Angular component has been loaded

Currently, I am facing an issue with a script tag containing a Skype web control CDN. The script has been placed in the head section of my index.html file, but it is being called before the component that needs it has finished loading. Does anyone have a ...

How can I make the burger icon responsive and centered in my navbar?

Struggling to center the burger icon in the navbar has been a bit of a challenge for me. Although it appears centered on small mobile devices, the icon shifts to the upper side on larger screens like tablets, losing its centered position. I am seeking advi ...