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

Which is better for scrolling in Angular 2+: using HostListener or window.pageYOffset?

Which syntax is best for maximizing performance in Angular 2+? Is it necessary to use HostListener, or is it simpler to obtain the scroll position using the onscroll window event and pageYOffset? @HostListener('window:scroll', ['$event&ap ...

Why is the view not reflecting the updates made to the model?

I recently started delving into Angular JS and have been following tutorials to learn it. One issue I'm facing is that my model doesn't seem to update the view. Can anyone help me figure out why this is happening? Here is the code snippet: < ...

I am looking to modify the highlighted table cell whenever the value within it changes

I am currently working on a small project related to the Stock Market. In this project, I need to dynamically change the style of the td element based on data fluctuations - green highlight for an increase and red highlight for a decrease. In the provid ...

Displaying a custom error page in Next.js with the appropriate status code

I recently implemented a custom error page following the instructions provided in the documentation. My goal was to use this error page for specific errors that may occur during the getStaticProps function. Here's how I structured it: const Page: Next ...

Mapping the Way: Innovative Controls for Navigation

Currently, I am utilizing the HERE maps API for JavaScript. However, I would like to customize the design of the map controls similar to this: Below is an example for reference: HERE EXAMPLE Is it feasible to achieve this customization? ...

Displaying a 404 error page in a Vue.js and Vue Router single-page application when a resource is not

Implementing Vue and Vue Router in a single page application (SPA) has presented me with a challenge. In one of my view components, I query a repository for a specific resource. If the resource cannot be found, I'd like to display a 404 error page wit ...

Generate responsive elements using Bootstrap dynamically

I'm having success dynamically generating bootstrap elements in my project, except for creating a drop-down menu. ColdFusion is the language I am using to implement these div elements: <div class="panel panel-primary"><div class="panel-head ...

Using Javascript to Showcase a Video's Number of Views with Brightcove

How can I show the number of views for a video without using Brightcove's player? Brightcove Support shared this resource: , but I'm having trouble understanding it. ...

Is there a way to generate and transmit a text file using XmlHttpRequest or $.ajax?

The server is anticipating an html or txt file to be sent from a form named "websitetopdf". The file is dynamically created on client javascript and should only function properly on Chrome. Below is the form that needs to be used for sending: <form ac ...

What is the solution to the error message that states a bind message provides 4 parameters, while a prepared statement "" necessitates 5?

Is there a way to fix the issue where the bind message provides 4 parameters but the prepared statement "" requires 5? I've tried solutions from others who faced similar problems without success. (I've included all classes for better error unders ...

What is the limit of CSS includes that IE can process?

While working on theming Drupal, I encountered an unusual issue. After enabling a few modules that added 5 to 10 link tags to the page, I noticed a strange behavior in different browsers. Firefox successfully added the new stylesheets to the cascade, but i ...

Is Adsense flexibility the key to achieving the perfect fluid layout?

I've successfully created a CSS 3 column fluid layout, thanks to everyone's help! In my left column, I have a Google AdSense advert. Unfortunately, the sizes of these adverts are not very flexible. I'm wondering if there is a way to change t ...

Can VueJS 1 and 2 be integrated within the same package.json configuration?

At the moment, my JavaScript files are using VueJS 1. However, I am preparing to work on a new section of the system and want to switch to VueJS 2. ...

Adding HTML content using jQuery's document.ready feature

As a jQuery novice, I am attempting to incorporate a Facebook like button using the jQuery document.ready function. In my external Javascript file (loaded after the jQuery script), you will find the following code snippet: $(document).ready(function(){ ...

What is the best way to establish a default selection in Angular?

After retrieving JSON data from the server, it looks something like this: $scope.StateList = {"States": [ { "Id": 1, "Code": "AL", "Name": "Alabama" }, { "Id": 2, "Code": "AK", "Name": "Alask ...

Tips for maintaining consistent styles in CSS for multiple websites

I am currently working on developing a customizable chatbot widget using react. The goal is to create a chatbot widget that can be easily integrated into any website, similar to the functionality of rasa-webchat. During testing on some websites, I encount ...

Storing the closed state of a pop-up box in localStorage for future reference

I'm struggling to get localStorage working properly on my website (). Here's what I need to achieve: A newsletter subscription pop-up on every page - this part is functioning correctly An option for users to click 'X' to close the po ...

Tips on transmitting form information from client-side JavaScript to server-side JavaScript with Node.js

Having created an HTML page with a form, my goal is to capture user input and store it in a JSON file. However, I've run into some confusion... In the process, I utilized the express module to set up a server. My mind is juggling concepts such as AJA ...

What is the best way to split an array into smaller chunks?

My JavaScript program fetches this array via ajax every second, but the response time for each request is around 3 to 4 seconds. To address this delay, I attempted to split the array into chunks, however, encountered difficulties in completing the task: { ...

What is the reason for the continual influx of new users being added to the database?

I have a Node.JS and MongoDB console application where I've implemented adding users in one file and outputting all collection objects to the console in another file. When running the command - node scripts/get_all_users.js, both existing users are di ...