Error in jQuery when trying to access the src attribute of an image: "undefined src

Just started delving into jQuery. I'm trying to grab the image source and showcase it in a fixed division like a pop-up, along with the image title. However, I'm encountering difficulties in fetching the image source.

My attempt with the .attr() method is returning undefined.

HTML:

            <div id="album">

                <div class="pic">

                </div>

                <div class="screen">
                    <h1 class="title">Photo 1</h1>
                    <img src="images/1 png.png" class="image" />
                    <p class="description">This is a description</p>
                </div>

                <div class="screen">
                    <h1 class="title">Photo 1</h1>
                    <img src="images/1 png.png" class="image" />
                    <p class="description">This is a description</p>
                </div>
                <span class="clear_left"></span>

            </div>

css:

.screen {
    border: 1px solid green;
    margin: 10px auto;
    float: left;
    cursor:pointer
}

.image {
    width: 300px;

}

.title {
    font-size: 30px;
}

.description {
    font-size: 25px;
}

.pic {
    width: 600px;
    position:fixed;
}

js:

$(document).ready(function () {
    $(".pic").hide();
    $(".screen").click(function () {
        display();
    });
});

function display() {
    var source = $("img",this).attr("src");
    alert("The souce of the image is " + source);
}

Answer №1

The issue lies in the fact that the display() function lacks the necessary element context when triggered by a click event. This results in it displaying undefined

To fix this problem, consider the following solution:

$(document).ready(function () {
    $(".pic").hide();
    $(".screen").click(function () {
        display($(this));
    });
});

function display($this) {
    var source = $("img", $this).attr("src");
    alert("The image source is " + source);
}

See it in action

Answer №2

Avoid enclosing your function call within an additional anonymous function:

Example: http://jsfiddle.net/3RtFZ/

$(".box").hover(showMessage);

By doing this, the function will now receive the context of this.

Answer №3

this in the context of the display function is actually referring to the anonymous function, not the specific element. It is not necessary to wrap it. Using $('.screen').click(display) ensures that this points to the .screen element.

To improve clarity, I suggest modifying the display function as follows:

function display() {
    var source = $(this).find('img').attr('src');
    alert("The source of the image is " + source);
}

This approach utilizes jQuery to target the clicked .screen element and then locates the img element within. It may provide a clearer understanding, although it ultimately comes down to personal preference.

Answer №4

The reason why the value of this in the display function is not the same as in the click function for .screen is due to the scope of this. To test this, you can add a console.log(this); statement inside the display function to see the value of this.

If you need to pass the value of this to the display function, you can utilize the call function like this:

$(document).ready(function () {
    $(".pic").hide();
    $(".screen").click(function () {
        display.call(this);
    });
});

function display() {
    var source = $("img", this).attr("src");
    alert("The source of the image is " + source);
}

Alternatively, you can eliminate the anonymous function and directly pass in the display function like so:

$(".screen").click(display);

Answer №5

The reason behind this issue is the undefined value of your src attribute.

function showImage() {
    var imgUrl = $("img", this).attr("src", "images/okay.jpg");
    alert("The source of the image is: " + imgUrl);
}

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 to effectively filter nested arrays within Mongoose Populate function

