- how to load all elements on my page with javascript?
- 1 Answer 1
- How to know if all is loaded on the page?
- 3 Answers 3
- Javascript javascript which all elements are loaded
- How to ensure that all elements are loaded on an html page, and then we perform some modifications on elements in CSS?
- Javascript check if all clicks have completed loading elements
- Script can’t get elements on page load JS
how to load all elements on my page with javascript?
I have a dynamic page with different elements in each generates, and I want to load all of their lines to an alert for example or a page with JavaScript. Is this possible? For example, if I had this line to my page:
sometimes HTML, sometimes JSP, sometimes ASP and so on You wont be getting JSP/ASP code with ajax, not sure what you are asking here.
I think you are talking about Ajax? You can use Ajax to get the content of the page itself and store them as a string for alert(). If only I understood your question correctly. [x]
1 Answer 1
You can use Ajax. Here’s an example that alert s the contents of the page test.aspx , for example:
var rq; // Initialize the request: if(window.XMLHttpRequest) < rq = new XMLHttpRequest(); // Standards-compliant way, compatible with every browser except IE6 and under >else < rq = new ActiveXObject('Msxml2.XMLHTTP'); // IE6-compatible. >// Open the request: rq.open('GET', 'test.aspx', true); // GET is the method (you're probably familiar with this), test.aspx is the URL, and true means send asynchronously. // Set up the state-change handler: rq.onreadystatechange = function() < if(rq.readyState === 4) < // Request complete alert(rq.responseText); // The response is in the responseText property. >>; // Finally, send the request: rq.send(null);
For more information, Google «Ajax.» There are plenty of good tutorials.
@MikeRedford: I didn’t downvote your question, personally. it’s clear enough. 4 other people did, though.
How to know if all is loaded on the page?
I am building a page with lots of ajax calls and creating the DOM dynamically. What is the best way to get to know whether all the ajax call is made and all the DOM element is finished building ?! I tried following prototype.js event observer :
Event.observe(window, 'load', function () < alert("Loaded!"); >);
The window onload event fires when all of the page has loaded, that is, when the HTTP request and all of the files (ex. images) have been downloaded. Any AJAX request made afterwards doesn’t affect the firing of the onload event. You should probably handle each onload event for each AJAX request and do something when all have fired.
Having a page with a lot of asynchronous processes you might consider using a mediator pattern. stackoverflow.com/questions/14440809/…
3 Answers 3
You need to respond to the ajax calls completing by adding code to their success (or complete ) handlers.
For example, let’s assume you’re making three ajax calls to populate the DOM. After each ajax call, increment some global counter by 1, then call a function that checks if the counter is three (meaning all of the ajax calls are finished). If it is, you would run your alert(‘Loaded!’); .
This is easier to do with $.Deferred() objects, if you are using jQuery for your ajax calls.
If you have lots of ajax calls returning elements on your page then the only way to know when they have all finished is to keep track of them and use their callbacks to work out when its all loaded. The load or ready events on the page are only concerned with resources loaded through the html and not loaded via asynchronous requests. Asynchronous being the key bit here.
If I were you I would have two global variables: totalNumberOfCalls & finishedCalls
At the start of my page I would set totalNumberOfCalls to the correct number, then on each callback I would have a small bit of code similar to this:
if (++finishedCalls == totalNumberOfCalls) console.log('Page Loaded'); else console.log( (finishedCalls / totalNumberOfCalls) * 100 + '% loaded');
This way you can easily add a simple counter to work out the progress.
If you are loading images and other external elements then it might be worth doing the counting on the load events of the returned elements so you get the actual finished loading time and not time when the request has returned but not any associated resources.
If this all seems a little too much, then just make the ajax calls synchronous instead, that way you page will stall while the calls are going on. This is not good practice though.
Javascript javascript which all elements are loaded
Please note that assigning the contents (which have to be HTML to work properly) to clears out the DOM subtree of your container so that you can assign new content to it without having to worry about any event handlers or outdated DOM nodes. Any resources loaded from the remote source are not involved in this process at all so you don’t risk multiple runs of this function, and every time that new content is loaded into the container, the old one is effectively overwritten.
How to ensure that all elements are loaded on an html page, and then we perform some modifications on elements in CSS?
I fixed this in my code using this,
You cannot modify the CSS anywhere in the code. It has to be modified only when the search bar has been loaded with all its sources. I tried adding a $document.ready(function()<>); or adding the css at the end of the body. Nothing worked because we are using a different javascript library/toolkit here — Dojo. Hence, we can only performs operations based on how the data is loaded or when call backs are called in Dojo. and not in normal HTML javascript to jQuery.
How to load javascript after all DOM element rendered in Vanilla, You have 2 options, as Maxzeroedge commented, you can add a listener to the load event in the DOM so that block gets executed after all the
Javascript check if all clicks have completed loading elements
Well you could enclose your loading elements in an .ajaxComplete()
Thus you trigger the behavior of your extra function when all ajax events are done on a specific container/selector.
In this case you can still make use of jQuery.ajaxStop(). It will fire when all your ajax events have completed.
How to wait for elements to be loaded in DOM in JavaScript?, Define them globally and set the with DOMContentLoaded. let char; let num; window.addEventListener(‘DOMContentLoaded’, function() < char
Script can’t get elements on page load JS
If you have no idea regarding when and how the class ‘collapsible’ is added to your DOM, you might want to consider using a MutationObserver interface, which provides the ability to watch exactly for changes being made to the DOM tree.
// Callback function to execute when mutations are observed var callback = function(mutationsList) < if (document.getElementsByClassName('collapsible').length >0) < // YOUR CODE HERE . this.disconnect(); >>; // Create an observer instance linked to the callback function var observer = new MutationObserver(callback); // Select the node that will be observed for mutations // this is targeting the whole html tree, you can narrow it if you want var targetNode = document.documentElement; // Options for the observer (which mutations to observe) var config = < attributes: true, childList: true, subtree: true >; // Start observing the target node for configured mutations observer.observe(targetNode, config);
In this way, your code will actually wait for the class ‘collapsible’ to be added to your DOM before being executed.
BTW, I would not produce a code which is relying on someone else’s code: if you are not in control of the class ‘collapsible’ you are preparing your code for failure .
There is a solution to get things done. This method will do the trick providing that any resources to be loaded are returned as HTML .
function load_content(p_rsrc) < var l_request = new XMLHttpRequest(); l_request.addEventListener('readystatechanged', function(p_event) < if(this.readystate == 4) // We wind up here once AJAX reports the request to be completed (either because of a timeout or because of a reaction from the server) if(this.status == 200) < let l_col; let l_target = document.getElementById('div-for-remote-content'); let l_this; if(l_target == null) < console.error('FATAL: Could not find container for remote content!'); throw "internal error"; >// Assign the received contents to the container // This clears out any previous content, including any event handlers, before adding the new content. l_target.innerHTML = l_request.responseText; // Once we are here we can attach event handlers to any element that brings along the "collapsible" class. // The following statement digs up all elements of the collapsible class that are present in their container. l_col = document.querySelectorAll('#div-for-remote-content .collapsible'); // Now dig through the entire list of items. for(l_this of l_col) < l_this.addEventListener("click", function(p_event) < p_event.target.classList.toggle("active"); if (p_event.target.style.display === "block") p_event.target.style.display = "none"; else p_event.target.style.display = "block"; >, false); > > // You can do some additional status handling here, like dealing with any errors >, false); l_request.open('GET', p_rsrc, true); l_request.send(); >
As you can see the event listeners are attached outside of the scope of the loaded new content if and only if the AJAX request returned with a success (that is, status code 200). Any other status code won’t allow the script to modify the contents of your container, and I have also added some rudimentary sanity checks.
Please note that assigning the contents (which have to be HTML to work properly) to .innerHTML clears out the DOM subtree of your container so that you can assign new content to it without having to worry about any event handlers or outdated DOM nodes. This avoids duplicate invocation of your event handler and also allows for attaching this function to a button as an event handler (or invocation from another script block). Please note that you have to pass the path to the desired resource to this function.
Corrected a bug in my code snippet
When you import this code into your document you need to make sure that it gets invoked whenever someone loads extra content into the document. You can do that by attaching a wrapper function to whatever mechanism is required to facilitate this (i. e. a button that triggers an event handler which in turn calls this function and also provides the URL of the resource to be loaded).
Once load_content() is called, the following sequence of events is set off:
- Create an XMLHttpRequest (required to perform an AJAX request for the desired resource).
- Attach an event handler to the XMLHttpRequest object that listens for ready state transitions (so we can determine when the response is available for use).
- Open the resource for retrieval. Please note that the third parameter is set to true to make this an asynchronous request.
- Send the request. The XMLHttpRequest immediately returns, but since we are listening for readystatechange events we detect once the request has been processed. In the meantime other things may be taken care of.
- Eventually the request is answered, the readystatechange event fires, and our request reports that the request has been completed ( this.readyState == 4 ). This is our signal that we can begin processing the resource.
- Check whether the request has been successful (i. e. this.status == 200 ). If not, something has gone wrong and everything should be left untouched.
- Otherwise see whether the container exists. If not, log to the console and throw an exception (safeguard against an unknown element).
- Assign the response text to the .innerHTML of our container. The old content is discarded, and a new DOM subtree is constructed in said container.
- Get a list of all elements that belong to the collapsible class and reside in our container.
- For every element thus found repeat: Attach an event handler that listens for click events and which, when invoked, toggles the visibility of the elemet in question.
Any resources loaded from the remote source are not involved in this process at all so you don’t risk multiple runs of this function, and every time that new content is loaded into the container, the old one is effectively overwritten.
This function will keep looking for a specific class on a target element:
function checkElement(selector, cb) < var raf; var found = false; (function check() < const el = document.querySelector(selector); if (el) < found = true; cancelAnimationFrame(raf); // Do something here console.log('Found it'); // Include your logic in the callBack cb(); >else < raf = requestAnimationFrame(check); >>)(); return found; >
checkElement('collapsibile', elementReady); function elementReady() < var coll = document.getElementsByClassName("collapsible"); var i; for (i = 0; i < coll.length; i++) < coll[i].addEventListener("click", function() < this.classList.toggle("active"); var content = this.nextElementSibling; if (content.style.display === "block") < content.style.display = "none"; >else < content.style.display = "block"; >>); > >;
It acts like a «watcher». You can modify the check function of course as you see fit. Using document.querySelector(selector); will match only the first element in the DOM.
I’d use EventDelegation probably in your case but my understanding is that you are after something else.
Onload function runs before loading of all elements, I have only one js file linked to my page, and below I showed how I organized the code (hope its a right way). I have also put a broken img link