Edward Tanguay
Edward Tanguay

Reputation: 193462

How to get image source of first image with JQuery?

In the following code, I want the first image to be displayed when the page loads, however, it doesn't show anything, and no error in Firebug.

How can I get this line to work:

$('img#main').attr('src', $('img:first').src);

Full Code:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="http://www.google.com/jsapi"></script>
        <script type="text/javascript">
            google.load('jquery', '1.5');
            google.setOnLoadCallback(function() {

                $('img.thm').css({opacity: 0.7});
                $('img#main').attr('src', $('img:first').src); //doesn't work

                $('img.thm').width(80).click(function() {
                    $('img#main').attr('src', this.src);
                });
                $('img.thm').mouseover(function() {
                    $(this).css({opacity: 1.0});
                });
                $('img.thm').mouseout(function() {
                    $(this).css({opacity: 0.7});
                });
            });
        </script>
        <style type="text/css">
            img.thm {
                cursor: hand;
                cursor: pointer;
            }
        </style>
    </head>
    <body>
        <div id="menu">
            <img class="thm" src="images/test1.png"/>
            <img class="thm" src="images/test2.png"/>
            <img class="thm" src="images/test3.png"/>
        </div>
        <div id="content">
            <img id="main"/>
        </div>
    </body>
</html>

Upvotes: 2

Views: 18800

Answers (3)

Vivek
Vivek

Reputation: 11028

$('img#main').attr('src', $('img:first').attr('src'));

Upvotes: 1

philwinkle
philwinkle

Reputation: 7056

$('img').first().attr('src')

Upvotes: 5

BoltClock
BoltClock

Reputation: 724532

Use .attr() when getting the image source from $('img:first') which is a jQuery object:

$('img#main').attr('src', $('img:first').attr('src'));

The .src property is for the DOM object representing the image. You could use it like this (see .get()):

$('img#main').attr('src', $('img').get(0).src);

But for consistency's sake I would use .attr().

Upvotes: 10

Related Questions