Ed Nez Ed Nez - 3 months ago 17
jQuery Question

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>

Answer

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();

        }
    });
});
Comments