Efficiently toggle visibility on multiple images

91 views Asked by At

I have a chat web application that needs a hide/show avatars in chat setting.

How would you go about it an efficient way? So that you could easily show the images back and without parsing all the images.

Posting this question and answering it for those who, as me, are in need of something like this

2

There are 2 answers

0
Daniel Andrei On BEST ANSWER

Some might think it is ok to hide/show the images by querying like this :

Assuming class .hide {display: none} and default display state of an image is block.

Example code :

 var images = document.querySelectorAll('.images');

 images.toggleClass('hide');

While this will work you would have to go through all the images which is constly.

A better way would be to grab the container of the images and make the images hide/show based on a class that could be toggled on the container itself.

Example code :

Having the following CSS :

.hide .images {display: none;}

and the following jQuery :

function toggleImages() { 

   var container = $('#container');

   container.toggleClass('hide'); 

}

The end result would be this : The class would be toggled on the container and the css style would apply the changes.

Hope someone finds this helpful!An application of this would be the setting for a chat user to toggle the avatars in chat.

0
Myk Klemme On

Here's a quick example of a link that toggles image visibility

HTML

<img src="http://placehold.it/50/50" class="img">
<img src="http://placehold.it/50/50" class="img">
<img src="http://placehold.it/50/50" class="img">

<a href="#" class="toggle">Toggle images</a>

jQuery

$(".toggle").click( function(e) {

    // Don't show # in url
    e.preventDefault()

    // The content to toggle
   $(".img").toggle()
})

Example: http://jsfiddle.net/d0a7xofn/