Is there a tag in HTML that will only display its content if JavaScript is enabled? I know <noscript> works the opposite way around, displaying its HTML content when JavaScript is turned off. But I would like to only display a form on a site if JavaScript is available, telling them why they can't use the form if they don't have it.
The only way I know how to do this is with the document.write(); method in a script tag, and it seems a bit messy for large amounts of HTML.
Easiest way I can think of:
<html>
<head>
<noscript><style> .jsonly { display: none } </style></noscript>
</head>
<body>
<p class="jsonly">You are a JavaScript User!</p>
</body>
</html>
No document.write, no scripts, pure CSS.
You could have an invisible div that gets shown via JavaScript when the page loads.
I don't really agree with all the answers here about embedding the HTML beforehand and hiding it with CSS until it is again shown with JS. Even w/o JavaScript enabled, that node still exists in the DOM. True, most browsers (even accessibility browsers) will ignore it, but it still exists and there may be odd times when that comes back to bite you.
My preferred method would be to use jQuery to generate the content. If it will be a lot of content, then you can save it as an HTML fragment (just the HTML you will want to show and none of the html, body, head, etc. tags) then use jQuery's ajax functions to load it into the full page.
test.html
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$.get('_test.html', function(html) {
$('p:first').after(html);
});
});
</script>
</head>
<body>
<p>This is content at the top of the page.</p>
<p>This is content at the bottom of the page.</p>
</body>
</html>
_test.html
<p>This is from an HTML fragment document</p>
result
<p>This is content at the top of the page.</p>
<p>This is from an HTML fragment document</p>
<p>This is content at the bottom of the page.</p>
First of all, always separate content, markup and behaviour!
Now, if you're using the jQuery library (you really should, it makes JavaScript a lot easier), the following code should do:
$(document).ready(function() {
$("body").addClass("js");
});
This will give you an additional class on the body when JS is enabled.
Now, in CSS, you can hide the area when the JS class is not available, and show the area when JS is available.
Alternatively, you can add no-js as the the default class to your body tag, and use this code:
$(document).ready(function() {
$("body").removeClass("no-js");
$("body").addClass("js");
});
Remember that it is still displayed if CSS is disabled.
I have a simple and flexible solution, somewhat similar to Will's (but with the added benefit of being valid html):
Give the body element a class of "jsOff". Remove (or replace) this with JavaScript. Have CSS to hide any elements with a class of "jsOnly" with a parent element with a class of "jsOff".
This means that if JavaScript is enabled, the "jsOff" class will be removed from the body. This will mean that elements with a class of "jsOnly" will not have a parent with a class of "jsOff" and so will not match the CSS selector that hides them, thus they will be shown.
If JavaScript is disabled, the "jsOff" class will not be removed from the body. Elements with "jsOnly" will have a parent with "jsOff" and so will match the CSS selector that hides them, thus they will be hidden.
Here's the code:
<html>
<head>
<!-- put this in a separate stylesheet -->
<style type="text/css">
.jsOff .jsOnly{
display:none;
}
</style>
</head>
<body class="jsOff">
<script type="text/javascript">
document.body.className = document.body.className.replace('jsOff','jsOn');
</script>
<noscript><p>Please enable JavaScript and then refresh the page.</p></noscript>
<p class="jsOnly">I am only shown if JS is enabled</p>
</body>
</html>
It's valid html. It is simple. It's flexible.
Just add the "jsOnly" class to any element that you want to only display when JS is enabled.
Please note that the JavaScript that removes the "jsOff" class should be executed as early as possible inside the body tag. It cannot be executed earlier, as the body tag will not be there yet. It should not be executed later as it will mean that elements with the "jsOnly" class may not be visible right away (as they will match the CSS selector that hides them until the "jsOff" class is removed from the body element).
This could also provide a mechanism for js-only styling (e.g. .jsOn .someClass{}) and no-js-only styling (e.g. .jsOff .someOtherClass{}). You could use it to provide an alternative to <noscript>:
.jsOn .noJsOnly{
display:none;
}
In the decade since this question was asked, the HIDDEN attribute was added to HTML. It allows one to directly hide elements without using CSS. As with CSS-based solutions, the element must be un-hidden by script:
<form hidden id=f>
Javascript is on, form is visible.<br>
<button>Click Me</button>
</form>
<script>
document.getElementById('f').hidden=false;
</script>
<noscript>
Javascript is off, but form is hidden, even when CSS is disabled.
</noscript>
You could also use Javascript to load content from another source file and output that. That may be a bit more black box-is than you're looking for though.
Here's an example for the hidden div way:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
*[data-when-js-is-on] {
display: none;
}
</style>
<script>
document.getElementsByTagName("style")[0].textContent = "";
</script>
</head>
<body>
<div data-when-js-is-on>
JS is on.
</div>
</body>
</html>
(You'd probably have to tweak it for poor IE, but you get the idea.)
My solution
.css:
.js {
display: none;
}
.js:
$(document).ready(function() {
$(".js").css('display', 'inline');
$(".no-js").css('display', 'none');
});
.html:
<span class="js">Javascript is enabled</span>
<span class="no-js">Javascript is disabled</span>
Alex's article springs to mind here, however it's only applicable if you're using ASP.NET - it could be emulated in JavaScript however but again you'd have to use document.write();
You could set the visibility of a paragraph|div to 'hidden'.
Then in the 'onload' function, you could set the visibility to 'visible'.
Something like:
<body onload="javascript:document.getElementById(rec).style.visibility=visible">
<p style="visibility: visible" id="rec">This text to be hidden unless javascript available.</p>
There isn't a tag for that. You would need to use javascript to show the text.
Some people already suggested using JS to dynamically set CSS visible. You could also dynamically generate the text with document.getElementById(id).innerHTML = "My Content" or dynamically creating the nodes, but the CSS hack is probably the most straightforward to read.
Related
When I insert this code into my file it seems to block my CSS from showing. I made a script to try and print text once the page has loaded which I am then going to use later to make a loaded bar. This is my code. All that happens is I get the text "Test" printed on my page.
<html>
<head>
<link rel="stylesheet" type="text/css" href="custom.css">
<script>
function myFunction() {
document.getElementById('index').innerHTML = "test";
}
</script>
</head>
<!-- Page Body -->
<body id="index" onload="myFunction()">
<div class="header">
<div id="headerbar"></div>
<ul id="">
</div>
</body>
</html>
When you set the innerHTML of the index element, it completely replaces everything in the body. So you no longer have the DIV with the header class, and you no longer have the DIV with the headerbar ID. There's nothing for your CSS to refer to. It's as if you had written:
<body id="index">test</body>
Well for one we have no way of knowing what your CSS does, but an issue I see is that when you are using innerHTML it overwrites existing HTML. As in everything inside the body tag is overwritten to just test text.
Caveat: My presumption is that you don't have styles on the body either.
What exactly is your CSS supposed to style when you set the innerHTML of your body element to "test" ? You're removing all other contained elements by doing this.
I guess what you wanted to do is add a text node like this:
document.body.appendChild(document.createTextNode("test"));
Not quite sure how to define this issue. I just started working with jQuery and Javascript and pretty much everything is fine, except for when the page initially loads. I have the page fade in, but it looks like all the CSS isn't being applied until the jQuery loads.
I tried this script in my Head tag, but it doesn't work. Help?
<script type="text/javascript">
$(function(){
$('#box-container').hide();
});
$(window).load(function() {
$("#box-container").show();
});
</script>
Whoops: site: http://www.elijahish.com
You should use a Javascript console like Chrome Console or Firefox Firebug to debug your code.
First, you are placing your script block which requires jQuery before jQuery is defined:
<head>
<script type="text/javascript">
$(function(){
$('#box-container').hide();
});
$(window).load(function() {
$("#box-container").show();
});
</script>
...
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
...
So you would see the following (in Chrome Console):
ReferenceError: $ is not defined
$(function(){
Second, you seem to be trying to run a script which is accessing (in the first block) an element (#box-container) before it has been seen in the DOM itself. You could use jQuery.ready on that first block, but that could be messy. I would instead suggest you place this right after <div id="box-container"> is defined:
<body ...>
<div id="box-container" ...>
...
</div>
<script type="text/javascript">
(function($){
$('#box-container').hide();
$(window).load(function() {
$("#box-container").show();
});
})(jQuery);
</script>
Demo: http://jsfiddle.net/5JpVB/4 (I use a setTimeout for dramatic effect.)
Or put it directly after the <div ...> is opened:
<div id="box-container">
<script type="text/javascript">
(function($){
$('#box-container').hide();
$(window).load(function() {
setTimeout(function(){
$("#box-container").show();
}, 2000);
});
})(jQuery);
</script>
Box Container shown on window.onload.
</div>
http://jsfiddle.net/5JpVB/5/
And the coup de grĂ¢ce (document.write nothwithstanding):
<head>
...
<script>
document.write('<style>#box-container{display: none;}</style>');
</script>
...
</head>
http://jsfiddle.net/5JpVB/2/
Yes, that is a script that "puts" the style display: none into the header, which "neatly" bypasses some of the conjecture that's been thrown around (there's downsides for each method, more or less). There's an elegance to this method (except, of course, using document.write, which is icky).
And yet another way, using the CSS display: none method:
<head>
...
<style>
#box-container {
display: none;
}
</style>
...
<div id="box-container">
<noscript><style>#box-container{display: block;}</style></noscript>
Box Container shown on window.onload.
</div>
http://jsfiddle.net/5JpVB/3/ (Just the Result page, disable Javascript to see it work.)
You are getting a case of FOUC : http://www.bluerobot.com/web/css/fouc.asp/
And, years later we are still plauged! http://paulirish.com/2009/avoiding-the-fouc-v3/
A variety of solutions are included on this link.
You could also set the style of your content to be hidden before running the javascript that shows the content. Jared shows you a nice way to do this.
Might I make a suggestion that you use combination of CSS and JavaScript, rather than one or the other. I had the same issue using jQueryUI on a site I'm building and found that a lot of these solutions out there would make the contact unavailable to those without JavaScript.
So here is what I did:
CSS:
.flash #wrapper {
display: none;
}
What this does is set the <div id="wrapper"> to hidden only if it is a decendent of the class flash. So to keep it from being hidden from those with out javascript I add the class flash to the <html> element. So it can only be physically hidden if the end user has JavaScript enabled, otherwise they'll at least have access via the unstylized content.
JavaScript:
$('html').addClass('flash');
$(doctument).ready(function() {
/* Do all your stuff */
/* When done show the wrapper with the content stylized */
$(#wrapper).show();
});
Depending on your pages time to load you might get a little flash, but it wont be a flash of unstylized content, which is rather ugly. In my case I had a jQueryUI menu item that would flash the normal <ul> element first then the menuUI item, and my <div> elements are resized with jQuery so that each <div> column is equal hight, but it would flash the different heights first. This fixed it while still giving accessability to none Script enabled browsers.
I would like some help displaying contents (to different pages) within one HTML page using JavaScript.
This is a sample of what I have found so far: http://www.swan10.nl/stuff/test.htm however instead of displaying "FAQ question #blabla" in the box every time a link is clicked, I would like to display words and images like a normal content. Is there a way to do this?
I tried removing the CreateDiv function and replacing it with HTML codes but it doesn't work.
Thank you in advance :)
Umm, well you would need to use AJAX to pull the data into the page and display it in whatever method you choose. If you want to use a framework look into JQuery. It has nice AJAX functions. Otherwise read HERE
After re-reading your post I think you might just want to choose which div is displayed on a form at one time. This you can achieve by placing all of your divs in the same container. Then toggle their display css property.
Using jQuery it's as simple as
$('#divname').load('/path/to/file.html');
Note that the result should probably not include <html> and <head> tags (although you don't seem like you care about well formed HTML code).
I should probably also mention that you shouldn't make the client load content for you, that's what server side code is for.
Personally I would use the innerHTML property on one of your elements. It will allow you to add markup to that element. Check it out here: http://www.w3schools.com/jsref/prop_html_innerhtml.asp
<html>
<head>
<title>Multiple DIV</title>
<style type="text/css">
DIV#db {
border : 1px solid blue;
width : 400px;
height : 400px;
}
</style>
<script type="text/javascript">
var Content = new Array();
Content[0] = '<i>test1</i>';
Content[1] = '<b>test2</b><br><img src =http://www.w3schools.com/images/w3schoolslogo.gif>';
Content[2] = '<u>test3</u>';
Content[3] = '<s>test4</s>';
function Toggle(IDS) {
document.getElementById('db').innerHTML = Content[IDS];
}
</script>
</head>
<body onLoad="Toggle(0,10)">
FAQ #1
FAQ #2
FAQ #3
FAQ #4
<p />
<div id="db"></div>
</body>
</html>
I updated it to work all javascripty with the innerHTML
I have a blog with annotated references like [1] that.
[1]Jake Smith. http://example.com ..............
[2].............
I want it so the [1] in the text is an anchor that links to the [1] in the References. I know I could do this by doing something in the text like [1]and then making every list item in the references have an id, , that is, that is,
<ol>
<li id="ref1"></li>
...
</ol>
But that's a lot of work for me to go through all the blog posts. I'm sure I could make a JavaScript or jQuery function to add this functionality, but then it would not work with JavaScript disabled. So is there some other function I don't know? Like some fancy CSS trick, or should I just use JavaScript to do this?
What are your recommendations?
You could have the links inline so it displays normally when the user has JavaScript disabled. With JavaScript on, just style it as a Wikipedia reference.
Demo: http://jsfiddle.net/6A8nX/
Your options are:
A blog plugin that detects this in the content and forms the link and adds the related id to the appropriate element for you when the HTML is being output
A script that runs and does the same thing after the HTML has loaded.
Manually adding the links by hand.
A blog plugin is your best bet, since surely this is a solved problem (though it would depend on your blogging platform, of course).
CSS is for styling, it can't add links/ids.
In addition, remember that if you are ever going to display multiple blog posts on each page, you will want to add the blog id to the anchor as well. Instead of ref1, you'll want:
ref_[blogid]_[refid]
JavaScript and CSS are the way to go, if you cannot do this on the server side. The following will do what you want:
<html>
<head>
<style type="text/css">
ref {
display:none;
vertical-align:super;
font-size:small;
}
references {
display:block;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" language="javascript"></script>
<script language="javascript">
window.onload = function(){
$("references").append("<ol>");
$("ref").each(function(index) {
$("references").append("<li><a name=\"ref_"+(index+1)+"\">"+$(this).text()+"</a></li>");
$(this).html("["+(index+1)+"]");
$(this).css("display", "inline"); // hides references unless the script runs
});
$("references").append("</ol>");
}
</script>
</head>
<body>
<p>This is a reference.<ref>http://www.google.com</ref></p>
<p>This is a another reference.<ref>http://www.yahoo.com</ref></p>
<references>
</references>
</body>
</html>
CSS is for presentation, and does not provide logic. Javascript is the best answer in this case, because it provides the tools and logic you need to accomplish the task.
So I was thinking a simple way to deal with javascript being disabled by the browser would be the following:
<head>
<title>JavaScript Test</title>
<noscript>
<meta http-equiv="Refresh"
content="1;url=nojs.html" />
</noscript>
</head>
And having the nojs.html have something like:
<p>Return to test after enabling javascrpt.</p>
At the crash page.
This isn't my preferred method, but it's nice and simple until something more graceful can be worked out for users without javascript.
However, it is not valid to put a <noscript> element in the head section. The preliminary tests worked anyway, of course, but I'm superstitious when it comes to my code being valid, plus I'd hate for this to actually fail a field test.
So is there a valid way to do this? Perhaps wrapping the noscript in another element, like an object tag? Or some even simpler way I'm not thinking of?
I am not sure why you need to redirect to another page instead of just showing a message. I use JS and a little CSS to handle these situations for me. Something like this:
<head>
....
<script type="text/javascript"> document.documentElement.className += " js"</script>
<link rel="stylesheet" type='text/css' href="css/layout.css" media="all" />
</head>
<body>
<div id="noscript">Please enable JavaScript, then refresh this page. JavaScript is required on this site</div>
<div id="wrapper">
...
</div>
</body>
Then in layout.css:
#wrapper { display: none } /* Hide if JS disabled */
.js #wrapper { display: block } /* Show if JS enabled */
.js #noscript { display: none } /* Hide if JS enabled */
By doing it this way, the class is applied to the html element before the page is rendered so you won't get a flicker as the non-JS content is swapped out for the JS content.
Doug's solution is pretty good, but it has a few drawbacks:
It is not valid to have a class attribute on the html element. Instead, use the body.
It requires that you know what display type to set the element to (i.e. ".js #wrapper { display: block }").
A simpler, more valid and flexible solution using the same approach could be:
<html>
<head>
<!-- put this in a separate stylesheet -->
<style type="text/css">
.jsOff .jsOnly{
display:none;
}
</style>
</head>
<body class="jsOff">
<script type="text/javascript">
document.body.className = document.body.className.replace('jsOff ','');
</script>
<noscript><p>Please enable JavaScript and then refresh the page.</p></noscript>
<p class="jsOnly">I am only shown if JS is enabled</p>
</body>
</html>
With this, it's valid html (no class attribute on the html element). It is simpler (less CSS). It's flexible. Just add the "jsOnly" class to any element that you want to only display when JS is enabled.
The <noscript> tag cannot be in the <head>, it must be in the <body>
The common practice is to show a message instead of redirecting, as there is no way to redirect only if javascript is disabled.
You could do it the other way around, have the first page be nojs.html, and on that page use javascript to redirect to the main content.
If you truly want a valid way to do it, make your main page the nojs.htm page and use JS to hide all content before it's shown to the user and immediately redirect to the real main page using javascript.
I like Doug's solution. However, if you need to redirect, I would remember that while there is a spec and a standard, the world of web browsers is a dirty, imperfect world. Whether or not something is allowed by the spec is not as important as whether or not it works in the set of browsers you care about.
Just look at the source code of any major site... Most of them won't validate I'd bet :)
What about:
noscript{
z-index:100;
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
min-height:1024px; background:#FFF;
}
And:
<noscript>
<p>Please enable Javascript on your browser.</p></noscript>