Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply/Remove Css on button

On clicking "Show/Hide Submit" button the "Submit" button need to be shown and hidden. My code is working but is there a better way of doing it [Javascript part alone]

<style type="text/css">
    .displayNone{
        display : none;
    }
    </style>



    <button id="sub" >Submit</button>
    <button id="control">Show/Hide Submit</button>

    <script type="text/javascript">

    $( document ).ready(function() {
        $("#control").click(function(){
        if($("#sub").attr("class") == "displayNone"){
            $("#sub").attr("class","")
        }
        else{
            $("#sub").attr("class","displayNone")
        }

        }); 
    });
    </script>

2 Answers

Hope you are not aware of .toggleClass() predefined method :) Try the below code

$( document ).ready(function() {
    $("#control").click(function(){
    $("#sub").toggleClass("displayNone");
    }); 
});
like image 54
Nofi Avatar answered Apr 11 '26 00:04

Nofi


As a possible improvement to @Nofi's answer, you could cache the "#sub" jQuery object in between clicks :) (It saves you having to find the element everytime)

$( document ).ready(function() {
    var $sub = $('#sub');
    $("#control").click(function(){
       $sub.toggleClass("displayNone");
    }); 
});
like image 44
Ruben Serrate Avatar answered Apr 11 '26 00:04

Ruben Serrate



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!