I received the following object from a Mongoose query: let systems = [ { "maxUserLevel": 1, "subsystems": [ { "sections": [], "name": "apple" ...

Using Javascript/JQuery to apply pixel values in CSS styling

Recently, I've come across a discrepancy between two different ways of accessing CSS properties in jQuery: <foo>.css('marginTop') (which I always assumed was the standard notation) and <foo>.css('margin-top') (which ...

Exploring the functionality of textareas within iframes on iPad

There is a known issue where textareas and inputs do not function properly on iPad Safari when placed inside an iframe. For more information, visit: This bug can easily be reproduced on iOS 7, but seems to work fine on iOS 8. Despite this issue, I am in ...

Having trouble toggling the dropdown submenu feature in a Vuejs application?

.dropdown-submenu { position: relative; } .dropdown-submenu .dropdown-menu { top: 0; left: 100%; margin-top: -1px; } <div class="dropdown"> <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">Tutorial ...

Is there a way to change or delete this inline javascript using Greasemonkey?

I stumbled upon this script within the head of a website: <script type="text/javascript" > function Ext_Detect_NotInstalled(ExtName,ExtID) { } function Ext_Detect_Installed(ExtName,ExtID) { alert("We have detected an unauthorized extension. Pl ...

What is the best way to instruct jQuery to disregard an empty server response?

After examining this piece of code: $.ajax({ type: "POST", url: theRightUrl, data: whatToPost, logFunction: whatever, suppressSuccessLogging: !0, dataType: "html" }); I encountered an issue where Firefox displays a "no element ...

Display or conceal a YouTube video with a click

Q1) Is it possible to use JQuery on page load to detect the file name of an image and then dynamically position it on the page with CSS? Q2) What is the most efficient way to achieve this without embedding iframe code inside a specific div.icon element? ...

Exploring the Possibilities with NodeJS and Socket.IO

I've encountered an interesting issue with my use of NodeJS and Socket.io. The server receives data through ZeroMQ, which is working perfectly fine. However, when there are a large number of connected clients (over 100), it appears that there is a de ...

Activation of states in response to item clicks

Recently, I started using the US-Map plugin created by newsignature (). I have put together a chart that highlights various state laws for comparison on a per-state basis. Currently, the setup allows me to compare 3 states at a time. Users can easily clos ...

Is the navigation dropdown toggle triggered by both mouseout and when hovering off of it?

I'm looking for some assistance in modifying the code so that the dropdown menu not only hides on click, but also hides on mouseout and/or when another top-level menu button is hovered over. View jsfiddle example $(document).ready(function () { ...

Add an item to one ng-repeat by clicking a button in another ng-repeat

I'm trying to manipulate two ng-repeats by adding values from one to the other and vice versa. Here's a snippet of my HTML: <div id="external-events"> <div ng-repeat="selected in selectedcolumn"> <div class="external-event b ...

When a block is clicked, jQuery will reveal that block while hiding the others sequentially, starting with the second block, then the third, and finally the fourth

Creating a navigation menu with 4 blocks can be a bit tricky, especially when trying to show one block at a time upon click. Here is my code attempt, but unfortunately it's not working as expected. I would greatly appreciate any help or suggestions on ...

Getting the value of an element using a string in JQuery

How can I achieve the following using JQuery? var test = "'#ISP'"; alert($(test).val()); I am receiving a "Syntax error, unrecognized expression." I believe I might be overlooking something here. Thank you in advance! ...

Pass arguments in an ajax request when making a request with jQuery datatables

My goal is to populate a jQuery datatable using ajax and pass parameters to the function retrieving data from the database. This is what I want to achieve: $('#datatables').dataTable( { "bProcessing": true, "bServerSide": true, "sAj ...

Dealing with adding up optional values from v-model in Vue.js can be a challenging task

Within this function, I need to display the remaining amount. remainingAmount: function() { return parseFloat(this.sumAmount) - (parseFloat(this.cash) + parseFloat(this.kNet) + parseFloat(this.kNetOnline)); } The three parameters cash ...

What is the best way to integrate Halfmoon's JS from npm into my current code using Gulp?

I am eager to incorporate the Halfmoon framework into a personal project and have successfully downloaded it through npm. To utilize the example JavaScript provided on this page (found at ), I need to import the library using a require statement. var halfm ...

What are some ways to utilize JavaScript for expanding an HTML form?

I am in the process of developing a basic web application that allows users to create messages with attached files. multiple html file inputs using this javascript link: http://img38.imageshack.us/img38/4474/attachments.gif The functionality to "attach a ...

Error encountered in Next.js while fetching data: Invalid JSON response received, with an unexpected token "<" at the start of the JSON data

I've been attempting to utilize the getStaticProps function in order to send a request and then pass the retrieved data to a component: However, I keep encountering this error: FetchError: invalid json response body at reason: Unexpected token < ...

I am currently working on a website that offers different themes, and I am attempting to update the iframe to reflect the selected theme on the site

I'm feeling lost on how to accomplish this task. Despite my efforts, I have been unable to find a solution so far. Perhaps utilizing javascript might be the key here, yet I am uncertain about integrating it into the existing script that I use for modi ...

Reconfigure the Node application using Express to seamlessly access modules through route files

I recently created a basic app using npm express. After generating the app.js file, I attempted to add new modules but encountered an issue where I couldn't access them in the route files. For example, when trying to utilize the 'request' mo ...