Search code examples
htmlhref

Auto load an image into a <div> from a href out of a different <div>


So i have two div's. Code below.

<div class="picture">

</div><!-- end picture -->

<div class="gallery">
    <a href="link-to-image01.jpg"><img src="mythumnail01.jpg" /></a>
    <a href="link-to-image02.jpg"><img src="mythumnail02.jpg" /></a>
    <a href="link-to-image03.jpg"><img src="mythumnail03.jpg" /></a>
</div><!-- end gallery -->

When the pages loads, i'd like the first "href" from the "div.gallery" to show in the "div.picture".

The gallery is manageable, so the thumbnails in the ".gallery" may end up changing. That is why I would like to look at the first "href" within "div.gallery" and display it in "div.picture".

Is something like this possible? I have some code at the moment that loads the "div.gallery"'s "href" into it on a click event. But cant work out how to do it automatically without clicking. The code for that is below.

<script>
    $(document).ready(function () {
        $("div.gallery a").click(function (event) {
            event.preventDefault();
            $("div.picture").html($("<img>").attr("src", this.href).fadeIn(1000));
        });
    });
</script>

Thanks in advanced.


Solution

  • You may try access the first <a> with JQuery:

    $(document).ready(function () {
        var href = $('div.gallery a').get(0).href;
        $('div.picture').html($('<img>').attr('src', href).fadeIn(1000));
    })