Search code examples
jqueryimagesrcattralt

How do I get the image? attr JQuery


I've been trying to get an image src with JQuery for a while but it's still not happening ...

$(document).ready(function(){

var modall = $(".myModal");
var img = $(".myImg");
var modalImg = $(".img01");
var captionText = $(".caption");
var span = $(".close-img");

    img.click(function(){
        modall.css( 'display', 'block' );
        modalImg.attr( 'src' );
        captionText.attr( 'alt' );
    });

    span.click(function(){
      modall.css( 'display', 'none' );
    });

});

This is the code I'm trying to get 'src' and 'alt' on the 'myImg' image.

        <img class="myImg" src="<?php print $row['simg5']; ?>" alt="<?php print $row['title']; ?>" width="300" height="200" />
    <div class="image myModal">
        <span class="close-img">&times;</span>
        <img class="image-content img01" >
        <div class="caption"></div>
    </div>

And this is the code that I embed the SQL image itself.

How do I take 'src' to 'MyImg' and get the image?

Thanks !


Solution

  • You're not actually setting values with the following lines:

    modalImg.attr( 'src' );
    captionText.attr( 'alt' );
    

    You need to pass in the value you would like to change that attribute to, otherwise you just return the current value of that attribute.

    You'll need to change this block like so to pass in the src/alt of the clicked img:

    img.click(function(){
        modall.css( 'display', 'block' );
        modalImg.attr('src', $(this).attr('src'));
        captionText.attr('alt', $(this).attr('alt'));
    });
    

    See here for more details: http://api.jquery.com/attr/

    Hope that helps.