Skip to content Skip to sidebar Skip to footer

How 2 To Merge Two Functions In Javascript For Same Div

The below code is working fine, but i want merge checked and click functions in single function. Is it possible? $(function () { if($('#enablepromo0').is(':checked')) $('

Solution 1:

Use the change event and trigger it, it can then detect the current state of the checkbox. I altered the code to toggle a class instead to avoid a "flash" initially.

$(function() {
  $("#enablepromo0").on('change', function() {
    let isChecked = !this.checked;
    $("#PromoPanel").toggleClass("hidden", isChecked, {
      duration: 300
    });
  }).trigger('change');
});
.panel {
  border: solid lime 1px;
  background: #ddffdd;
}

.hidden {
  display: none;
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
Check to show: <inputtype="checkbox"id='enablepromo0' /><divclass="container"><divid="PromoPanel"class="panel hidden"><h2>Hi There</h2>Get stoked</div></div>

Solution 2:

both function do the same job so i changed something to show an alert:

$(function () {  

$("#enablepromo0").click(function () {
     alert("dddddd")
  if($("#enablepromo0").is(":checked"))   
     $("#PromoPanel").show(300);
  else
    $("#PromoPanel").hide(300); 
        });

 


  
});
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script><inputtype="checkbox"id='enablepromo0'/><divid="PromoPanel"style="border: 1px solid  red; width:50px; heigth:50px; display:none;">uuu</div>

Solution 3:

Move the code to its own function and call as required:

functionshowHide() {
  if ($("#enablepromo0").is(":checked"))   
     $("#PromoPanel").show(300);
  else
    $("#PromoPanel").hide(300);
}

$(function () { 
  showHide();

  $("#enablepromo0").click(function () {
    showHide();
  });
});

Post a Comment for "How 2 To Merge Two Functions In Javascript For Same Div"