Display the file name of the following/preceding images on the backward/forward button

Hello, I am fairly new to web development and could use some professional assistance. I have a slideshow set up, but I am struggling with adding the filename of the next or previous images to the back/forward icons of the slideshow. Is this achievable with the current code setup? Here is an image to illustrate my point: example

HTML:

<div id="container">
        <ul>
            <li><img src=""></li>
            <li><img src=""></li>       
        </ul>
        <span class="button prevButton"></span>
        <span class="button nextButton"></span>
</div>

JS:

$(window).load(function(){
            var pages = $('#container li'), current=0;
            var currentPage, nextPage;

            $('#container .button').click(function(){
                currentPage = pages.eq(current);
                if($(this).hasClass('prevButton'))
                {

                    if (current <= 0)
                        current = pages.length-1;
                    else
                        current = current-1;
                }
                else
                {
                    if (current >= pages.length-1)
                        current = 0;
                    else
                        current = current + 1;
                }
                nextPage = pages.eq(current);   
                currentPage.hide(); 
                nextPage.show();        
            });
    });

Answer №1

Your approach seems a bit off, as you don't necessarily have to create an element for every image you have.

If you want to obtain the filename, you can use the following code snippet:

 url.substring(url.lastIndexOf('/')+1);

Here is the full code:

<img src="" id="slide">    


$(window).load(function(){
        function getFileName(url) {
            return url.substring(url.lastIndexOf('/')+1);
        }
        var $imgEl = $("#slide");
        var counter = 0;
        var imagesSrcs = [ 'http://www.exmaple.com/example.jpg', 'http://www.exmaple.com/example.jpg', 'http://www.exmaple.com/example.jpg']; 


        $('#container .button').click(function(){
            if($(this).hasClass('prevButton'))
            {

                counter--;
                if (counter < 0)
                    counter = imagesSrcs.length - 1;
            }
            else
            {
                counter++;
                if (counter == imagesSrcs.length)
                     counter = 0;

            }
            $imgEl.attr('src', imagesSrcs[counter]);
            console.log(getFileName(imagesSrcs[Math.min(counter + 1, imagesSrcs.length -1)])); //next image file name  
            console.log(getFileName(imagesSrcs[Math.max(counter - 1, 0)])); //previous image file name      
        });
});

https://jsfiddle.net/u0fcbgga/

Answer №2

Thanks so much for your help with the code. The slideshow is working well, but I may have caused some confusion with my previous message, I apologize for that. What I'm really looking for is to have two back/forward button icons in the slideshow, and I'd like the names of the next/prev images to be displayed before clicking the buttons. Here are the links to the icons: https://i.sstatic.net/uWxOx.jpg. The desired result should look something like this: Result.

p/s: Thank you for your dedication and hard work.

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

Intercept Axios Responses - Retrieving API Responses for HTTP Statuses that are not in the 200 range

I've set up a custom Axios instance with interceptors for handling responses. As per the Axios documentation, the success interceptor is triggered for 2xx statuses while the error interceptor handles any other status codes. My goal is to show an error ...

Choose an image with Jquery Mobile 1.4.2

I attempted to create a combobox with images using Jquery Mobile, and found a solution on Stack Overflow. Here is the JsFiddle link for reference: http://jsfiddle.net/ezanker/Ba4gG/4/ However, when implementing it in my project which uses Jquery Mobile 1 ...

Using CSS to cut out a triangle shape from an image

Our designer has a vision for this: However, I'm struggling to find a suitable method for creating the triangle crop effect: Implementing an :after element that spans the entire width and utilizes border tricks to form a triangle shape Creating a l ...

Having difficulty using the forEach() method to loop through the array generated by my API

During my troubleshooting process with console.log/debugger, I discovered that I am encountering an issue when attempting to iterate over the API generated array in the addListItem function's forEach method call. Interestingly, the pokemonNameList ar ...

Changing the visibility of a model in a method using the setVisible() method with Wicket Ajax

