user3216933
user3216933

Reputation: 275

Removing <div> if Javascript is disabled

I have a list that is part of a larger menu:

<ul>
<li>Menu Item 1</li>
<li>Menu Item 2</li>
<li>Menu Item 3</li>
</ul>

I want to hide the list completely IF Javascript is disabled in the web browser.

I tried one solution that works, but it uses the noscript element within head, which is not compliant with XHTML. I'm seeking a solution that complies with XHTML.

Upvotes: 4

Views: 430

Answers (4)

TheYaXxE
TheYaXxE

Reputation: 4294

You can hide the ul with css, and then use javascript to show it.

In this way, the ul will not show if the javascript is disabled, because it is hidden my the css.

jQuery Way:

HTML:

<ul>
    <li>Menu Item 1</li>
    <li>Menu Item 2</li>
    <li>Menu Item 3</li>
</ul>

CSS:

ul {
    display: none;
}

jQuery:

$(document).ready(function() }
   $('ul').show();
});

When using jQuery, remember to put the jQuery libery in the <head> section of your pages:

<script src="http://code.jquery.com/jquery-latest.min.js"></script>

jQuery Fiddle


Plain Javascript Way:

If you don't want to use jQuery, but plain javascript you can add an ID to your <ul> and then show it with javascript like this:

HTML:

<ul id="menu">
    <li>Menu Item 1</li>
    <li>Menu Item 2</li>
    <li>Menu Item 3</li>
</ul>

CSS:

ul {
    display: none;
}

Javascript:

document.getElementById('menu').style.display = "block";

Plain Javascript Fiddle

Upvotes: 2

user2968831
user2968831

Reputation:

You might be better going the other way and only displaying it if javascript is enabled.

Create a class something like the below...

.JSenabled {display:none}

Toggle class on $(document).ready() using $('.JSenabled').show().

Add this class to any elements you want to hide when JS is unavailable.

You'll also need to link the jQuery library.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

Upvotes: 6

qwertynl
qwertynl

Reputation: 3933

You can add a "hidden" css id and then only show that object if javascript if enabled:

HTML:

<div class="hidden" id="hiddenDiv">
  <ul>
    <li>Menu Item 1
    <li>Menu Item 2
    <li>Menu Item 3
  </ul>
</div>

CSS:

#hiddenDiv{
  display: none;
}

Javascript

window.onload = function() {
    document.getElementById('hiddenDiv').style.display = "block";
};

Upvotes: 0

Alex
Alex

Reputation: 7374

This would work

<div class="hidden">
  <ul>
    <li>Menu Item 1
    <li>Menu Item 2
    <li>Menu Item 3
  </ul>
</div>

.hidden {
  display: none;
}
$(function()
{
  $(".hidden").show();
});

Upvotes: 7

Related Questions