1

I have got 21 images inside multiple divs. Below is an example of the images.

<img src="fruits/lychee.png" class ="fruit" id="fruitl156">
<img src="fruits/cranberry.png" class ="fruit" id="fruitl141">
<img src="fruits/avocado.png" class ="fruit" id="fruitl214">

When the page loads 3 - 6 random images will be visible. Now I want to be able to know which images are visible by its id. So basically I want to pass the id of each visible image on to a function.

This is what I did. But its not doing as expected. Not all visible image id's are passed. How can I identify the visible images and be able to pass each of their IDs to the passFunction() ?

$('#getIDs').click(function(){
   if( $('.fruit').css('visibility', 'visible') ){
       passFunction( $(this.id) );
   }
});
Bekki
  • 719
  • 2
  • 12
  • 20

3 Answers3

2

Try using this pseudo :visible on document load (am assuming the images are created randomly when the document loads) as follows:

$('.fruit:visible').each(function(){
       passFunction( $(this).attr("id") );
});
KAD
  • 10,972
  • 4
  • 31
  • 73
  • 1
    It actually doesn't matter for the id, since both (attr and prop) are gonna have the same value and are not manipulated by any user interaction. Prop is better used with form elements to set/get the element values since attr will fail sometimes.. Though it can surely be used here. – KAD Aug 03 '15 at 19:29
1

This is done easily with :visible and .each()

$('#getIDs').click(function(){
    $('.fruit:visible').each(function (){
       passFunction( $(this.id) );
   });
});

BUT

the :visible selector might not select all the "invisible" images. (example images that are visible but are off screen)

Ziv Weissman
  • 4,400
  • 3
  • 28
  • 61
0

As leonid mentioned if your code is showing/hiding image elements you can use :visible selector with any of above code examples. You would also need to lookout how images are being shown/hidden. If it is controlled by opacity or visibility css styling it will come in visible images ids even if not shown on screen. If it has css styling as display:none it wont get caught in :visible selector that is what I noted in jquery visible selector example. You can refer to https://api.jquery.com/visible-selector/

pratikpawar
  • 2,038
  • 2
  • 16
  • 20