Attempting to create a single function that can be utilized with numerous divs that share the same class in jQuery

Currently, I am working on creating a basic jquery gallery viewer.

In my code, I have the following structure:

<div class="photoset">
  <img />
  <img />
</div>

<div class="photoset">
  <img />
  <img />
  <img />
</div>

The objective is to show only one image at a time and allow users to click on the right half of the current image to switch to the next one.

This is what I've implemented so far:

$(document).ready(function () {

    var counter = 0,
    $items = $('.photoset figure'), 
    numItems = $items.length;

    var showCurrent = function () {
        var itemToShow = Math.abs(counter % numItems); 
        $items.removeClass('show');
        $items.eq(itemToShow).addClass('show');
    };

    $("div").click(function (e) {
        var pWidth = $(this).innerWidth();
        var pOffset = $(this).offset();
        var x = e.pageX - pOffset.left;
        if (pWidth / 2 > x) {
            counter--;
            showCurrent();
        }
        else {
            counter++;
            showCurrent();
        }
    });

});

Although the click functionality works, all the divs are affected by it and there seems to be an issue with how the counter is functioning.

Here is the part of the code responsible for generating the gallery:

@foreach (var item in Model)
{
    <br />
    @Html.DisplayFor(modelitem => item.GalleryName)
    <br />
    <div class="photoset">

        @{ var images = item.ImagePaths;}
        @for (var i = 0; i < Enumerable.Count(images); i++)
        {
        <br />
        <figure class="@(i == 0 ? "show" : "" ) ">
            <img src="~/images/@Html.DisplayFor(modelImage => images[i].FileName)" alt="" height="300" width="500" />
        </figure>
        <br />
        }
    </div>

I apologize if the solution appears obvious, as I am new to jQuery/JavaScript myself.

Answer №1

Give this a shot:

Your HTML:

<div class="gallery">
  <img src="http://inspirebee.com/wp-content/uploads/2013/04/animal-fashion-parade.jpg" />
  <img src="http://www.fubiz.net/wp-content/uploads/2013/03/Fashion-Zoo-Animals18.jpg" />
  <img src="http://inspirebee.com/wp-content/uploads/2013/04/animal-in-fashion.jpg" />
  <img src="http://www.fubiz.net/wp-content/uploads/2013/03/Fashion-Zoo-Animals20.jpg" />
</div>

<div class="gallery">
  <img src="http://www.fubiz.net/wp-content/uploads/2013/03/Fashion-Zoo-Animals26.jpeg" />
  <img src="http://www.fubiz.net/wp-content/uploads/2013/03/Fashion-Zoo-Animals14.jpg" />
  <img src="http://inspirebee.com/wp-content/uploads/2013/04/animal-fashion.jpg" />
  <img src="https://framboisemood.files.wordpress.com/2013/04/fashion-zoo-animals13.jpg" />
  <img src="http://www.fubiz.net/wp-content/uploads/2013/03/Fashion-Zoo-Animals9.jpg" />
</div>

Your CSS:

.gallery > img:not(:first-child) {
  display: none;
}

Your JavaScript:

$(document).ready(function() {
    $('.gallery').each(function(){
        $(this).data('counter', 0);
    });

    var showImage = function(gallery) {
        $items = gallery.find('img');
        var counter = gallery.data('counter');
        var numItems = $items.length;
        var imageToShow = counter % numItems; 
        $items.hide();
        $items.eq(imageToShow).show();
    };

    $('.gallery').on('click', function(e) {
        e.stopPropagation();
        var gallery = $(this);
        var gWidth = gallery.innerWidth();
        var gOffset = gallery.offset();
        var x = e.pageX - gOffset.left;
        if (gWidth / 2 > x) {
            gallery.data('counter', gallery.data('counter') - 1);
            showCurrent(gallery);
        } else {
            gallery.data('counter', gallery.data('counter') + 1);
            showCurrent(gallery);
        }
    });
});

Check it out on JSFiddle: https://jsfiddle.net/ty0vqk2y/1/

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

Parse the text file to extract its data and display that data in a table using Yii2 framework

Below is the javascript code used in my form: $('#idOfButton').click(function(){ var id = $('#input').val(); $.get('index.php?r=tbltime/get-file',{ id : id },function(data){ var data = $.parseJSON(data); ...

I am experiencing an issue with the display inline feature not functioning properly in Firefox

I am working with Html code: <div class="login"> <form class="form-horizontal signin"> <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">Ema ...

struggling with handling form data in Express/Node application

Currently this is my setup: Below is the Post method I am using app.post('/barchartentry', function(req, res){ res.render('barchart', { title: 'EZgraph: Bar Chart', barValues: req.body.myInputs, labelValues: req.body ...

Adjusting the page size in the material table to display all items

I am currently working with React and Material Table. Objective My goal is to provide the user with the option to set the pageSize to 'All' in order to display all rows in the material table. Steps Taken I utilized the useState hook to create ...

retrieve data from JSON file

function retrieveDataFromProfiles(){ const fs = require('fs') fs.readFile('src/data/profileInfo.json', function(error, data){ if(error){ alert(error); } var profileData = JSON.parse(data); //retrieves the JSON data of ...

Is there a way to eliminate the default Tab indicator in Materializecss?

Utilizing the tab feature in MaterializeCSS to enhance the navigation tabs for my web application. By default, the initial tab is already chosen, evident by the underlined indicator beneath it as depicted in the image below. https://i.sstatic.net/PbGb5.pn ...

My Angular2+ application is encountering errors with all components and modules displaying the message "Provider for Router not found."

After adding routing to my basic app through app.routing.ts, I encountered errors in all of my test files stating that no Router is provided. To resolve the errors, I found that I can add imports: [RouterTestingModule], but is there a way to globally impo ...

Adapting software for use with Panasonic Viera

We are in the process of transferring our current HTML/JavaScript/CSS application to the Panasonic platform. Our current setup involves using JavaScript for generating HTML and CSS for styling the application. The programming language used in the Panasoni ...

Causing a click event to occur results in crashing the browser

Take a look at this link: example on jsfiddle Why does the click event keep triggering multiple times when a div is clicked, eventually causing the browser to crash? What could be causing this issue and how can it be resolved? The actual div contains a l ...

Top Method for Reloading Element-Specific JavaScript When Replacing Elements

Is there a better way to re-initialize JavaScript without needing a page refresh? I'm currently struggling with appending an MDBootstrap <select> tag, which involves more than just adding a child element. Instead, I have to remove the element an ...

The setInterval function is active in various components within Angular 6

Recently, I started using Angular(6) and incorporated the setInterval function within a component. It's functioning properly; however, even after navigating to another route, the setInterval continues to run. Can someone help me determine why this is ...

How can I include a path prefix to globs provided to gulp.src?

Consider the contents of these two essential files: settings.json { "importFiles": [ "imports/data.js", "imports/functions.js", "imports/styles.css" ] } builder.js var build = require("builder"), combine = require("combine-files"), ...

Access exclusive RSS feeds from Twitter

I am facing a challenge in showcasing the most recent 3 tweets from Twitter on my client's website. The tweets are marked as private, making it difficult to access them. How can I pass the username and password to retrieve these latest tweets? Is it p ...

Passing a JavaScript object that may be undefined to a pug template in Node.js

My journey requires transferring a set of JavaScript objects to the pug template. router.get('/edit/:itemObjectId', async function(req, res, next) { var itemObjectId = req.params.itemObjectId; var equipmentCategoryArr = []; var lifeE ...

Refreshing an iframe located on disparate domains

There is a webpage called "main.jsp" within the domain "domain1". This page contains an iframe that loads content from another domain known as "domain2". Essentially, "main.jsp" serves as a common content platform, with the iframe displaying content from v ...

Tips for positioning a modal in the center specifically for zoomed-in mobile devices

I created a modal that uses the following function to center itself: center: function() { var top=Math.max($window.height() - $modal.outerHeight(),0) / 2; var left=Math.max($window.width() - $modal.outerWidth(),0) / 2; $modal.css({ ...

The successful cross-origin request was achieved without the implementation of CORS

I'm starting to second-guess myself now. Using jQuery Ajax, we can initiate a POST request. For example: $.post("https://external.com", $('form').serialize()); When I check my Chrome console, I see this message: XMLHttpRequest cannot l ...

What's the best way to avoid global application of stylesheets imported for svelte carbon components?

My dilemma lies in wanting to utilize the DatePicker feature from carbon-components-svelte. Unfortunately, when I do so, the global application of styles from carbon-components ends up causing some conflicts with my own custom styles. As per the documenta ...

Retrieving the link to share for every video located in the Dropbox folder

My Dropbox folder contains a set of videos labeled "v1.avi, v2.avi, ....., vn.avi". I am looking to automate the process of extracting the share link for each video in the folder so that I can easily use it as a source value for HTML video. . . . Is ther ...

Tips for displaying the UI Slider value on multiple fields simultaneously

I'm trying to display the value of a UI range slider in an input box. I have successfully done this, but now I want to show the same value in another div as well. Currently, I am able to capture the slider's value in the input box, but I also ne ...