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"));
Related
I am loading .html content with jquery .load() but the javascript and css is not applied to the one.html/two.html after it is loaded by the .load() function.
Example below:
<head>
<style> styles1 </style>
<link href="stylesheets/style2.css" rel="stylesheet">
<script src="script1.js">
<script>
$(document).ready(function(){
$("button.os").click(function(){
fillmein = $(this).attr("target");
fillmeinfile = $(this).attr("target")+'.html';
$("."+fillmein).load("/contentfolder/"+fillmeinfile);
});
});
...
other scripts
...
</script>
</head>
<body>
<p>the css and any js is applied to this block</p>
<button class="os" target="one">replace</button>
<div class="one">I will be replaced by one.html</div>
<button class="os" target="two">replace</button>
<div class="two">I will be replaced by two.html</div>
</body>
I understand that the one.html/two.html is loaded after the styles and javascript is loaded by the browser but how I get the styles and javascript that is in the <head> to apply to the newly loaded one.html/two.html?
I new to jQuery so let me know how I clarify if needed. thanks!
EDITED
Thanks for providing answers everyone! Updated the code example to clarify what I meant.
copying the <style> and <script> into the one.html and two.html works but if I load the javascript twice it could conflict. for example, having logic that searches $(document), and functions that collapse and expand a section can be called multiple times. Is it possible to have the js and css that was loaded in the main page work on the newly loaded .html files or is there any clean and DRY way to do this?
As suggested by Arun P Johny in his comment
You simply put your CSS inline on the target document and it will be automatically loaded along with the content.
You can write
$('button').on('click','Classname',function(){
//write your structure here
})
This will work for all tags with 'Classname',which are already present or dyanamically added later on.
In my script i'm trying to get my Javascript script to return a URL, so I can use the URL as a background for the website.
Here is my code:
//background script
//backgrounds
Rblxscreenshot_zombietower = "http://saberman888etai.net/background_images/rblxscreenshot.png";
Rblxscreenshot_zombietower2 = "http://saberman888.netai.net/background_images/zombietower2.png";
Rblxscreenshot_deathrun = "http://saberman888.netai.net/background_images/deathrun_ice.png";
Rblxscreenshot_deathrun2 = "http://saberman888.netai.net/background_images/deathrun_lobby.png";
SCREENSHOTS = [
Rblxscreenshot_zombietower,
Rblxscreenshot_zombietower2,
Rblxscreenshot_deathrun2,
Rblxscreenshot_deathrun
];
function returnBackground(){
return SCREENSHOTS[Math.floor((Math.random() * SCREENSHOTS.length)+1)];
}
And here is my HTML code:
<!DOCTYPE html>
<head>
<title>Saberman888's Website</title>
<link rel="stylesheet" type="text/css" href="theme.css"/>
<script type="text/javascript" src="background.js"/>
</head>
<body style="background-image:url(<script src="http://saberman888.netai.com/background.js">returnBackground()</script>);">
<div class="box">
<div style="text-align:center;">
<h1>Home</h1>
Home
Conlangs
Projects
</div>
<hr>
<div id="minibox" style="margin-left:100px;">
<h2>Conlangs</h3>
<ul>
<li>Florrum</li>
<li>Genie</li>
</ul>
</div>
<div id="minibox" style="margin-left:100px;">
<h2>Projects</h2>
<ul>
<li>DLBOX</li>
<li>QuarryLang</li>
</ul>
</div>
<div id="links">
My Youtube
My DeviantArt
My Twitter
<a href="8.42.96.39/User.aspx?ID=49027085
">My Roblox</a>
My Github
</div>
</div>
</body>
</html>
As you can see, in the HTML code it uses the function returnBackground() to get a URL to use as a background, but the background doesn't show up, any reason why?
If you try to mod with the length of the array, it will be always inside the range. This issue looks like an out of range error in the line below:
function returnBackground(){
return SCREENSHOTS[Math.floor((Math.random() * SCREENSHOTS.length)+1)];
}
So replace it with:
function returnBackground(){
return SCREENSHOTS[Math.floor((Math.random() * SCREENSHOTS.length)+1) % SCREENSHOTS.length];
}
Update
Just saw a basic mistake, you cannot use a <script> tag or any other tag for that instance, inside an attribute. That's a syntax error:
<body style="background-image:url(<script src="http://saberman888.netai.com/background.js">returnBackground()</script>);">
You cannot set the background URL like that. Instead you need to this way:
<body onload="returnBackground();">
And in the returnBackground() should set the background in this way:
document.body.style.backgroundImage = url;
Your full returnBackground() function:
function returnBackground(){
document.body.style.backgroundImage = SCREENSHOTS[Math.floor((Math.random() * SCREENSHOTS.length)) % SCREENSHOTS.length];
}
The way you're trying to include the script is incorrect.
As per the HTML5 specification, a script tag has to contain either a src attribute or script content inside the tags, not both. (The only allowed content for a script tag with src specified is documentation, i.e. comments.)
Quote on the script element:
If there is a src attribute, the element must be either empty or contain only script documentation that also matches script content restrictions.
(This wasn't correct before HTML5 either, but (I think) it was more ill-defined, so it might work in some browsers, but don't rely on this.)
Also, the script tag cannot be inlined within a style (or any other) attribute.
For example, one of your better options is modifying the script to retrieve the body DOM element and manipulates its style, its background-image specifically (taking a more imperative approach). Then just include this script inside a script tag into your HTML.
Praveen Kumar's suggestion of adding an onload event handler is probably even easier, but the script include has to be fixed regardless of which path you choose.
What am I doing wrong in the code below that I'm not able to get a reference to the footer div?
<html>
<title></title>
<head></head>
<body>
<script>alert(document.getElementById('footer'));</script>
<div id="footer">testing footer</div>
</body>
</html>
you are calling getElementById() before the footer is loaded.
put the script at the bottom of the body or run in onload
Place the script tag below the div you are trying to select. I'm guessing the alert is returning null?
Change it to:
<script type="text/javascript">alert(document.getElementById('footer').innerHTML);</script>
And put it after the DIV.
Note, the innerHTML is assuming you're just trying to get the text from within that div.
Should be
<html>
<title></title>
<head></head>
<body>
<div id="footer">testing footer</div>
<script>alert(document.getElementById('footer'));</script>
</body>
</html>
The script tag i located before the footer and thus will be executed before the footer is created.
There are couple of things that you can do:
place script below footer.
add the deferred attribute to script
attach to onload event
I am not clear why its not working the javascript code when I add it to the header section as follows.
We can place a javascript code within the body as follows
<html>
<head>
<title> Simple Test </title>
</head>
<body>
<div id="mydiv"> This is the div content </div>
<script type="text/javascript" >
document.getElementById("mydiv").innerHTML=Date();
</script>
</body>
</html>
But when I place the same JavaScript code in the header section it doesn't work.
<html>
<head>
<title> Simple Test </title>
<script type="text/javascript" >
document.getElementById("mydiv").innerHTML=Date();
</script>
</head>
Can Someone please explain the issue. I know I can Write a JavaScript function in header and call it in an event. But can't we Use in this way. If Can't why.
<html>
<head>
<title> Simple Test </title>
<script type="text/javascript" >
window.onload= function (){document.getElementById("mydiv").innerHTML=Date();}
</script>
</head>
I think above code will help you to solve your problem. You can try this one.
because when the page is loaded, by the time the browser gets to that <script> element, the #mydiv element has not yet been created.
either use an "onload" event, or put your scripts at the bottom of the page.
It's because the page is being rendered in the order it's read. Therefore when the script in the header is evaluated the rest of the page hasn't been rendered yet (ie the myDiv element hasn't been created).
When you create an event handler in the head that works fine - the handler is set up before the rest of the page is loaded but the event can't happen until the element exists.
When you put it in the <head>, it runs before the <body> exists.
this is because of the page rendering order.you can access elements before it has been created. if you can, try to put all JavaScript code end of the page(before closing body tag). it will save your page load time. if you cannot put it in the bottom, put the code inside onload event.
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.