How can you transfer data from a jQuery function to a designated div element?

I'm struggling to transfer data from a function to a specific div, but I can't seem to make it work. I'm in the process of creating a gallery viewer and all I want is to pass the counter variable, which I use to display images, and the total number of files for each gallery on the page.

Below is the code snippet:

Javascript/jQuery

$(document).ready(function () {
    $('.photoset').each(function () {
        $(this).data('counter', 0);
        $items = $(this).find('img')
        $(this).data('numItems', $items.length);
    });

    var showCurrent = function (photoset) {
        $items = photoset.find('img');
        var counter = photoset.data('counter');
        var numItems = $items.length;
        var itemToShow = Math.abs(counter % numItems);

        $items.fadeOut();
        $items.eq(itemToShow).fadeIn();
    };

    $('.photoset').on('click', function (e) {
        e.stopPropagation();
        var photoset = $(this);
        var pWidth = photoset.innerWidth();
        var pOffset = photoset.offset();
        var x = e.pageX - pOffset.left;
        if (pWidth / 2 > x) {
            photoset.data('counter', photoset.data('counter') - 1);
            if (photoset.data('counter') < 0)
                photoset.data('counter', photoset.data('numItems') - 1);
            showCurrent(photoset);
        } else {
            photoset.data('counter', photoset.data('counter') + 1);
            if (photoset.data('counter') > photoset.data('numItems') - 1)
                photoset.data('counter', 0);
            showCurrent(photoset);
        }
        $(this).text(photoset.data('counter') + 1 + " de " + photoset.data('numItems'))
    });
});

Razor HTML

<div class="container">
    @{ var i = 10; }
    @foreach (var item in Model)
    {
        <div class="row">
            <div class="col-md-4 col-md-offset-4 text-center">
                <br />
                @Html.DisplayFor(modelitem => item.NomeGaleria)
                <br />
            </div>
        </div>
        <div class="row"><div class="col-md-4 col-md-offset-4 text-center"><div class="nav-informer"></div></div></div>
        <div class="row">
                <div class="photoset center-block">


                    @{ var item2 = item.FilePaths;}
                    @for (var k = 0; k < Enumerable.Count(item2); k++)
                {
                        <br />
                        <img src="~/images/@Html.DisplayFor(modelItem2 => item2[k].FileName)" style="@(k != 0 ? "display: none" : "" ) " />
                        <br />
                    }

                </div>

        </div>

    }
</div>

I am using this line of code

$(this).text(photoset.data('counter') + 1 + " de " + photoset.data('numItems'))

to send the data to the "nav-informer" div without success. Can anyone suggest what might be wrong here? Apologies if this sounds like a silly question, as I'm still learning jQuery.

UPDATE

Here is the final rendered HTML page:

<div class="container">

    <div class="row">
        <div class="col-md-4 col-md-offset-4 text-center">
            <br />
            Gallery One
            <br />
        </div>
    </div>
    <div class="row"><div class="col-md-4 col-md-offset-4 text-center"><div class="nav-informer"></div></div></div>
    <div class="row">
            <div class="photoset center-block">



                    <br />
                    <img src="/images/572fdd6b-13eb-48d2-8940-23da73e056c0.JPG" style=" " />
                    <br />
                    <br />
                    <img src="/images/018a55be-a8a7-4412-8415-1678d01eb6a2.JPG" style="display: none " />
                    <br />
                    <br />
                    <img src="/images/e5b0bdcb-d517-49a5-818b-245d46c0a0d9.JPG" style="display: none " />
                    <br />

            </div>

    </div>
    <div class="row">
        <div class="col-md-4 col-md-offset-4 text-center">
            <br />
            Gallery Two
            <br />
        </div>
    </div>
    <div class="row"><div class="col-md-4 col-md-offset-4 text-center"><div class="nav-informer"></div></div></div>
    <div class="row">
            <div class="photoset center-block">



                    <br />
                    <img src="/images/fdc2e9fd-978a-4150-87af-483e34f68798.JPG" style=" " />
                    <br />
                    <br />
                    <img src="/images/b17d169d-e5ed-45cd-9901-1d9dc294c873.JPG" style="display: none " />
                    <br />
                    <br />
                    <img src="/images/3ad1ae20-7102-4d69-b658-7b3d8cbfb9e8.JPG" style="display: none " />
                    <br />
                    <br />
                    <img src="/images/4ef03a84-da00-4f93-b3a2-839ac2ec9ac2.JPG" style="display: none " />
                    <br />

            </div>

    </div>

Answer №1

When starting out with jQuery, using $(this) essentially refers to "the element where the process began," which in this scenario is .photoset. Therefore, $(this) = $('.photoset')

If you want the specified text to appear within your .nav-informer div, simply change $(this) to $('.nav-informer')

$('.nav-informer').text(photoset.data('counter') + 1 + " de " + photoset.data('numItems'));

UPDATE

It appears that you need to navigate through the hierarchy. Is each 'gallery' contained within a .container? If so, try the following:

$(this).closest('.container').find('.nav-informer').text(photoset.data('counter') + 1 + " de " + photoset.data('numItems'));

.closest() ascends the hierarchy to locate the closest parent of the initial element being referenced (in this case, $(this)).

'find()' operates in the opposite direction, descending through the hierarchy to identify the first occurrence of the specified element from the preceding point.

Combining them means using .closest() to reach the parent of the desired element and then .find() to target the subsequent element. This approach eliminates the complexity that arises from using .parents(), .children(), and .siblings().

UPDATE 2

Understood - Your method of exporting each gallery may become more complicated over time. Ideally, consider enclosing both the gallery and informer within the same container. However, if maintaining the current structure is necessary, try this:

