onclick button to get image info which is active

I am very new to JavaScript, i have created a image slider , but now i want a button ie: a human and robot, and if click on human button , and the current image is displayed human , i want a alert message ...how to do that ? do i need to store image in array ? total confusing....need asap....

    <code>
<pre>
<html>
<head>
  <script src="jquery-1.12.2.min.js"></script>
  <script src="main.js"></script>
  <script>
    function swapImages(){
      var $active = $('#myGallery .active');
      var $next = ($('#myGallery .active').next().length > 0) ? $('#myGallery .active').next() : $('#myGallery img:first');
      $active.fadeOut(function(){
      $active.removeClass('active');
      $next.fadeIn().addClass('active');
      });
    }

    $(document).ready(function(){
      // Run our swapImages() function every 5secs
      setInterval('swapImages()', 200);
    })
    </script>
  <style>
    #myGallery{
      position:relative;
      width:400px; /* Set your image width */
      height:300px; /* Set your image height */
    }
    #myGallery img{
      display:none;
      position:absolute;
      top:0;
      left:0;
    }
    #myGallery img.active{
      display:block;
    }
  </style>
</head>
<body>
  <div id="myGallery">
    <img src="image1.png" class="active" id="1" />
    <img src="image2.png" />
    <img src="image3.png" />
  </div>
  <button id="bt1" >Human</button>
<button id="bt2" >robot</button>
</body>
</html>
</pre>
</code>

Answers 1

  • Changes Made

    $("#bt1,#bt2").click(function() {
        alert($('img.active').attr('src'));
    });
    

    Working Demo

    function swapImages() {
      var $active = $('#myGallery .active');
      var $next = ($('#myGallery .active').next().length > 0) ? $('#myGallery .active').next() : $('#myGallery img:first');
      $active.fadeOut(function() {
        $active.removeClass('active');
        $next.fadeIn().addClass('active');
      });
    }
    
    $(document).ready(function() {
      $("#bt1,#bt2").click(function() {
        alert($('img.active').attr('src'));
      });
      setInterval(swapImages, 200);
    });
    #myGallery {
      position: relative;
      width: 400px;
      /* Set your image width */
      height: 300px;
      /* Set your image height */
    }
    #myGallery img {
      display: none;
      position: absolute;
      top: 0;
      left: 0;
    }
    #myGallery img.active {
      display: block;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="myGallery">
      <img src="image1.png" class="active" id="1" />
      <img src="image2.png" />
      <img src="image3.png" />
    </div>
    <button id="bt1">Human</button>
    <button id="bt2">robot</button>


Related Articles