How to Write Jquery If Else Statement?

This code shows frm01:

$(document).ready(function() {
$("#reg").click(function () {
$("#frm01").show("slide", { direction: "down" }, 1000);
});
});

But I want to hide frm01 if it is allready visible, and vice versa. How could I do this, please ?

4 Answers

Try jQuery's toggle() method:

$(function() {
    $("#reg").click(function () {
        $("#frm01").toggle(1000);
    });
});

You don't need jQuery to use if-else statements; Javascript implements those natively...

$(function() {
    $("#reg").click(function () {
        if ($("#frm01").is(":visible"))
            $("#frm01").slideUp(1000);
        else
            $("#frm01").slideDown(1000);
    });
});
1

try this:

$(document).ready(function() {
   $("#reg").click(function () {
    if ($("#frm01").is(':hidden')) {
      $("#frm01").show("slide", { direction: "down" }, 1000);
    } else {
      $("#frm01").hide(1000);
    }
  });
});
  $("#reg").on('click', function () {
    $("#frm01:hidden").show("slide", { direction: "down" }, 1000);
    $("#frm01:visible").hide("slide", { direction: "up" }, 1000);
  });

or

  $("#reg").toggle(
    function () {
      $("#frm01").show("slide", { direction: "down" }, 1000);
    },
    function(){
      $("#frm01").hide("slide", { direction: "up" }, 1000);
    }
  );

should also work

You can use $.toggle() method to show and hide. Some time need to identify whether elements are hide or show.

$("#reg").click(function () {
if($("#frm01").hasClass('fram1-slide-on')){
    $("#frm01").hide();
    $("#frm01").removeClass('fram1-slide-on');
}   else {
    $("#frm01").show("slide", { direction: "down" }, 1000);
    $("#frm01").addClass('fram1-slide-on');
}

});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest