JasonDavis
JasonDavis

Reputation: 48953

Remove some CSS only if JS is supported

I have 2 Divs that I would like to insert a class into ONLY if Javascript is not supported.

So consider this.. one Div has this class="no-js-left" and the other has this class="no-js-right"

What is the most simple way of detecting this and either removing these is JS is support something without using Modernizr?

Also I am using jQuery if that means anything

Upvotes: 1

Views: 118

Answers (3)

BoltClock
BoltClock

Reputation: 723729

Without JavaScript, your markup will remain static. For this to work, you'll have to add the classes to your HTML first, and then remove those classes using JavaScript.

Since you're using jQuery, you can easily take them out with .removeClass():

$('.no-js-left, .no-js-right').removeClass('.no-js-left .no-js-right');

Upvotes: 8

copy
copy

Reputation: 3372

You should also consider using the root elements class name and different CSS selectors like this example:

<html class="js-disabled">
<head>
    <script type="text/javascript">
      document.getElementsByTagName("html")[0].className = "js-enabled";
    </script>

and

.js-enabled .something { /* ... */ }
.js-disabled .something { /* ... */ }

This solution has a couple of advantages over BoltClocks answer:

  1. It's actually faster, because it gets evaluated at the same time as the rendering of your page
  2. You don't depend on jQuery if you want to drop it later ;-)
  3. I would rather have .js-disabled .something than .js-disabled-something (personal preference though)

Upvotes: 1

Virendra
Virendra

Reputation: 2553

Use the following code. If JavaScript is supported by the browser the below code will execute and hide the divs with classes no-js-left and no-js-right.

$(document).ready(function() {
    $('.no-js-left').hide();
    $('.no-js-right').hide();
});

This code will just hide the divs and not actually remove them.

If you want to delete the divs from the page use

$(document).ready(function() {
    $('.no-js-left').remove();
    $('.no-js-right').remove();
});

Update: If you want to just remove the classes then use

$(document).ready(function() {
    $('.no-js-left').removeClass('.no-js-left');
    $('.no-js-right').removeClass('.no-js-right');
});

Upvotes: -1

Related Questions