$(this).closest('.row').prev('.row').find('.nav-informer').text(photoset.data('counter') + 1 + " de " + photoset.data('numItems'));

Using .parent() will traverse only one parent level, while .parents() or .closest() can be used when further ascension is required. Once you reach the desired level, utilize .siblings() or, in this case, .prev() due to the consistent positioning of your .nav-informer before the .photoset. This targets the immediately preceding div at the same level.

View a quick example in This Fiddle.

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

How can we programmatically add click handlers in Vue.js?

Currently attempting to add some computed methods to an element based on mobile viewports exclusively. Here is a simplified version of my current project: <a class="nav-link float-left p-x-y-16" v-bind:class={active:isCurrentTopicId(t.id)} @click="onTo ...

Automatically update the div every few seconds and pause when it has loaded successfully

I am facing a challenge in creating a div that refreshes automatically every 10 seconds, but stops when it successfully loads. Here is the jQuery script I have developed: <script type="text/javascript"> $(document).ready(function(){ var j = jQuer ...

Can user-generated code execute Javascript Promises in its entirety?

Can one fully implement the JavaScript Promise class using only userspace code, without relying on any support from native code (such as the internals of JavaScript) that would typically only be accessible to those working on a JavaScript engine like the V ...

What is causing the breakdown of bordered tables in Bootstrap when the border-separate property is set to collapse?

I am experiencing an issue with my bordered table that is using the Bootstrap classes table table-bordered. When I add border-collapse: separate, the borders are correctly separated, but the top and bottom borders seem to disappear due to zero width. I am ...

When examining two arrays for similarities

I am dealing with two arrays within my component arr1 = ["one", "two"] arr2 = ["one", "two"] Within my HTML, I am utilizing ngIf in the following manner *ngIf="!isEnabled && arr1 != arr2" The isEnabled condition functions as expected, however ...

Adding a Font Awesome icon on the fly in Vue.js

In my Vue modal, I have two inputs along with a button that adds two more inputs dynamically when clicked. Everything is functional, but I want to include a font awesome icon next to the dynamically created inputs. How can I achieve this in Vue? Here' ...

Using AJAX to dynamically load an image by setting the image path as the source of the image tag

I'm facing a challenge with my AJAX call that is used to display user details in a modal. I recently integrated an image upload feature for users, but now I'm struggling to display the uploaded image. I have tried looking for solutions online, bu ...

I don't understand why my BeautifulSoup code is throwing an attribute error even though the variable it's referring to is assigned a value

Currently, I am working with Python 3.9.1 along with selenium and BeautifulSoup to develop my first web scraper targeting Tesco's website. This is essentially a mini project that serves the purpose of helping me learn. However, upon running the code p ...

Having trouble hiding the hamburger menu depending on the screen width

I'm trying to figure out how to hide the hamburger menu when the screen width exceeds 400px. You can check out the site at damf.co Currently, the hamburger menu appears when the screen width is less than 400px. If you click on it and then expand the ...

Material UI: Easily adjusting font size within Lists

When developing forms with react js and material UI, I encountered an issue with changing the font size within lists to achieve a more compact layout. The code fontSize={10} didn't seem to have any effect regardless of where I added it. Is there a wa ...

What is the proper way to update a dropdown value in a React JS component?

Can you please guide me on how to assign a value in a dropdown in react js? I am retrieving the dropdown data after a delay of 3000 milliseconds and then I need to set a value in the dropdown. const App = ({ children }) => { const val = "ax"; const ...

Displaying the division of shares in an HTML table using jQuery to add a new row

I recently worked on transposing a table, adding classes and ids to specific HTML tags, and converting numbers with commas into integers. Now, I am attempting to calculate the percentage share and display it in a new row. Here is the original table for re ...

AngularJS: Pause the data binding functionality temporarily

How can I temporarily deactivate data binding in AngularJS? I am working with a list called items that is being displayed using ng-repeat. I need to perform some operations on this list without immediately updating the page, as this could cause slowdown. ...

Activate Angular Material's autocomplete feature once the user has entered three characters

My goal is to implement an Angular Material Autocomplete feature that only triggers after the user has inputted at least three characters. Currently, I have it set up so that every click in the input field prompts an API call and fetches all the data, whic ...

a script in JavaScript that retrieves the selected value from a radio button box

I have an AJAX table where I need to highlight one of the rows with a radio box on the left side. However, I lack proficiency in JavaScript and would like assistance in retrieving the value of the radio box by its ID from this table once it has been select ...

Implementing a Moving Background Image with CSS3 or jQuery

I am facing an issue with a background image that has a file size of 4+ MB in PNG format. My website is a single page website and I want to use this background image, but I'm unsure how to go about it. Is there a way to reduce the size of the image s ...

Puppeteer and Chromium are ready to go with no need for any configuration

I have a specific HTTP request that I am trying to intercept, but I am encountering issues when chromium is launched through puppeteer. Some flags seem to be causing the requests to not return the expected data. However, everything works fine when I manual ...

Update the Material UI input field value using an external JavaScript script

Imagine I find myself exploring an online form that utilizes Material UI components, for instance, this example link. I am interested in automatically filling the input fields with a specific value using JavaScript in the console: for (input of document.g ...

The Google Maps API swipe feature on mobile devices is causing issues with screen scrolling

When users visit my website on mobile, they encounter a situation where Google Maps suddenly covers the entire page, preventing them from scrolling away. This is because swiping up or down only moves the map view within Google Maps, instead of scrolling th ...

What causes compatibility issues between JEST and import statements in NEXTJS?

Just starting out with unit testing in JavaScript and I'm attempting to create a unit test for a Next JS project. However, when running the test, I encountered the following error: Code: import {isBase64} from '../../service/base64-service&a ...