RoyS RoyS - 13 days ago 6
jQuery Question

One toggled image displayed at a time

In a Joomla page I have icons which when clicked toggle an image. This is the jQuery script (courtesy of guradio "Toggling between icon and larger image with transition" - April12 '16):

jQuery(document).ready(function() {
jQuery('img.do_things').on('click', function(evnt) {
var image_path = jQuery('p#image_path').html(),
image1_src = image_path.substring(0, 26) + 'scene_icon' + '.png',
elementId = evnt.target.id,
image2_src = image_path + elementId + '.png',
origsrc = jQuery(this).attr('src'),
src = '';
origsrc === image1_src ? src = image2_src : src = image1_src; //toggle between the src
jQuery(this).fadeOut(800, function() {
jQuery(this).attr('src', src); //set src
}).fadeIn(1200);
});
});


The html for the image path is:

<p id="image_path">/templates/beez_20/images/doing_things/</p>


At present, any images that are displayed remain displayed whether or not other icons are clicked. So it is possible that in a page with 5 icons, 5 images can be displayed simultaneously. I want to change this so that only one image is displayed at any one time. I've tried to work out the logic for this using variables as flags, but with no success. Any help would be much appreciated.

Answer

Write a function that converts an image back to its icon form:

function make_icon(img) {
    var image_path = jQuery('p#image_path').html(),
      src = image_path.substring(0, 26) + 'scene_icon' + '.png';
    if (img.attr('src') != src) {
        img.fadeOut(800, function() {
            img.attr('src', src);
        }).fadeIn(1200);
    }
}

And call it on all the other images.

jQuery(document).ready(function() {
  jQuery('img.do_things').on('click', function(evnt) {
    var image_path = jQuery('p#image_path').html(),
      image1_src = image_path.substring(0, 26) + 'scene_icon' + '.png',
      elementId = evnt.target.id,
      image2_src = image_path + elementId + '.png',
      origsrc = jQuery(this).attr('src'),
      src = '';
      origsrc === image1_src ? src = image2_src : src = image1_src;      //toggle between the src
      jQuery('img.do_things').not(this).each(function(i, img) {
        make_icon($(img));
      });
      jQuery(this).fadeOut(800, function() {
        jQuery(this).attr('src', src);      //set src
      }).fadeIn(1200);
  });
});