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

Communication between AngularJS directives and controllers occur when a function is called upon a change

I have developed a unique custom directive which is defined as: <div class="col-md-6"> {{templateMapping[colProp].SheetPointer}} <select class="form-control" ng-model="selectedColumn" ng-change="changeMapping()" ng ...

Why can my JavaScript server code read "2011" but not "20,11" when both are formatted as strings?

Currently, I am trying to establish a connection between Storm and JavaScript through redis. While the redis aspect of the connection is functioning correctly, I am encountering an issue when attempting to publish tuples (essentially Strings). Even though ...

Sending JavaScript objects from React.js to Node.js

I send the object to the backend (Node js) when making an API call, but I am logging the objects for verification. Initially, I used POSTMAN to check and it worked perfectly. However, when attempting to pass an object in the frontend (Reactjs), it appear ...

Encountering issues when trying to build a Nestjs app with node-crc (rust cargo) in Docker

I am encountering an issue with building my Nest.js app using Docker due to a dependency called "node-crc" version "2.0.13" that fails during the docker build process. Here is my Dockerfile: FROM node:17.3.1-alpine RUN curl https://sh.rustup.rs -sSf | sh ...

The checkbox is currently selected, however, I would like it to be dese

I am facing an issue where I cannot figure out why the password checkbox always turns to checked even when it is supposed to stay unchecked. No matter what, it doesn't behave as I intended and I am struggling to explain this behavior... <template&g ...

Sizing labels for responsive bar charts with chart.js

I'm encountering a problem with my bar chart created using chart.js - the responsive feature works well for some elements but not all. Specifically, the labels on my bar chart do not resize along with the window, resulting in a strange look at smaller ...

What could be causing my unique Angular custom date filter to output nonsensical results?

This is the Jade markup: .col-md-9 | {{client.person.date_of_birth | date:'standardDate'}} Here's the filter in Angular: .filter('standardDate', function($filter){ var dateFilter = $filter('date'); ...

retrieve a reply from a PHP script and incorporate it into JavaScript following an AJAX request

I've been working with an ajax call and everything seems to be running smoothly thanks to this script: $(document).ready(function() { $('.sortable').sortable({ stop: function(event, ui) { $(ui.item).effect("highlight"); ...

Move the focus to the previous input field by removing the key

I have created a phone number input with 10 fields that automatically skip to the next field when you fill in each number. However, I would like to be able to go back to the previous field if I make a mistake and need to delete a digit. How can I achieve ...

Testing a Nuxt application using Jest and Sinon: A comprehensive guide

Currently, I am in the process of adding a unit test to a Nuxt application using Jest and Sinon for stubbing functions. My main goal is to stub Axios get calls. Here's how I create an instance: return shallowMount(BarChart, { stubs: { highchart ...

Retrieve the value of an AngularJS expression and display it in a window alert using AngularJS

Hey there, I am in the process of trying to display the value of an expression using AngularJs As a beginner in angular, I am working on figuring out how to retrieve the value of the expression either with an alert or in the console. I'm utilizing A ...

unable to retrieve value from JSON object

It appears that I'm having trouble accessing my object variables, most likely due to a silly mistake on my part. When I console.log my array of objects (pResult), they all look very similar with the first object expanded: [Object, Object, Object, Obj ...

Node.js is being utilized to send an abundance of requests to the server

Here is my setup: var tempServer=require("./myHttp"); tempServer.startServer(8008,{'/fun1':fun1 , '/fun2': fun2 , '/fun3':fun3 , '/fun4':fun4},"www"); This code creates a server on localhost:8008. If I enter th ...

Breaking down the jQuery datepicker into individual fields for Day, Month, and Year

Currently, I am using the Contact Form 7 plugin on my Wordpress website, which I believe uses the jQuery datepicker for its date fields (please correct me if I'm mistaken). My query is about splitting the user input box into three separate elements ( ...

Vue JS - Issue with rendering <tr> and <td> elements in table component

I have created a custom table component using vue.js: <template> <div> <table class="table border"> <thead> <tr> <td>header 1&l ...

What's the best way to arrange a computed property based on a particular value?

Having reviewed the [documentation for Vue.JS][1], I came across a method that sorts by all even numbers as an example. While this is useful, I am trying to sort an array based on a specific name value within the array itself - which involves making a comp ...

What's the best way to adjust text color to black or white for maximum contrast when the background changes?

Currently, I am attempting to replicate the email element found on this website: .custom-blend-mode { mix-blend-mode: difference; } Although I have managed to make it work, it results in a change to the opposite color. Ideally, I would like it to remai ...

JavaScript AJAX Event Listener

Currently seeking a way to intercept ajax events in JavaScript before any Ajax method is triggered. While there is an ajaxListener in JQuery that could work if all the ajax requests were from JQuery, unfortunately, they are not. So the question remains: ho ...

Using ng-repeat and selectize in AngularJS to populate a multi-select drop-down with values and set selected values

In this instance, I was able to achieve pure HTML select multiple functionality by using this example (JS Bin of pure html select tag). However, instead of sticking to just the pure HTML approach, I opted to use the Selectize plugin. The confusion arose w ...

Is there a method to prevent data loss on page refresh by persisting data stored in a database?

I'm currently developing a commenting feature for a blog using the latest version of NextJs. The text input collects data and sends it to the 'Vercel' hosted database. I am able to successfully fetch the data from the frontend as expected. ...