Importing multiple HTML Pages into a single div on page load - javascript

I am trying to import multiple HTML External pages into a single div.
Example: I am page1.HTML, page2.html and so on. I have this piece of JQuery:
<script type="text/javascript">
$(document).ready(function() {
$('.main').load('page1.html');
});
</script>
This works fine except I am not sure how to add multiple pages to become imported into the same div on page load.
Thank my friends.

If you want multiples then you cant use load. Use $.get instead and specify the callback to add them to the div:
var pages = ['page1.html', 'page2.html', etc..],
$main = $('.main'),
doLoad = function () {
if(pages.length > 0) {
// use shift to get the next page off the array
$.get(pages.shift(), function(content) {
// append content to .main
$main.append(content);
// call do load to get the next entry
doLoad();
});
}
};
doLoad();

var pages=["page1.html","page2.html","page3.html"],
mainDiv=$(".main");
$.each(pages, function(i,page){
var newDiv=mainDiv.append("div");
newDiv.load(page);
});
load() will be easier than get() if you only want to load page fragments (which is usually the case if you deal with complete pages that include head tags).

Create an array of HTML-files to load, and iterate through the array with an ajax call for each page, and then use jQuery prepend() to put the contents into your element.

Related

How do I add another div id to setInterval load?

I have this AJAX script that refreshes/updates a div with the id #main.
Is it possible to add yet another id #count to also refresh/update along with the other where it says /// can add another function here
I don't know javascript or ajax but I've tried to add function timingLoad() { $('#count').load(' #count', function() and just $('#count').load(' #count', function() but without any luck to get it working.
$(document).ready(function() { /// Wait till page is loaded
setInterval(timingLoad, 3000);
function timingLoad() {
$('#main').load(' #main', function() {
/// can add another function here
});
}
}); //// End of Wait till page is loaded
Sounds like you want to load the current page (via AJAX) at regular intervals and extract the contents of two separate HTML elements (#main and #count).
I would use jQuery.get() instead of .load() for this
$.get().done(doc => {
$("#main").html($("#main", doc))
$("#count").html($("#count", doc))
})
This loads the current page via $.get() then sets the HTML content of #main and #count with their counterparts from the loaded document.

Execute script after loaded in div [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Initialize script
I have a page (Page1.html) and in this page a div (#div1) that get its content from other divs in another page (Page2 #div1/2/3/4/5). The content is loaded in by jQuery load script. The content is loaded in based on choice in a select box, so the content is loaded in after Page1 has finish loaded.
Problem:
When I get some content from Page2 that's depending on jQuery, these elements don't work. They don't execute.
My questions:
Is there any way to make the a whole inloaded #div from Page2 (all the content) to execute WHEN its loaded in? Right now the existing elements "initialize" when they are loaded in, for example: function initializeSlider(){ slider };.
Now I am trying to add in some more elements depending on jQuery, and wounder if initializing all the objects is the correct way of execute all these scripts, or is there any way that execute all the jQuery elements at once so no need to initializing all object one by one?
Executing or Initializing one script:
If there is no way to execute/initialize all scripts at once when a div is loaded in. I am trying to execute or initialize this script without success, have tried both the "$(document).ready(function() {" and initialize it similar to the slider but the element is not executing.
$(document).ready(function() {
$(".lil").click(function () {
$(this).toggleClass("highlight");
});
});
Depending on what you're initializing; for events make sure and use .on():
$("#div1").on('click', '.lil', function () {
$(this).toggleClass("highlight");
});
Use:
$(document).ready(function() {
$("#div1").on('click', '.lil', function () {
$(this).toggleClass("highlight");
});
});
You could give that function a name. Something like:
function toggleClasses(classToToggle) {
$(classToToggle).click(function () {
$(this).toggleClass("highlight");
});
}
Then, your main page could have:
$(document).ready(function() {
toggleClasses('.lil');
});
And at the bottom of the partial view that you load from page 2, add this:
<script>
toggleClasses('.partialViewClass');
</script>
That way, as soon as that Partial View is done loading, it will call that same function.
If all you're doing is toggling that class, you might want to add a parameter for a secondary class to differentiate the elements in the partial view from the elements in the original page, that way the ones in the original page won't get toggled back when the partial view gets loaded.
So the ones in your partial view would need the highlight class as well as that secondary differentiation class (class="lil partialViewClass"). Pass the class as the parameter to the function so each one will only toggle what it should.

How to .load() just a specific div from a page into a a target div, not the whole page

I have the following script that loads a page into a div and not just the targeted div. This is most evident when going back to my index and my header and footer are jammed into the <div id="contentspace"></div>.
I read on here somewhere that the div needs to be placed in it's own page prior to being displayed. Not sure which method would do that. Is this possible without hashtags Thanks for your help
<script type="text/javascript">
$(function() {
$('#header a').click(function() {
$('#contentspace').empty();
$("#contentspace").load(this.href, function(response){
console.log($('#content', response).html())
event.preventDefault();
});
});
});
</script>
The method .load() can load page fragment, simply by specifying a valid jquery selector next to the url.
$('myelement').load('page.html #content', function() {
...
});
Note that when loading page fragments, jquery will remove any SCRIPT element it might contain.
In you example, you would do:
$("#contentspace").load(this.href + ' #content', function(response){
...
});
Did you read the documentation at all? Take a look at the section titled Loading page fragments in the jQuery API for .load(). Essentially you just pass a selector along with the URL of the page to load as the first argument of the method.

reinitialize processing.js sketch after ajax request

I would like to refire the styling and processing.js scripts that i linked to in the head so that they display correctly when brought in through an ajax-request. I see where in the ajax request this code needs to be, but i don't know how to tell the code to simply reapply the script. I've seen people using getScript() to do this, but from what i can tell this reloads the script, rather than simply telling it repeat or refire. Do all of the scripts need their own reinitialization? I found the syntax highlighters .highlight() method, but i am yet to get the processing script to load. currently, Processing.loadSketchFromSources($('#processing'), ['mysketch.pde']); does not work. I am using current versions of all libraries. Surprised i haven't been able to find the answer yet, as a lot of people seem to have the same problem. Thanks for your help!
index page:
$(document).ready(function () {
// put all your jQuery here.
//Check if url hash value exists (for bookmark)
$.history.init(pageload);
//highlight the selected link
$('a[href=' + document.location.hash + ']').addClass('selected');
//Search for link with REL set to ajax
$('a[rel=ajax]').live("click",function(){
//grab the full url
var hash = this.href;
//remove the # value
hash = hash.replace(/^.*#/, '');
//for back button
$.history.load(hash);
//clear the selected class and add the class class to the selected link
$('a[rel=ajax]').removeClass('selected');
$(this).addClass('selected');
//hide the content and show the progress bar
//$('#content').hide();
$('#loading').show();
//run the ajax
getPage();
//cancel the anchor tag behaviour
return false;
});
});
function pageload(hash) {
//if hash value exists, run the ajax
if (hash) getPage();
}
function getPage() {
//generate the parameter for the php script
var data = 'page=' + encodeURIComponent(document.location.hash);
$.ajax({
url: "loader.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
//hide the progress bar
$('#loading').hide();
//add the content retrieved from ajax and put it in the #content div
$('#content').html(html);
//display the body with fadeIn transition
$('#content').fadeIn('fast');
//reapply styles?
//apply syntax highlighting. this works
SyntaxHighlighter.highlight();
//relaod processing sketch, currently displays nothing
Processing.loadSketchFromSources($('#processing'), ['mysketch.pde']);
}
});
}
This the ajax-loaded content:
<!--ajax'd content-->
<??>
<h2>code</h2>
<pre class="brush: php">
$last_modified = filemtime("header.php");
echo("last modified: ");
echo(date("m.j.y h:ia", $last_modified));
</pre>
<script type="application/processing">
</script>
<canvas data-processing-sources="mysketch.pde" id="processing">
</canvas>
</div>
</body>
</html>
<??>
So, let's analyze what usually happens when you include an (external or internal) Javascript code: It will automatically execute only the code that is available in the global scope. "Good" scripts will only add one command to the global scope which will then execute the initialization code somewhere in a function/method.
All you need to do is view the external Javascript file and find out what is being executed from the global scope. There is no general answer to that ... some scripts use an object and call its init() method ... but that is totally subject to the imagination of the developer.
If you have javascript that needs to trigger, you MUST add this to the head element:
var head = document.head || document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.innerHTML = "your AJAX-obtained js code";
head.appendChild(script);
The same trick goes for CSS. Add a element to the head with your CSS declarations as innerHTML. So: make sure to preprocess your AJAX response and split out the JavaScript and CSS elements, then add those to the document header. It's probably easier to make your response a JSON object along the lines of:
{
html: "<html>string<goes>here</goes></html>",
scripts: ["url1","url2","url2",...],
style: ...
}
and then parsing that JSON for the html (which you use as innerHTML for a new document.createElement("div") or something, and then append wherever it needs appending), the scripts (which you turn into elements for HEAD insertion) and the style declarations (which you turn into elements for HEAD insertion).
(On a functional note, your example AJAX response looks like it has PHP code in it. I have no idea what you're using it for, but that looks like a bad response)
Just incase anyone stumbles upon this:
If you have processing.js already loaded, simply call Processing.reload() in your AJAX success/complete function.
Perhaps you already have an element with id="processing" on your page. In that case $("#processing") will only return the first one. If that is the case, change the id or use a class instead.
The other option, which I don't recommend, is to use $("[id=processing]"). That will return every element on the page with id="processing". But, don't use it. Use unique ids in your page, or switch to using classes, whichever works best for you.

Structure for handling several script loaded from ajax

So as many others I have a problem dealing with scripts from external pages I load with ajax.
Im trying to set up a page with an "admin panel" on top of it. I want to be able to navigate to several admin pages within the panel. The different admin pages have both internal <script>and external js-files that they include. The scripts are loaded as they should but they seem to stack up or are not being managed in a good way.
I made a small test on one of the admin pages:
$('.left-col').click(function () {
alert();
});
Here, whenever I return to this page it will bind another click to it so I then get two alerts each time I click the div. I can solve this easily by running $('.left-col').unbind(); in my ajax.success.
However for some admin pages there are tons of .click/.change/.live etc and I'm not even sure what they are (i.e. from external plugins). So can I somehow unbind/remove all of the scripts loaded from each of my ajax-loaded page without having to specify each elements? I know I can use selectors with unbind but it doesnt seem very effective to loop over each div/img/input etc and unbind, and I'm not even sure if it will work.
This is how I load the admin pages:
<script type="text/javascript">
$(document).ready(function() {
function reloadAdminPanel(url) {
if(typeof(url) === "undefined") {
var url = '/admin/panel/dashboard/';
}
$.ajax({
'success': function (data, textStatus) {
var jData = $(data);
// override links in admin to run reloadAdminPanel()
jData.find('a').each(function() {
var newUrl = $(this).attr('href');
$(this).click(function(e) {
reloadAdminPanel(newUrl);
return false;
});
});
$('div.panel__inner').remove();
$('body').prepend(jData);
delete jData;
},
'url': url
});
}
reloadAdminPanel();
});
</script>
Any help is appreciated, cheers!
The structure of the page:
<html>
<body>
<div class="panel__inner"> <!-- admin panel --> </div>
<!-- rest of project site -->
</body>
</html>
Maybe itd help if you show us the structure of the elements, but from the definition of "Remove" in Jquery, it should remove the element, its children, all events and any data associated to it.
Is div.panel__inner located inside your body tag? I see that you are doing a remove on the div, but prepending the data to $('body'). Can you remove the body contents itself?

Categories

Resources