Shahriar Quayser Rafee Shahriar Quayser Rafee - 1 year ago 45
jQuery Question

jQuery ready function for multiple drawings

I am trying to use jQuery

ready
function for multiple ids so that they show and hide individually without writing the same type again and again. When I try to use it on the same line it opens all the drawings all together. The code looks something like this-

<script type="text/javascript">
$(document).ready(function(){
$('#p1','#p2', '#p3','#p4').hide();
$('#p1-show','#p2-show','#p3-show','#p4-show').click(function(){
$('#p1','#p2','#p3','#p4').show();
});
$('#p1-hide','#p2-hide','#p3-hide','#p4-hide').click(function(){
$('#p1','#p2','#p3','#p4').hide();
});
});
</script>

Answer Source

The previous answers will work, but in case there are many such drawings then giving an #id to all those becomes badly repetitive and should be avoided. Following is a code snippet to make it more robust without much hard coded #ids.

$(function(){
    $('.toggle-btn').on('click', function(){
        var root = $(this).closest(".picture-container");
        var img = $(root).find("img");
        $(img).toggle();
    });
});
body > div {
  margin: 10px;
  padding: 10px;
  background-color: #eee;
  border-radius: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    
<div class="picture-container">
  <button class="toggle-btn">Show/Hide</button>
  <div>
     <img src="http://24.media.tumblr.com/tumblr_lggvvf2mCm1qgnva2o1_500.gif">
  </div>
</div>
<div class="picture-container">
  <button class="toggle-btn">Show/Hide</button>
  <div>
     <img src="http://24.media.tumblr.com/tumblr_lggvvf2mCm1qgnva2o1_500.gif">
  </div>
</div>
<div class="picture-container">
  <button class="toggle-btn">Show/Hide</button>
  <div>
     <img src="http://24.media.tumblr.com/tumblr_lggvvf2mCm1qgnva2o1_500.gif">
  </div>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download