Open a <span> when the image loaded by Jquery is loaded

Asked

Viewed 229 times

2

This is the Jquery code: What I want is that when I click the loaded image it displays a span with text at the end of the image.

(function(){

    /* Private variables */

    var overlay = $('<div id="galleryOverlay">'),
        slider = $('<div id="gallerySlider">'),
        prevArrow = $('<a id="prevArrow"></a>'),
        nextArrow = $('<a id="nextArrow"></a>'),
        overlayVisible = false;


    /* Creating the plugin */

    $.fn.touchTouch = function(){

        var placeholders = $([]),
            index = 0,
            allitems = this,
            items = allitems;

        // Appending the markup to the page
        overlay.hide().appendTo('body');
        slider.appendTo(overlay);

        // Creating a placeholder for each image
        items.each(function(){

            placeholders = placeholders.add($('<div class="placeholder">'));
        });

        // Hide the gallery if the background is touched / clicked
        slider.append(placeholders).on('click',function(e){

            if(!$(e.target).is('img')){
                hideOverlay();
            }
        });

        // Listen for touch events on the body and check if they
        // originated in #gallerySlider img - the images in the slider.
        $('body').on('touchstart', '#gallerySlider img', function(e){

            var touch = e.originalEvent,
                startX = touch.changedTouches[0].pageX;

            slider.on('touchmove',function(e){

                e.preventDefault();

                touch = e.originalEvent.touches[0] ||
                        e.originalEvent.changedTouches[0];

                if(touch.pageX - startX == 0){



                }

                else if(touch.pageX - startX > 10){

                    slider.off('touchmove');
                    showPrevious();
                }

                else if (touch.pageX - startX < -10){

                    slider.off('touchmove');
                    showNext();
                }
            });

            // Return false to prevent image
            // highlighting on Android
            return false;

        }).on('touchend',function(){

            slider.off('touchmove');

        });

        // Listening for clicks on the thumbnails
        items.on('click', function(e){

            e.preventDefault();

            var $this = $(this),
                galleryName,
                selectorType,
                $closestGallery = $this.parent().closest('[data-gallery]');

            // Find gallery name and change items object to only have
            // that gallery

            //If gallery name given to each item
            if ($this.attr('data-gallery')) {

                galleryName = $this.attr('data-gallery');
                selectorType = 'item';

            //If gallery name given to some ancestor
            } else if ($closestGallery.length) {

                galleryName = $closestGallery.attr('data-gallery');
                selectorType = 'ancestor';

            }

            //These statements kept seperate in case elements have data-gallery on both
            //items and ancestor. Ancestor will always win because of above statments.
            if (galleryName && selectorType == 'item') {

                items = $('[data-gallery='+galleryName+']');

            } else if (galleryName && selectorType == 'ancestor') {

                //Filter to check if item has an ancestory with data-gallery attribute
                items = items.filter(function(){

                    return $(this).parent().closest('[data-gallery]').length;

                });

            }

            // Find the position of this image
            // in the collection
            index = items.index(this);
            showOverlay(index);
            showImage(index);

            // Preload the next image
            preload(index+1);

            // Preload the previous
            preload(index-1);

        });

        // If the browser does not have support
        // for touch, display the arrows
        if ( !("ontouchstart" in window) ){
            overlay.append(prevArrow).append(nextArrow);

            prevArrow.click(function(e){
                e.preventDefault();
                showPrevious();
            });

            nextArrow.click(function(e){
                e.preventDefault();
                showNext();
            });
        }

        // Listen for arrow keys
        $(window).bind('keydown', function(e){

            if (e.keyCode == 37) {
                showPrevious();
            }

            else if (e.keyCode==39) {
                showNext();
            }

            else if (e.keyCode==27) { //esc
                hideOverlay();
            }

        });


        /* Private functions */


        function showOverlay(index){
            // If the overlay is already shown, exit
            if (overlayVisible){
                return false;
            }

            // Show the overlay
            overlay.show();

            setTimeout(function(){
                // Trigger the opacity CSS transition
                overlay.addClass('visible');
            }, 100);

            // Move the slider to the correct image
            offsetSlider(index);

            // Raise the visible flag
            overlayVisible = true;
        }

        function hideOverlay(){

            // If the overlay is not shown, exit
            if(!overlayVisible){
                return false;
            }

            // Hide the overlay
            overlay.hide().removeClass('visible');
            overlayVisible = false;

            //Clear preloaded items
            $('.placeholder').empty();

            //Reset possibly filtered items
            items = allitems;
        }

        function offsetSlider(index){

            // This will trigger a smooth css transition
            slider.css('left',(-index*100)+'%');
        }

        // Preload an image by its index in the items array
        function preload(index){

            setTimeout(function(){
                showImage(index);
            }, 1000);
        }

        // Show image in the slider
        function showImage(index){

            // If the index is outside the bonds of the array
            if(index < 0 || index >= items.length){
                return false;
            }

            // Call the load function with the href attribute of the item
            loadImage(items.eq(index).attr('href'), function(){
                placeholders.eq(index).html(this);
            });
        }

        // Load the image and execute a callback function.
        // Returns a jQuery object

        function loadImage(src, callback){

            var img = $('<img>').on('load', function(){
                callback.call(img);
            });

            img.attr('src',src);
        }

        function showNext(){

            // If this is not the last image
            if(index+1 < items.length){
                index++;
                offsetSlider(index);
                preload(index+1);
            }

            else{
                // Trigger the spring animation
                slider.addClass('rightSpring');
                setTimeout(function(){
                    slider.removeClass('rightSpring');
                },500);
            }
        }

        function showPrevious(){

            // If this is not the first image
            if(index>0){
                index--;
                offsetSlider(index);
                preload(index-1);
            }

            else{
                // Trigger the spring animation
                slider.addClass('leftSpring');
                setTimeout(function(){
                    slider.removeClass('leftSpring');
                },500);
            }
        }
    };

})(jQuery);
  • No. It is an image gallery display plugin "Touchtouch". What I want is for the moment when the image is magnified next to it to appear superimposed on it a field with explanatory text.

1 answer

4


Preserving the plugin structure Touchtouch, whose demo you can also see here, you can solve your problem as follows:

HTML

In the elements that make up the slider, we will add a new attribute with the text to be used in our <span/> that will be at the bottom of the picture:

<a href="http://example.com/image1.jpg" 
   style="background-image:url(http://example.com/image1_small.jpg)" 
   title="Olá" 
   data-span="Texto da SPAN"   <!-- novo atributo com texto para a <span/> -->
></a>

CSS

Now let’s give a basic formatting to the new element that will be above the image:

#gallerySlider .placeholder span{
    position:absolute;
    display:block;
    bottom:0;
    left:0;
    width:100%;
    height:30px;
    text-align:center;
    color:#FFF;
    font-weight:strong;
}

And for this to work well, we have to position relative to the existing element with the class .placeholder:

#gallerySlider .placeholder{
    /* manter os estilos já atribuídos */
    position:relative;
}

JS

Now, in the code of the plugin, we will add a new instruction in the section responsible for displaying the image, so that after it the new element is also presented <span/>.

First, a function to generate the <span/> and place it at the bottom of the image, standing on top of it:

function loadSpan(target, text) {

    var $span = $('<span/>').html(text);

    target.append($span);

    var $spanInPlace = target.find("span"),
        $targetImage = target.find('img'),
        distanceBot  = target.height() - $targetImage.offset().top - $targetImage.height();

    $spanInPlace.css({"bottom": distanceBot+"px"});   
}

Now we call the function after the image call:

// Call the load function with the href attribute of the item
loadImage(items.eq(index).attr('href'), function(){
    placeholders.eq(index).html(this);

    // 1º parâmetro, o elemento que recebeu a imagem
    // 2º parâmetro, o texto a colocar na SPAN
    loadSpan(placeholders.eq(index), items.eq(index).attr('data-span'));
});

Demonstration

The demo below can also be viewed on Jsfiddle.

/**
 * @name		jQuery touchTouch plugin
 * @author		Martin Angelov
 * @version 	1.0
 * @url			http://tutorialzine.com/2012/04/mobile-touch-gallery/
 * @license		MIT License
 */

(function() {

  /* Private variables */

  var overlay = $('<div id="galleryOverlay">'),
    slider = $('<div id="gallerySlider">'),
    prevArrow = $('<a id="prevArrow"></a>'),
    nextArrow = $('<a id="nextArrow"></a>'),
    overlayVisible = false;


  /* Creating the plugin */

  $.fn.touchTouch = function() {

    var placeholders = $([]),
      index = 0,
      items = this;

    // Appending the markup to the page
    overlay.hide().appendTo('body');
    slider.appendTo(overlay);

    // Creating a placeholder for each image
    items.each(function() {
      placeholders = placeholders.add($('<div class="placeholder">'));
    });

    // Hide the gallery if the background is touched / clicked
    slider.append(placeholders).on('click', function(e) {
      if (!$(e.target).is('img')) {
        hideOverlay();
      }
    });

    // Listen for touch events on the body and check if they
    // originated in #gallerySlider img - the images in the slider.
    $('body').on('touchstart', '#gallerySlider img', function(e) {

      var touch = e.originalEvent,
        startX = touch.changedTouches[0].pageX;

      slider.on('touchmove', function(e) {

        e.preventDefault();

        touch = e.originalEvent.touches[0] ||
          e.originalEvent.changedTouches[0];

        if (touch.pageX - startX > 10) {
          slider.off('touchmove');
          showPrevious();
        } else if (touch.pageX - startX < -10) {
          slider.off('touchmove');
          showNext();
        }
      });

      // Return false to prevent image 
      // highlighting on Android
      return false;

    }).on('touchend', function() {
      slider.off('touchmove');
    });

    // Listening for clicks on the thumbnails

    items.on('click', function(e) {
      e.preventDefault();

      // Find the position of this image
      // in the collection

      index = items.index(this);
      showOverlay(index);
      showImage(index);

      // Preload the next image
      preload(index + 1);

      // Preload the previous
      preload(index - 1);

    });

    // If the browser does not have support 
    // for touch, display the arrows
    if (!("ontouchstart" in window)) {
      overlay.append(prevArrow).append(nextArrow);

      prevArrow.click(function(e) {
        e.preventDefault();
        showPrevious();
      });

      nextArrow.click(function(e) {
        e.preventDefault();
        showNext();
      });
    }

    // Listen for arrow keys
    $(window).bind('keydown', function(e) {

      if (e.keyCode == 37) {
        showPrevious();
      } else if (e.keyCode == 39) {
        showNext();
      }

    });


    /* Private functions */


    function showOverlay(index) {

      // If the overlay is already shown, exit
      if (overlayVisible) {
        return false;
      }

      // Show the overlay
      overlay.show();

      setTimeout(function() {
        // Trigger the opacity CSS transition
        overlay.addClass('visible');
      }, 100);

      // Move the slider to the correct image
      offsetSlider(index);

      // Raise the visible flag
      overlayVisible = true;
    }

    function hideOverlay() {
      // If the overlay is not shown, exit
      if (!overlayVisible) {
        return false;
      }

      // Hide the overlay
      overlay.hide().removeClass('visible');
      overlayVisible = false;
    }

    function offsetSlider(index) {
      // This will trigger a smooth css transition
      slider.css('left', (-index * 100) + '%');
    }

    // Preload an image by its index in the items array
    function preload(index) {
      setTimeout(function() {
        showImage(index);
      }, 1000);
    }

    // Show image in the slider
    function showImage(index) {

      // If the index is outside the bonds of the array
      if (index < 0 || index >= items.length) {
        return false;
      }

      // Call the load function with the href attribute of the item
      loadImage(items.eq(index).attr('href'), function() {
        placeholders.eq(index).html(this);
        loadSpan(placeholders.eq(index), items.eq(index).attr('data-span'));

      });
    }

    // Load the image and execute a callback function.
    // Returns a jQuery object

    function loadImage(src, callback) {
      var img = $('<img>').on('load', function() {
        callback.call(img);
      });

      img.attr('src', src);
    }

    function loadSpan(target, text) {

      var $span = $('<span/>').html(text);

      target.append($span);

      var $spanInPlace = target.find("span"),
        $targetImage = target.find('img'),
        distanceBot = target.height() - $targetImage.offset().top - $targetImage.height();

      $spanInPlace.css({
        "bottom": distanceBot + "px"
      });
    }

    function showNext() {

      // If this is not the last image
      if (index + 1 < items.length) {
        index++;
        offsetSlider(index);
        preload(index + 1);
      } else {
        // Trigger the spring animation

        slider.addClass('rightSpring');
        setTimeout(function() {
          slider.removeClass('rightSpring');
        }, 500);
      }
    }

    function showPrevious() {

      // If this is not the first image
      if (index > 0) {
        index--;
        offsetSlider(index);
        preload(index - 1);
      } else {
        // Trigger the spring animation

        slider.addClass('leftSpring');
        setTimeout(function() {
          slider.removeClass('leftSpring');
        }, 500);
      }
    }
  };

})(jQuery);

$(function() {

  // Initialize the gallery
  $('#thumbs a').touchTouch();

});
/* The gallery overlay */

#galleryOverlay {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  opacity: 0;
  z-index: 100000;
  background-color: #222;
  background-color: rgba(0, 0, 0, 0.8);
  overflow: hidden;
  display: none;
  -moz-transition: opacity 1s ease;
  -webkit-transition: opacity 1s ease;
  transition: opacity 1s ease;
}


/* This class will trigger the animation */

#galleryOverlay.visible {
  opacity: 1;
}

#gallerySlider {
  height: 100%;
  left: 0;
  top: 0;
  width: 100%;
  white-space: nowrap;
  position: absolute;
  -moz-transition: left 0.4s ease;
  -webkit-transition: left 0.4s ease;
  transition: left 0.4s ease;
}

#gallerySlider .placeholder {
  background: url("preloader.gif") no-repeat center center;
  height: 100%;
  line-height: 1px;
  text-align: center;
  width: 100%;
  display: inline-block;
  position: relative;
}


/* The before element moves the
 * image halfway from the top */

#gallerySlider .placeholder:before {
  content: "";
  display: inline-block;
  height: 50%;
  width: 1px;
  margin-right: -1px;
}

#gallerySlider .placeholder img {
  display: inline-block;
  max-height: 100%;
  max-width: 100%;
  vertical-align: middle;
}

#gallerySlider .placeholder span {
  position: absolute;
  display: block;
  bottom: 0;
  left: 0;
  height: 30px;
  width: 100%;
  text-align: center;
  color: #FFF;
  font-weight: strong;
}

#gallerySlider.rightSpring {
  -moz-animation: rightSpring 0.3s;
  -webkit-animation: rightSpring 0.3s;
}

#gallerySlider.leftSpring {
  -moz-animation: leftSpring 0.3s;
  -webkit-animation: leftSpring 0.3s;
}


/* Firefox Keyframe Animations */

@-moz-keyframes rightSpring {
  0% {
    margin-left: 0px;
  }
  50% {
    margin-left: -30px;
  }
  100% {
    margin-left: 0px;
  }
}

@-moz-keyframes leftSpring {
  0% {
    margin-left: 0px;
  }
  50% {
    margin-left: 30px;
  }
  100% {
    margin-left: 0px;
  }
}


/* Safari and Chrome Keyframe Animations */

@-webkit-keyframes rightSpring {
  0% {
    margin-left: 0px;
  }
  50% {
    margin-left: -30px;
  }
  100% {
    margin-left: 0px;
  }
}

@-webkit-keyframes leftSpring {
  0% {
    margin-left: 0px;
  }
  50% {
    margin-left: 30px;
  }
  100% {
    margin-left: 0px;
  }
}


/* Arrows */

#prevArrow,
#nextArrow {
  border: none;
  text-decoration: none;
  background: url('arrows.png') no-repeat;
  opacity: 0.5;
  cursor: pointer;
  position: absolute;
  width: 43px;
  height: 58px;
  top: 50%;
  margin-top: -29px;
  -moz-transition: opacity 0.2s ease;
  -webkit-transition: opacity 0.2s ease;
  transition: opacity 0.2s ease;
}

