Search code examples
jqueryfunctioneachgsap

Simple jQuery Each Function


I have a codePen that has a simple setup. I am trying to get the appropriate button to click to reveal the appropriate image. We have a 'red box' that should reveal only the 1st image, and a 'green box' that should reveal only the 2nd image.

I know I can do this with simple javascript clicks--but I will have a lot of boxes on the page, and I want to do some sort of an each loop that will know which square I clicked on to reveal the right image associated with that square.

How can I set this up properly, so that I can have one click function that knows which square I've clicked to reveal the correct image ? I added some 'data' attributes to each image, thinking maybe I can reference that somehow with an each function...I'm just not exactly sure how to do that!

Here's the codePen to see what I mean

//reveal the appropriate large image here with javascript.
//Maybe I can use an array to choose the correct image?
//But how will the click function know which one to reveal ?
//Maybe an 'each' function can help,
//but I'm not sure how to set that up properly...

var correctImage = ["#img1", "#img2"];

$(".box").click(function( event ) {
  var largeImages = new TimelineMax();
  largeImages.set(correctImage, {css:{display: "block"}})
        .from(correctImage, 1, {autoAlpha:0, ease:Sine.easeOut});

});

// just a reset button here
$(".reset").click(function( event ) {
  var largeImages2 = new TimelineMax();
  largeImages2.set(correctImage, {clearProps: "all"});

});

Solution

  • It is rather simple. I will add an example of html below with javascript to demonstrate how to know which button was clicked.

    .my_image {
        display: none;
    }
    
    <a class="my_button" data-id="1">Test button 1</a>
    <a class="my_button" data-id="2">Test button 2</a>
    <a class="my_button" data-id="3">Test button 3</a>
    
    <img class="my_image" data-id="1" src="http://blog.jelanieshop.com/wp-content/uploads/2012/07/girl-laughing.jpg" />
    <img class="my_image" data-id="2" src="http://thumbs.dreamstime.com/x/laughing-girl-1938830.jpg" />
    <img class="my_image" data-id="3" src="http://dailyplateofcrazy.com/wp-content/uploads/2014/09/Beautiful-Girl-Laughing.jpg" />
    

    The magic:

    $(".my_button").click(function(){
        $(".my_image[data-id="+$(this).attr("data-id")+"]").show();
    });
    

    I hope this answers your question or at least helps you.