How do I apply loaded javascript and css to .load() content? - javascript

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.

Related

jquery load time and css styling inside it

like you see in the code below, the jquery loads a page but it seems that all the .css styling inside the jquery waits until the jquery is loaded which can take some fraction of a second if the file is big. So if I have .css("display","none") it will not work for that time causing a flickering before the styling kicks in. I have this problem only with Mozilla. The code below its only an example and it works well because is small. Some ideas how to fix this?
$(document).ready(function() {
$(".rectangle").click(function() {
$("body").load("debugging2.html", function() {
$(".rectangle").css("display","none")
$(".rectangle").fadeIn(1000);
}) ;
});
})
.rectangle{
height: 200px;
width: 200px;
background-color:#000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
<div>
<div class="rectangle"></div>
</div>
</body>
$(document).ready(function() {
$(".rectangle").click(function() {
$("head").append("<style>.rectangle{display:none;}</style>");
$("body").load("debugging2.html", function() {
$("rectangle").fadeIn(1000);
});
});
})
Since script tags are loaded synchronously (by default) they indeed block page rendering. It can result in blank unstyled page if HTML is not processed and styles are not loaded by that moment. Hence the common very simple solution is to move heavy script tags to the very end of the </body> and put necessary CSS style in the <head>.
As the result of above, CSS gets downloaded first, after HTML is loaded quickly, rendered and styled and only after that slow scripts get downloaded.
In code it will look something like this:
<head>
<link href="style.css" rel="text/css" type="stylesheet">
</head>
<body>
<div>
<div class="rectangle"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- some other scripts -->
</body>
As the bonus, you don't need to bind to document ready event anymore ($(document).ready(function() {});), since HTML is all loaded by default, when scripts are executed.

JavaScript not working as an external file

I'm new to HTML, JavaScipt and everything related to programming, and I'm trying to create a simple page.
Now, I'm stuck with the following problem: I want to change the date of my main.html file, but the main.js is not working. I've already change the <script> position to inside the <body>, after the </span> and even after the </body>, without success. If the content of the main.js is within the HTML it works fine, but as a external file it doesn't.
Here is my main.html:
<!DOCTYPE html>
<html>
<head>
<link href="main.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="main.js"></script>
<title>Page 1</title>
</head>
<body>
<p>WRF<br>
<span id="data">18/09/1987</span></p>
</body>
</html>
My main.js is just:
document.getElementById("data").innerHTML = "JUBA";
I've looked through the internet and through this forum, but all answers that I've found did not worked.
The files are on the same directory and the main.css works fine.
Thank you in advance.
At time you call main.js element #data was not created in DOM tree. You can fix this by putting the link to your Javascript file right before closing the body like this:
<script type="text/javascript" src="main.js"></script>
</body>
Document Object Model (DOM) is not "READY".
Try use onload event, inside main.js:
window.onload = function() {
document.getElementById("data").innerHTML = "JUBA";
};
If needs more "fast" than onload, use jquery with $(document).ready:
html:
<link href="main.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="main.js"></script>
main.js:
$(document).ready(function() {
$("#data").html("JUBA");
});
window.onload vs $(document).ready()
Answer by #Guffa:
The ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content (e.g. images) also has been loaded.
The onload event is a standard event in the DOM, while the ready event is specific to jQuery. The purpose of the ready event is that it should occur as early as possible after the document has loaded, so that code that adds functionality to the elements in the page doesn't have to wait for all content to load.
The element is not yet accessible when you run the script.
Either you can put the script at the end of the page or delay the execution.
You could put the JavaScript in the <body> tag after the rest of the page. When the browser loads it, the <span> will already be there to be edited.
As per your code the script will be called first then page will be loaded, therefore when the script is running there will not be any element having id data because yet page have to be loaded. There are many ways to achieve what you need.
1. Add a script tag before or after end of body like
or
<script type="text/javascript" src="main.js"></script>
</body>
Write .js file above before body i.e. in head tag and write the whole javascript code in onload method.
window.onload=function(){
document.getElementById("data").innerHTML = "JUBA";
};
window.onload=function(){
document.getElementById("data").innerHTML = "JUBA";
};
<p>WRF<br>
<span id="data">18/09/1987</span></p>

JavaScript code blocking CSS

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"));

How to replace Current script tag with HTML contents generated by the same script

I want to replace the current script tag with the HTML contents generated by the same script.
That is, my Page is
<html>
<body>
<div>
<script src="myfile1.js"></script>
</div>
<div>
<script src="myfile1.js"></script>
</div>
</body>
</html>
Inside each .js file corresponding html contents are generated. I want to put the contents as the innerHTML of the parent div. But can't set id for the parent div because the page is not static. So the current script tag must be replaced with the HTML content. How can I do this?
For each script tag src is the same. So can't identify with src. These scripts displays
some images with text randomly. Scripts are the same but displays different contents in divs on loading
Please help me
try inside of myfile1.js:
var scripts = document.getElementsByTagName( "script" );
for ( var i = 0; i < scripts.length; ++ i )
{
if ( scripts[i].src == "myfile1.js" )
{
scripts[i].parentNode.innerHTML = "new content";
}
}
This is a great question for those trying to implement a JSONP widget. The objective is to give the user the shortest possible amount of code.
The user prefers:
<script type="text/javscript" src="widget.js"></script>
Over:
<script type="text/javscript" src="widget.js"></script>
<div id="widget"></div>
Here's an example of how to achieve the first snippet:
TOP OF DOCUMENT<br />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
// inside of widget.js
document.write('<div id="widget"></div>');
$(document).ready(function() {
$.getJSON('http://test.com?remote_call=1', function(data) {
$('#widget').html(data);
});
});
<br />BOTTOM OF DOCUMENT
Have a look at: http://alexmarandon.com/articles/web_widget_jquery/ for the correct way to include a library inside of a script.
document.currentScript has been available since 2011 on Firefox and 2013 on Chrome.
document.currentScript documentation at MDN
<!DOCTYPE html>
<meta charset="UTF-8">
<title>currentScript test</title>
<h1>Test Begin</h1>
<script>
document.currentScript.outerHTML = "blah blah";
</script>
<h1>Test End</h1>
Unfortunately a running JavaScript file is not aware of where it is running. If you use document.write() in the script, the write function will take place wherever the script runs, which would be one way to accomplish what you want, but without replacing the contents or being able to perform any actions on the enclosing DIV.
I can't really envisage a situation where you'd have such stringent restrictions on building a page - surely if the page is dynamic you could generate identifiers for your DIV elements, or load content in a more traditional manner?
Why not use Smarty?
http://www.smarty.net/
You can use javascript in Smarty templates, or just use built-in functions.
Just take a look at http://www.smarty.net/crash_course
poof -- old answer gone.
Based on your last edit, here's what you want to do:
<html>
<head>
<!-- I recommend getting this from Google Ajax Libraries
You don't need this, but it makes my answer way shorter -->
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function getRandomContent(){
// I expect this is the contents of your current script file.
// just package it into a function.
var rnd = Math.random();
return "[SomeHtml]";
}
$('.random').each(idx, el){
$(this).html(getRandomHtmlContent());
});
});
</script>
</head>
<body>
<div class="random">
</div>
<div class="random">
</div>
</body>
</html>
If you don't mind the script tag remaining in place you can use something as simple as document.write().
myfile1.js:
document.write("<p>some html generated inline by script</p>");
It will do exactly what you need.

Is there a HTML opposite to <noscript>?

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.

Categories