So, I have this between my head tags
Difference between display
and visible
:
visible
still takes up space on the page. The adjacent content is not rearranged when the element is toggled between visible
and hidden
.display=none
will not take up any space on the page. Other display
values will cause the element to take up space. For example, display=block
not only displays the element, but adds line breaks before and after it.Your JS should be setting the div's display to "block" ("visible" isn't a valid value for display).
Also, from the looks of things your elements aren't in the DOM at the time the code is fired (your code doesn't see them yet). Do any of the following:
Place your code anywhere in the document body below the divs
or, use an unobtrusive strategy to fire your function on window load, a la:
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(nameOfSomeFunctionToRunOnPageLoad);
or, Use a JS framework's "ready" functionality, a la jQuery's:
$(function () {
nameOfSomeFunctionToRunOnPageLoad();
});
"visible" is not a valid value for "display". You're after "inline" or "block".
"visible" and "hidden" are valid values for the "visibility" CSS property.
The disadvantage of showing elements on ready is that they will only flicker in after the page has finished loading. This usually looks odd.
Here's what I usually do. In a script in the <head>
of the document (which runs before the body begins to render), do this:
document.documentElement.className = "JS";
Then, any CSS selectors that descend from .JS
will only match if JavaScript is enabled. Let's say you give your links a class of javascriptNeeded
(a class is more appropriate than a name here). Add this to your CSS:
.javascriptNeeded{
display: none;
}
.JS .javascriptNeeded{
display: inline;
}
…and the elements will be there from the start, but only if JavaScript is enabled.
The JavaScript is executed before the divs are in the DOM. The standard way to do something after the DOM is ready is to use jQuery's $(document).ready(function () { });
, but there are other ways as well.
The oldschool way is to use <body onload="myfunction()">
.
Here's a newer way (edit: put display:none
into CSS):
HTML:
<p class='javascript_needed'>hello</p>
CSS:
.javascript_needed {display:none;}
JavaScript:
$(document).ready(function () {
$('.javascript_needed').show();
});