How to retrieve the image source from a block using jQuery

Currently, I am working on developing a slider for my webpage using jquery's "Cycle" plugin. However, I have encountered an issue with accessing the image sources used in the slider. To provide more context, here is a snippet of code from the 'head' section:

<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="jquery.cycle.all.js"></script>
<script type="text/javascript">
    $('#slider').before('<ul id="pager">').cycle({ 
        fx: 'scrollHorz',
        speed: 900,
        timeout: 5500,
        pause: 1,
        pager: '#pager',

        pagerAnchorBuilder: function(idx, slide) { 
        return '<li><a href="#"><img src="' + slide.src + '" width="120" height="65" /></a></li>'; 
        } 
    });
</script>

Additionally, here is a portion of the html content related to this problem:

<div id="slider_container">
    <div id="slider">
        <div class="items">
            <img src="1.jpg"/>
            <div class="info">
                <h2>Tile Nr. 1</h2>
            </div>
        </div>
        <div class="items">                         
            <img src="2.jpg"/>
            <div class="info">
                <h2>Tilte Nr. 2</h2>
            </div>
        </div>
    </div>
    <div id="pager">

    </div>
</div>

Within the slider division, I aim to display blocks comprising both images and corresponding titles. Conversely, within the pager segment, only the images utilized in the slider should be shown. The stumbling block lies in correctly retrieving the image source from the relevant items block using the slide.src expression in the third JavaScript. How can I modify it to access the intended image sources?

Answer №1

Could you please create a jsFiddle that includes the necessary jquery files?

I believe that using slide.src may not be the correct approach. If slide refers to an element in the DOM, you should access its 'source' attribute like this: $(slide).attr('src')

Update:

It turns out that 'slide' refers to the containing div, so we should use the following instead:

$(slide).find('img').attr('src')

Answer №2

Upon examining the parameter slide within the pagerAnchorBuilder function, you will notice that it is a div element with the class items, and it contains an img element as its first child. This allows you to access the img tag and its src attribute in the following manner:

pagerAnchorBuilder: function(idx, slide) {
    var source = $('img', slide).attr('src');
    return '<li><a href="#"><img src="' + source + '" width="120" height="65" /></a></li>'; 
}

There are alternative ways to achieve the same result:

var source = $(slide).find('img').attr('src');
// or using native JavaScript
var source = slide.querySelector('img').getAttribute('src');
var source = slide.querySelector('img').src;
var source = slide.firstElementChild.src

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

Prefering `window.jQuery` over the yarn version

I am currently in the process of transitioning to Vite 3 with Vite Ruby on Rails from Webpacker and Webpack. One major issue I have encountered is that my system functions as a CMS. Some of our long-standing clients have jQuery code embedded directly withi ...

Using jest.fn() to simulate fetch calls in React

Can anyone explain why I have to include fetch mock logic within my test in order for it to function properly? Let's take a look at a simple example: Component that uses fetch inside useEffect and updates state after receiving a response: // Test.js ...

An issue encountered while implementing a post method with fetch and Express

I'm just starting out, so I hope my question isn't too basic. My goal is to send a longitude and latitude from client-side JavaScript to a Node.js server using Fetch and Express.js. Below is the HTML code snippet: <!DOCTYPE html> <html ...

ngMaterial flex layout not functioning properly

I can't seem to figure out why ngMaterial is not laying out my simple hello world app in a row. Despite checking the console for errors, I still can't see what I am doing wrong. I expected the content below to be displayed horizontally instead of ...

Tips for aligning a cluster of floating buttons at the center in Vuetify:

This is the code I am currently working with: <v-container height="0"> <v-row align="center" justify="center"> <v-hover v-slot:default="{ hover }" v-for="(option, index) in options" ...

What is the process for turning off express logs on my node.js command line interface?

Recently, I've begun delving into the world of node.js and in an effort to improve my debugging practices, I've decided to move away from relying solely on console.log. Instead, I am exploring the use of debug("test message") for my debugging ...

Can you provide me with a comprehensive list of all the colors available in Twitter Bootstrap 3?

I've integrated the twitter bootstrap sass 3.0.3.0 gem, which is supposed to be the latest version of twitter bootstrap 3.0.3. I'm trying to customize the colors using the 'customize' section of the LESS variables, but I can't seem ...

How can one effectively handle elements or objects that are both event listeners and event triggers?

Yesterday, I posted a similar question but found it too complex and vague after further research, so I removed it. I have now created a new demo here, which should be self-explanatory for the most part. Below are the HTML and JavaScript sections: <sel ...

What are some effective design principles for creating REST APIs in expressjs?

To streamline my code organization, I made the decision to create a methods folder. Within this folder, I store individual JavaScript files for each URL endpoint (such as website.com/billings). //expressJS configuration... const billings = require('. ...

Emailer: Missing Salutation

While attempting to send emails using Node with Nodemailer (https://github.com/nodemailer/nodemailer), the sendMail call from the Nodemailer transporter is throwing an error message of Greeting never received when connected to an Ethereal test email accoun ...

What is the method for transmitting a YAML file in the form of a base64 encoded string?

I am attempting to transmit a yaml file as a base64 string in order for this code to function: const response = await octokit.request('GET /repos/{owner}/{repo}/git/blobs/{file_sha}', { owner: 'DevEx', repo: 'hpdev-content&apos ...

Components in array not displaying in React

I've been struggling to generate a table from an array in React. Typically, I retrieve data from a database, but for testing purposes, I manually created the array to ensure the data is correct. Despite following examples by enclosing my map code with ...

Tips on incorporating the source path from a JSON file into a Vue component

Is there a way to render images if the path is retrieved from a JSON file? Typically, I use require('../assets/img/item-image.png'). However, I'm uncertain how to handle it in this scenario. Component: <div v-for="(item, index) in i ...

Utilizing React with an alternative server-side language

I have a small PHP backend for my website and I want to incorporate React on the front end. However, being new to front-end development and React, I am finding this process confusing as most online examples assume a JavaScript backend with Node modules. W ...

Removing special characters in ASP

Can someone please advise me on how to remove special characters in ASP (classic)? I am using an MS Access database. Is there a function similar to stripslashes() or addslashes() in PHP that can help with this? Any assistance would be greatly appreciated ...

Utilizing Jquery for precise element placement and retrieving its position details

Within my bundle of jQuery code, there are a few areas where I am experiencing difficulties trying to recall functions. The following is an excerpt of the code: $(document).ready(function(){ $("#myTablePager").html(""); $.ajax({ type: "POS ...

What is the best way to retrieve my data/json from req.body in Express?

Recently, I started working with node.js and encountered an issue while trying to access JSON data on my node.js server through a post request. The goal is to send this data to an API and then pass it back to my front-end JavaScript file. Despite being abl ...

Calculating the sum of values in a GridView using ASP.NET

I have an ASP.NET Web Application where I am utilizing a BulkEditGridView to create an order form. This GridView allows users to edit all rows simultaneously. Within the grid, there is a column that calculates the total cost for each item (cost x quantit ...

Hiding the C3 tooltip after engaging with it

I'm currently expanding my knowledge on utilizing C3.js for creating charts, and one aspect I'm focusing on is enhancing the tooltip functionality. Typically, C3 tooltips only appear when you hover over data points as demonstrated in this example ...

Is there a way to modify the styling for ListItemButton specifically when it is in a selected state?

My first experience with MUI involves trying to customize the styling of a button. After installing my project with default emotion as the styling engine, I attempted to override the existing styles using the css() method mentioned in the documentation: ...