So in my code, I have: public class MyClass extends WebPage { static AjaxFallbackLink ddd = null; static AjaxFallbackLink dddd = null; (...) } Within the constructor, I have: ddd = new AjaxFallbackLink("previous") { @Override pub ...

Troubleshooting: Unable to get the :last selector to work

$('.data_row:last').after('<tr class="odd"> <td class="first data" style="min-width: 29px;">2</td></tr>'); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> < ...

Executing Ionic function before application shutdown

Does anyone know of a function that can be triggered when the app is about to exit, close, or go into the background? Essentially any event that indicates "the user has stopped using the app"? In my app, I create a 'user log' that keeps track of ...

What is the process for installing the jQuery time ago plugin?

I'm having trouble getting the jquery time ago plugin to function properly. Below is the code I am using: <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script src="j ...

Issues arise with the functionalities of FireFox related to transformations and transitions

I've been working on my CSS and here is what I have: img.buttonImg { -webkit-transition: all 0.5s ease-in-out; -moz-transition: all 0.5s ease-in-out; -o-transition: all 0.5s ease-in-out; -ms-transition: all 0.5s ease-in-out; transition: ...

Finding the data type based on the button clicked with javascript: A beginner's guide

I am trying to work with a PHP function that generates dynamically created divisions. Each of these divisions contains a different data type and a button. How can I extract the data type of a division when the user clicks on the submit button using JavaScr ...

Book Roulette: Your Next Random Read

I created a code for a random quote generator and now I want to create something similar, but with images this time. I am looking to add a feature on my page where it can recommend a book by displaying its cover image when a button is clicked. For the pre ...

Having trouble with Typeahead Bootstrap not displaying dropdowns for ajax calls?

Utilizing Bootstrap 3 with the compatible Typeahead extension (https://github.com/bassjobsen/Bootstrap-3-Typeahead). The website operates on Django, and the query fetches information from a local Postgres server. Experiencing issues with displaying dropd ...

Attempting to eliminate the padding from the unordered list (ul) element within the pop-up box

Upon clicking the chip with chipName="button test IPA", a popup window appears. I am attempting to remove the padding from the ul tag within that popup. The issue I'm facing is that I cannot locate the ul tag in my HTML or JSX code. I have assigned a ...

When I increase the length of my website's header and footer, I notice that the data in the footer is only displayed on the homepage and not on the other

I am facing an issue with extending my header and footer in Django. The problem is that when I pass data to the footer, it only appears on the home page and not on other pages. I understand that I need to pass the data to every page individually, but I am ...

Is there a way to retrieve the final value from an Observable?

Trying to retrieve the last value from an observable. Here is an example of the code: // RxJS v6+ import { lastValueFrom, Subject } from 'rxjs'; import { scan } from 'rxjs/operators'; async function main() { const subject = new Subje ...

Oops! Hardhat Test Error "Error: Virtual Machine Exception occurred while processing transaction: reverted with reason 'Please deposit additional funds'."

Encountering an issue with the following error message: Error: VM Exception while processing transaction: reverted with reason string 'deposit more' in the Hardhat Test.js file Test.js -> it("should be able to withdraw if no one appl ...

Encountered error: Unable to access property 'value' as it is undefined while mapping in react components

element populateOptions() { return this.props.options.map((option, i) => ( <optgroup key={i} label={option.text}> {option.value.map((entry) => ( <option>{entry.text}</option> ))} </optg ...

What is preventing me from binding the array index to a model in AngularJS with two-way binding?

I'm currently facing a challenge with a seemingly simple task: I have an array of string values that I want to link to a select element's options, and then connect the index of the chosen value to a variable. However, I have found that neither us ...

Tips for creating a consistent format based on test cases

var years = Math.floor(seconds / (3600*24*365)) seconds -= years*3600*24*365 var days = Math.floor(seconds / (3600*24)) seconds -= days*3600*24 var hrs = Math.floor(seconds / 3600) seconds -= hrs*3600 var minutes = Math.floor(seconds / 60) ...

Vue(x) causing state mutation in array

I'm currently in the process of building a Vue application to help me learn more about web development. I've hit a roadblock when it comes to updating an array in my state with data from an API. Here's a snippet of the API response: { "st ...