Obtaining the ID of an IMG tag in jQuery

I have the following code (in this case for two images - but in reality, it could be replicated N times:

<figure title="" class="DragBox" dragableBox="true" style="opacity: 1;" id="thumb_1">
   <span class="pic" id='UAJ754'>
      <span class="imagewrap">&nbsp;</span>
    <span class="overlay">
      <a href="fulldata.php?UAJ754" class="popUpSimple" rel="thumb_1">Image Information</a>
    </span>
    <img src="/pics/UAJ754.jpg" alt="">
  </span>

  <figcaption class="AlbumFig_Caption">A picture caption.
  </figcaption>
</figure>
<figure title="" class="DragBox" dragableBox="true" style="opacity: 1;" id="thumb_2">
   <span class="pic" id='JB6732'>
      <span class="imagewrap">&nbsp;</span>
    <span class="overlay">
      <a href="fulldata.php?JB6732" class="popUpSimple" rel="thumb_2">Image Information</a>
    </span>
    <img src="/pics/JB6732.jpg" alt="">
  </span>

  <figcaption class="AlbumFig_Caption">A second picture caption.
  </figcaption>
</figure>

Now the span which has the class of 'pic' has a jQuery mousedown event associated with it - so that it doesn't matter which image the mouse is clicked on, the pic tag will log the event and display a popup window with data. That all works fine.

But I need to obtain either the ID tag of the specific 'pic' that had the mouse down, or retrieve the src of the IMG so i can get the ID, as this needs to be passed to the popup window to display the correct info for the right picture.

I have the following JS code:

            $(".pic").mousedown(function(e) {   

                var mouseX = e.pageX; 
                var mouseY = e.pageY;

            if (e.which === 3) {                    

               $('.infobox').css({'top':mouseY+'px','left':mouseX+'px'}).fadeIn();

               var imgref = $(".pic").attr('id');
               alert (imgref);

               return false;
            }else{
               $('.info').fadeOut();
            }
        });

Again, this works fine, but it only gives me the ID of the first 'pic' span no matter which 'pic' span is clicked. How can I get the ID field of the current 'pic' span ... the one that the mouse was over when the use pressed the button??

Answers


var imgref = $('img', this).attr('src');

you will get the src of the IMG.


try:

var imgref = $(this).attr('id');

or:

var imgref = $(this).prop('id');

instead of :

var imgref = $(".pic").attr('id');

$(".pic") will give the first div that have the class pic not the one you clicked on


var imgref =this.id;

because this is also an object and $(this) is wrapping an object in another object;


Instead of using var imgref = $(".pic").attr('id');

Use this: var imgref = $(this).attr('id');


Need Your Help

How to deep copy a list?

python list copy deep-copy

I have some problem with a List copy: