treehouse : what would you like to learn today?
Web Design Web Development iOS Development

text overlay

  • I''m attempting to write a little javascript function which will display an overlay with some text when an image is clicked on. I've created an array variable which holds the different text descriptions. the index should correspond to the image e.g. image 0 will correspond to the 1st item in the text array and so forth. how do i find out which child of the parent node "photoWrap" has been clicked on? if I know which child it is, I can use that as the index to the overlayText array - or do you have a better way of associating the image with the text?
    The html is
    <div id="overlayDiv"></div>
    <div id="photoWrap">
    <a href='#'><img src="images/snap0th.jpg" name="lhPhotos" class="shadow"></a>
    <a href='#'><img src="images/snap1th.jpg" name="lhPhotos" class="shadow"></a>
    <a href='#'><img src="images/snap2th.jpg" name="lhPhotos" class="shadow"></a>
    <a href='#'><img src="images/snap3th.jpg" name="lhPhotos" class="shadow"></a>
    <a href='#'><img src="images/snap4th.jpg" name="lhPhotos" class="shadow"></a>
    <a href='#'><img src="images/snap5th.jpg" name="lhPhotos" class="shadow"></a>
    <a href='#'><img src="images/snap6th.jpg" name="lhPhotos" class="shadow"></a>
    </div>


    the javascript is
    <script type="text/javascript">
    //this function overlays a description when a photo is clicked
    function showOverlay{
    var overlayText = new Array(7);
    overlayText[0] = "text for image 0!";
    overlayText[1] = "text for image 1";
    overlayText[2] = "text for image 2";
    overlayText[3] = "text for image 3";
    overlayText[4] = "text for image 4";
    overlayText[5] = "text for image 5";
    overlayText[6] = "text for image 6";

    overlayDiv.style.display = "block";
    overlayDiv.innerHTML = "<p>" + overlayText[imageNum] + "</p><p><a href='#'onclick='return hideOverlay();'>[close window]</a></p>";
    return false;
    }

    function hideOverlay(){
    overlayDiv.style.display = "none";
    overlayDiv.innerHTML = '';
    }


    // some jQuery to make the showOverlay more efficient by using event delegation instead of the onClick function
    $(function () {
    // When the the photoWrap div is clicked
    $('#photoWrap').click(function (e) {
    // work out which child element specifically was clicked.
    var jQtarget = $(e.target);
    // If an anchor tag or something inside an anchor tag was clicked
    if (jQtarget.is('a') || jQtarget.parents('a').size()) {
    //stop the anchor tag taking us anywhere
    e.preventDefault();
    // show the overlay.
    showOverlay(imageNum);
    }
    });
    });

    </script>

  • Rather than create arrays, I would prefer to insert the text of the attributes within the image itself: http://jsfiddle.net/tovic/26kWr/
  • yes, using the alt attribute is an easier way, thanks.