Beppe
Beppe

Reputation: 207

Add element styling when JavaScript is disabled

I'm trying to avoid adding online styling when JS is being disabled. For example, I'd like to hide an element in the body when JS is disabled, but i'd like to do it from external CSS only.

I'd like to avoid adding style like below

<noscript>
    <style>
    ...some style
    </style>

    <p class="no-js">You need Javascript enabled to view all of the content on this page.</p>
</noscript>

<body>
    <div>element to hide when js disabled</div>
</body>

Is there an alternative to this? Thanks!

Upvotes: 1

Views: 515

Answers (4)

Mi-Creativity
Mi-Creativity

Reputation: 9654

" I'd like to hide an element in the body when JS is disabled "

You can create a class with display:none, assign it to all elements you want to hide if javascript is disabled, and through javascript remove this class from these elements, if javascript is disabled, then this class will always apply and all elements with this class are not displayed

JS Fiddle

var secrets = document.querySelectorAll('.secret');
for (var i in secrets) {
  secrets[i].classList.remove('secret');
}
.secret {
  display: none;
}

Upvotes: 1

sg.cc
sg.cc

Reputation: 1816

Alternatively, just use Javascript to hide the div that tells users that they need js enabled (if Javascript is disabled, obviously it cannot hide the div, and it will be shown).

<script>

  document.addEventListener("DOMContentLoaded", function() { 
    document.getElementById('nojs').style.display = "none";
  });

</script>

Upvotes: 0

Pedram
Pedram

Reputation: 16575

You should use <noscript> tag, for hide an element, in <style> tag make it display:none. there is no way to this with standalone css! but you can do this with javascript or etc, look other answer.

<noscript>
    <style type="text/css">
        .divtohide {display:none;}
    </style>
    <div class="divtohide">
    Javascript is disabled!
    </div>
</noscript>

Upvotes: 0

Will Lamerton
Will Lamerton

Reputation: 76

Try this code:

<noscript>
  <style>
     #foo {
        display:none;
     }
  </style>
</noscript>

Upvotes: 0

Related Questions