In the Swiper function of JavaScript within a Django template, the occurrence of duplicate elements (products) is being generated

Experimenting with displaying products in a Django template, I decided to utilize the Swiper js class. This allowed me to showcase the products within a div, complete with navigation buttons for scrolling horizontally.

However, when testing this setup with one product inserted into my Product model from the admin panel, I encountered an issue. Every time I attempted to navigate using the "prev" or "next" buttons, or even clicked with the cursor, duplicates of the single element appeared.

Inspiration for this implementation came from the following link: here.

Check out the image below showcasing my product in the Swiper div:

https://i.sstatic.net/Ohj42.png

Here is the HTML CODE snippet from the Django template:

<!-- Products  -->
<div class="container my-4 bg-white border border-light-dark flex">

<div class="lunchbox">

  <!-- Slider main container -->
  <div id="swiper1" class="swiper-container"> 

      <!-- Additional required wrapper -->
      <div class="swiper-wrapper">

          <!-- Slides -->
          {% for product in products %}
              <div class="swiper-slide">
                <div class="product">
                  <img class="photograph" src="/media/product_images/{{product.product_code}}.jpg" alt="">
                  <h2 class="product__name">{{product.name}}</h2>
                  <p class="product__description"><span class="font-weight-normal">৳</span>{{product.product_price}}</p>
                </div>
              </div>
          {% endfor %}

      </div>

      <!-- Pagination -->
      <div class="swiper-pagination"></div>

  </div>

  <!-- Navigation buttons -->
  <div id="js-prev1" class="swiper-button-prev btn-edit" style="top:35%;"></div>
  <div id="js-next1" class="swiper-button-next btn-edit" style="top:35%;"></div>

</div>
</div>

And here is the JavaScript CODE snippet:

(function() {

  'use strict';

  const mySwiper = new Swiper ('#swiper1', {

    loop: true, 

    slidesPerView: 'auto',
    centeredSlides: true,

    a11y: true,
    keyboardControl: true,
    grabCursor: true,

    // Pagination
    pagination: '.swiper-pagination',
    paginationClickable: true,

    // Navigation arrows
    navigation: {
        nextEl: '.swiper-button-prev',
        prevEl: '.swiper-button-next',
      },
    observer: true,
    observeParents: true,

  });

})(); /* Immediately Invoked Function Expression (IIFE) - End */

Any assistance on resolving this issue would be greatly appreciated.

Answer №1

Check out the PHP code snippet below for a glimpse:

<div class="swiper-slide" data-hash="slide<?php echo $foorloop->current_post_index; ?>" >

In this section,

data-hash="slide<?php echo $objTestos->current_post; ?>"
is basically generating data-hash="slide1", data-hash="slide2", and so on.

Additionally, here's the JS part:

var swiper = new Swiper('.swiper-container', {
    hashNavigation: {
        watchState: true,
    },
    pagination: {
        el: '.swiper-pagination',
        clickable: true,
    },
});

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

Creating an NPM Module: Importing your own package as a dependency

Currently, I am in the process of developing a new NPM package. The repository includes an examples directory containing some JavaScript code that is compiled and served locally (or potentially through github.io). The configuration is reminiscent of the s ...

Revamping CSS for a Responsive Wordpress Tesseract Theme

I'm currently in the process of developing a website using the Tesseract theme at thevandreasproject.com. However, I have encountered an issue with responsiveness when integrating the SiteOrigins PageBuilder plugin. The compatibility between PageBuild ...

The Ajax validation form mistakenly redirects the echoes to a different page instead of the intended page for displaying the output

I am currently working on creating an ajax-form to validate the client-side server of my sign-up form. My goal is to have error messages displayed on the same page where they are triggered, without loading a separate page. Below is the code from my (sign ...

What is the best way to make one element match the height of another element?

I am facing an issue with the height of my two columns as I have another column separating them. The challenge is to make the left and right columns extend in height based on the content added to the center column. One important point to consider is that ...

Potential issue with Jhipster: loading of data could be experiencing delays

I've encountered an issue with getting my chart to display properly. I am working on creating a chart using ng2-charts, where I retrieve data from a service and then display it on the chart. The problem arises when the data is not correctly displayed ...

Angular2 material dropdown menu

Currently, I am studying angular2 with its material design. One of the modules I am using is md-select for material and here is a snippet of my code: <md-select> <md-option value="1">1</md-option> <md-option value="2">2< ...

Custom headers in XmlHttpRequest: Access control check failed for preflight response

Encountering an issue with an ajax GET Request on REST Server. Test results and details provided below. There are two methods in the REST Server: 1) resource_new_get (returns json data without custom header) 2) resource_api_new_get (also returns json d ...

The CORS middleware seems to be ineffective when used in the context of Node.js

I have set up my REST API on a Raspberry Pi server and connected it to the public using localtunnel. I am trying to access this API from a localhost Node.js application. The Node application is running on Express and includes some static JS files. However, ...

When moving to a different page, PHP seems to have a problem keeping the session values in place

As I work on my PHP application, I encounter an issue with maintaining session values. In this scenario, I have two files: 'sidebar.php' and 'home.php'. The sidebar is included on the home page, and it contains login controls. Logging i ...

Looking to adjust the background-image size of a table cell (td) upon clicking a specific

I have a website where I would like to display logos of different games with links attached to them. I have managed to adjust the size of the image on hover, but now I am looking for a way to keep the size bigger after clicking on the link. Is there a simp ...

Can anyone lend a hand with styling this menu without relying on margins in CSS?

I've been working on a website and I've noticed a significant lag in Internet Explorer when hovering over the menus. It appears that Cufon is contributing to this issue, especially when applying height, width, margins, or paddings to the li:hover ...

Guide to sending properties to reducer in React with Redux

I've been grappling with the complexities of react-redux for hours. I'm aiming to display an <Alert /> to the user when the value of isVisible is true. However, I'm still struggling to grasp the architecture of redux. Despite my effort ...

Issue with Navbar Collapse Toggle not deactivating (following transition from bootstrap v4 beta to v4 alpha 6)

Recently, I encountered an issue with my navbar after switching to v4 alpha 6 in order to utilize the responsive utilities that this version offered. If you visit the following page: , you will see what I mean. Prior to upgrading to v4 alpha 6, all menu ...

Retrieving data with model.fetch in Backbone.js when the server response is null

In my app, we utilize model.fetch() to retrieve JSON from the server. The render function is triggered when the model undergoes a change and looks like this: if(_.isUndefined(this.model.get("id_number"))){ this.template = initialTemplate; } else if(th ...

Does anyone know of a tool that allows you to save HTML as a standalone page?

Looking for a solution to easily send standalone .html files with no external dependencies to clients on a regular basis. The original pages are built using node.js and express, and feature libraries like High Charts. Up until now, I have been manually pre ...

Exploring the functionality of the `super()` method in TypeScript

I'm trying to enhance the standard JavaScript Error class by adding another property called code, but for some reason, TypeScript is not allowing me to do so. Here is the code snippet: export class HttpError extends Error { public message: string ...

Tips for enabling the auto complete feature in your settings

I have multiple websites similar to Facebook where users input an email address and by clicking a button, a list of email addresses is displayed. Could someone please explain how this functionality is created? Can it be accomplished using only HTML or are ...

What is the process for dynamically checking in a node in jstree?

I am utilizing Jstree from https://github.com/vakata/jstree. I have successfully loaded the tree structure, and now I want to bind checked checkboxes from an array of data. By default, the nodes have unique ids. I will check the id of each node in the arra ...

Bidirectional Data Binding Using Meteor and React

When using Meteor, the getMeteorData() method is preferred over getInitialState(). But how can we achieve binding, especially with regards to a user's surname in their profile? ... getMeteorData() { return { u = Meteor.user() } }, componentRen ...

How do the JavaScript thread and the Silverlight UI thread interact with each other?

While JavaScript operates on a single thread, Silverlight does not follow the same restrictions. However, when it comes to the interaction between JavaScript and Silverlight, it is crucial that communication occurs on the Silverlight UI thread. The relati ...