I've done a simple menu using some HTML, CSS and Javascript. The main idea is that it should be hided until the user click on it, but the problem is that it won't start the page hidden and nothing happens when I click, just like if the Javascript won't active. Here is part of my files:
index.html
<head>
<link rel="stylesheet" type="text/css" href="style/sample.css" />
</head>
<body>
<script src="js/menu.js" type="text/javascript"></script>
<div id="container">
<div id="header">
<center>
<div class="leftMenu" onclick="toggleMenu()">Menu</div>
<h1>Test</h1>
</center>
<ul>
<li>About</li>
<li>Blog</li>
<li>Contact</li>
</ul>
</div>
</div>
</body>
menu.js
$(document).ready(function() {
$('#header ul').addClass('hide');
$('#header').append('<div class="leftMenu" onclick="toggleMenu()">Menu</div>');
});
function toggleClass() {
$('#header ul').toggleClass('hide');
$('#header .leftMenu').toggleClass('pressed');
}
sample.css
#header ul.hide {
display: none;
}
#header div.pressed {
-webkit-border-image: url(graphics/button_clicked.png) 0 8 0 8;
}
What I'm making wrong and how I can correct it?
I think at least part of the problem is that the menu toggle div you're creating is using the function toggleMenu() and not toggleClass().
EDIT: I made a jsfiddle that shows the changes I would propose to make it work properly: http://jsfiddle.net/avidal/dDDKz/
The key is to remove the onclick attributes, and use jQuery to handle the event binding for all current, and future matching elements:
$(document).ready(function() {
$('#header ul').addClass('hide');
$('#header').append('<div class="leftMenu">Menu</div>');
$('#header div.leftMenu').live('click', toggleClass);
});
function toggleClass() {
$('#header ul').toggleClass('hide');
$('#header .leftMenu').toggleClass('pressed');
}
Ok, a few things:
Make sure you have a doctype. You said this was just part of your code, so perhaps you do, but just to be sure, I'll point this out anyway. You can just use the html5 doctype (it is compatible with IE6 if that's a worry):
<!DOCTYPE html>
<html>
<head>...head stuff here </head>
<body> ...Body stuff here</body>
</html>
Make sure you are loading the jquery library. Again, maybe you already are, but just making sure your bases are covered here. I'd suggest putting it in your HEAD. You should also move menu.js out of the head and just below the closing BODY tag.
If you want the UL to start off hidden, you should have the default CSS for it display none. Otherwise, even if your script was working, you would see the ul for a moment before it became hidden as the page would first load and then the JS would apply the class. In that gap between page loading and JS applying your class, the UL will be visible.
Your scripts could really be optimized, and I apologize for not being more specific (shouldn't write these when I'm trying to get ready for bed), but I'll at least point out the most obvious fix here - make sure that you are calling the correct method. I see that in the HTML snippet you are appending, you are calling toggleMenu(), but in your actual JS, your function is called toggleClass. Change one of those so they match.
Related
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.
Thanks in advance for your help.
So I have a fully functioning page, but when I make the following changes, my jQuery accordion stops working on rollover and all of my navigation links (which point to #sections as it's a single-page scrolling site) stop working completely. Here is the deadly code:
<script type="text/javascript">
$(document).ready(function(){
$(document).ready(function () {
$('#fadeDiv').fadeIn(3000);
});
});
</script>
</head>
<body>
<DIV ID="fadeDiv" style="display:none;">
... page here ...
</div>
</body>
All functionality which breaks is WITHIN the fadeDiv. It's worth noting that the links (a href="#section") can be IN a div that fades in and will work fine, but will break if, rather, I fade in the containing div of #section.
Weird.
why are you calling the document ready 2?
Does the jquery file pulled in?
your code should look like this
<script type="text/javascript">
$(document).ready(function() {
$('#fadeDiv').fadeIn(3000);
});
</script>
and add this to your header
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
and i would recomend putting the display none in css
I can't get a jQuery UI modal dialog it to work as in the demo! Consider this recipe:
<html>
<head>
<script type="text/javascript" src="/javascripts/jquery.js"></script>
<script type="text/javascript" src="/javascripts/jquery-ui.js"></script>
</head>
<body>
<p>First open a modal dialog</p>
<p>Then try to hover over me</p>
<p>And <a onclick="alert('clicked!'); return false;" href="alsobroken"> click me!</a></p>
</body>
</html>
While the dialog is active, the second link is correctly disabled but the third link (onclick) still works! Also, the little browser hand appears when hovering both links. This is not like the demo... what am I doing wrong?
As Pointy points out, this is normally controlled by the jQueryUI CSS. But one can get around it by adding slightly hackish snippet to one's CSS file.
.ui-widget-overlay {
height:100%;
left:0;
position:absolute;
top:0;
width:100%;
}
That way the "shroud" div covers up all buttons and there's no need to use the jQueryUI CSS.
The problem is that you're not including the jQuery UI CSS file(s). You get the CSS file from the download package you prepare at the jQuery UI site, or I think you can get the standard "lightness" one from Google. Without the CSS file, the mechanism can't make the "shroud" layer work. Also you may have noticed that the dialog doesn't look like anything; that'll get better too when you add the CSS files.
http://jsfiddle.net/wxyBG/1/
It is possible not to show html page in user browser until some JavaScript(built-in or in separate file) will be loaded and executed(for page DOM manipulation)?
The easiest thing to do is to set the css variable
display: none;
to the whole page.
then when everything is loaded you can set the display to
display: block; // or something else that suits.
If you make sure that piece of CSS is loaded at the very start of your document it will be active before any html is shown.
if you use a javascript library like jQuery you'll have access to the $(document).ready() function, and can implement a switch over like this:
<html>
<head>
<title>test</title>
<style type="text/css">
body > div {
display: none;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
$('body > div').css('display', 'block');
});
</head>
<body>
<div>
This will initially be hidden.
</div>
</body>
</html>
Not in the classical way you'd distribute a page. Browsers will (usually) start to display chunks of the base HTML file as it arrives.
Of course, you could simulate this by generating all the HTML on the fly from some included Javascript file. But that doesn't sound like a good plan as it will degrade horribly for people without JS enabled, or if you have a minor bug in your script. A better option might be to style the body tag to display: none and restyle it from the script to make certain parts visible again.
What is it you're actually trying to achieve? It sounds like there's likely to be a better way to do this...
Place the content of HTML page in a DIV, make its diplay none and on load of body diplay it.
<script type="text/javascript">
function showContent() {
var divBody=document.getElementById('divBody');
divBody.style.display= 'block';
}
</script>
<body onload="showContent()">
<div id="divBody" style="display: none;">
<--HTML of the page-->
</div>
</body>
Examples of what you might want to do:
Facebook's "BigPipe": http://www.facebook.com/notes/facebook-engineering/bigpipe-pipelining-web-pages-for-high-performance/389414033919
This method allows you to load JS first then ASYNC+inject all DOM content.
GMail
Zimbra (open-source web app similar to MS Outlook/Exchange)
My understanding is that you want to run some javascript code before you load the page. In the js file you write your init function and add the eventlistener to the window on "load" event. This will ensure that the init code gets executed first and then you can start displaying the HTML content.
var Yourdomain = {};
YourDomain.initPage = function(){
/* Your init code goes here*/
}
window.addEventListener("load", YourDomain.initPage, false);
All You really need to do is give your element an ID or CLASS and use the dislay: none; property. When your ready to show it just delete it.
CSS:
#div_1 {
display: none;
}
HTML:
<div id="div_1">
<p>This will be the hidden DIV element until you choose to display it.</p>
<p id="js_1"></p>
<script>
var x = "Some Test ";
var y = "Javascript";
document.getElementById("js_1").innerHTML = x + y;
</script>
</div>
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.