#prevArrow:hover,
#nextArrow:hover {
  opacity: 1;
}

#prevArrow {
  background-position: left top;
  left: 40px;
}

#nextArrow {
  background-position: right top;
  right: 40px;
}

#thumbs {
  width: 480px;
  margin: 60px auto 35px;
  text-align: center;
}

#thumbs a {
  width: 120px;
  height: 120px;
  display: inline-block;
  border: 7px solid #303030;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
  border-radius: 4px;
  margin: 6px 6px 40px;
  position: relative;
  text-decoration: none;
  background-position: center center;
  background-repeat: no-repeat;
  background-size: cover;
  -moz-background-size: cover;
  -webkit-background-size: cover;
}

#thumbs a:after {
  background-color: #303030;
  border-radius: 7px;
  bottom: -136px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
  color: #FFFFFF;
  content: attr(title);
  display: inline-block;
  font-size: 10px;
  max-width: 90px;
  overflow: hidden;
  padding: 2px 10px;
  position: relative;
  text-align: center;
  white-space: nowrap;
}

#credit {
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  font-size: 11px;
  margin: 0 auto 70px;
  opacity: 0.5;
  padding: 12px 16px;
  text-align: center;
  width: 400px;
}


/*----------------------------
	Media Queries
-----------------------------*/

@media screen and (max-width: 960px) {
  #thumbs,
  #credit {
    width: auto;
  }
  footer {
    display: none;
  }
  #bsaHolder {
    display: none;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="thumbs">
  <a href="http://farm8.staticflickr.com/7013/6754656011_3de2cc73a2_z.jpg" style="background-image:url(http://farm8.staticflickr.com/7013/6754656011_3de2cc73a2_m.jpg)" title="Lion Rock" data-span="bubu 1"></a>
  <a href="http://farm8.staticflickr.com/7042/6895252645_45f5dfffaa_z.jpg" style="background-image:url(http://farm8.staticflickr.com/7042/6895252645_45f5dfffaa_m.jpg)" title="Holsten Gate" data-span="bubu 2"></a>
  <a href="http://farm8.staticflickr.com/7183/6943277737_21b521659c_z.jpg" style="background-image:url(http://farm8.staticflickr.com/7183/6943277737_21b521659c_m.jpg)" title="Blue Hour" data-span="bubu 3"></a>
  <a href="http://farm8.staticflickr.com/7047/7000951429_5eae078a62_z.jpg" style="background-image:url(http://farm8.staticflickr.com/7047/7000951429_5eae078a62_m.jpg)" title="Waikato Landscape" data-span="bubu 4"></a>
  <a href="http://farm6.staticflickr.com/5346/7051537899_efc7a44830_z.jpg" style="background-image:url(http://farm6.staticflickr.com/5346/7051537899_efc7a44830_m.jpg)" title="Tauranga Bridge" data-span="bubu 5"></a>
  <a href="http://farm8.staticflickr.com/7268/6951148260_440661b4d1_z.jpg" style="background-image:url(http://farm8.staticflickr.com/7268/6951148260_440661b4d1_m.jpg)" title="East Coast" data-span="bubu 6"></a>
  <a href="http://farm8.staticflickr.com/7259/6930112984_5fcc076288_z.jpg" style="background-image:url(http://farm8.staticflickr.com/7259/6930112984_5fcc076288_m.jpg)" title="Cathedral Cove" data-span="bubu 7"></a>
  <a href="http://farm8.staticflickr.com/7276/6886626710_047cd03acb_z.jpg" style="background-image:url(http://farm8.staticflickr.com/7276/6886626710_047cd03acb_m.jpg)" title="The Pond" data-span="bubu 8"></a>
  <a href="http://farm8.staticflickr.com/7020/6683299491_f2b5f6aa8b_z.jpg" style="background-image:url(http://farm8.staticflickr.com/7020/6683299491_f2b5f6aa8b_m.jpg)" title="Good Night" data-span="bubu 9"></a>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.