Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Add and Remove CSS file with one button

I created a button that ADD CSS file to the page header. How Can I REMOVE this CSS from the header with the second click on the same button?

Thanks

<script>
$(document).ready(function(){
  $("#myButton").click(function(){
  var ls = document.createElement('link');
  ls.rel="stylesheet";
  ls.href="myCSSfile.css";
  document.getElementsByTagName('head')[0].appendChild(ls);
    });

});
</script>


<button id="myButton">Add / Remove</button>
like image 718
Ed Nez Avatar asked Sep 27 '26 00:09

Ed Nez


1 Answers

Just add something to identify the style tag, an ID seems appropriate

$(document).ready(function(){
    $("#myButton").on('click', function(){

        if ( $('#myStyle').length === 0 ) { // does not yet exist

            $('<link />', {
                id   : 'myStyle',
                rel  : 'stylesheet',
                href : 'myCSSfile.css'
            }).appendTo('head');

        } else { // exists, remove it

            $('#myStyle').remove();

        }
    });
});
like image 115
adeneo Avatar answered Sep 29 '26 12:09

adeneo



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!