Javascript Mirror html object - javascript

Basically I have html with variables
html = `<div>${product.id}<img src="${product.src}"/></div>`
then I update the dom simply with
document.querySelector('.container').innerHTML = html;
so far so good, problem is the html contains images and everytime I update, the page flickers, I was thinking if there was a more unintrusive method to only update the changed values

Hide the images when appending to DOM, then toggle visibility when the image finishes loading. https://jsfiddle.net/ftpd9sxz/
function showImage() {
this.style.visibility = 'visible';
}
let product = {
id: 2,
src: "https://pbs.twimg.com/profile_images/1010263656456744960/bXOUw0hb_bigger.jpg"
}
let html = `<div>${product.id}<img src="${product.src}" style="visibility: hidden" /></div>`;
document.querySelector('.container').innerHTML = html;
document.querySelector('.container img').addEventListener("load", showImage);

Related

How can I fetch data with jquery .load, only when the target page's DOM is loaded?

I have this page where I have a ranking system. For the ranking to display I create some elements on a loop through javascript, according to the data that I fetch from the database. Then, I want the data to change when the database changes, but instead of having to reload the page, I want it to reload just the div related to the ranking content. The problem is that when I call the function $(#idOfRankingsParent).load("index.php #idOfRankingsChild), it doesn't load anything because the content is only created after the DOM is fully loaded (because of the document.createElement, and appendChild, etc). Is there any way for me to load the content after every element is created?
So, I have this function being called on a setInterval:
function loadContent() {
console.log("loaded");
$( "#ranking-container" ).load("index.php #ranking-wrapper");
rankingList.style.filter="blur(0)";
}
setInterval(loadContent, 5500);
Then I have this function creating the elements, and being called as soon as possible:
function createRanks() {
(...)
var pontosOrdered = x;
var equipasOrdered = y;
for (var t=0; t<equipasOrdered.length; t++) {
var rankLi = document.createElement("li");
rankingList.appendChild(rankLi);
if (t===0) {rankLi.id="first-place";}
if (t===1) {rankLi.id="second-place";}
if (t===2) {rankLi.id="third-place";}
var lugarP = document.createElement("p");
rankLi.appendChild(lugarP);
lugarP.classList.add("lugar");
lugarP.innerHTML=t+1;
var nomeEquipaP = document.createElement("a");
rankLi.appendChild(nomeEquipaP);
nomeEquipaP.innerHTML=equipasOrdered[t];
nomeEquipaP.href="/equipas/#"+nameToLowerCase(equipasOrdered[t]);
var pontosP = document.createElement("p");
rankLi.appendChild(pontosP);
pontosP.classList.add("pontos");
pontosP.innerHTML=pontosOrdered[t];
}
}
$(document).ready(function() {
createRanks();
});
(edited)
I have here some prints of the page when I load the first time:
And when the div loads:

Show LOADING in innerHTML while object is being loaded

I have following JavaScript function that load contents return by contacts.php into DIV id contacts-container, it takes a lot of time to complete the task. I want to show "LOADING.." text in the DIV id contacts-container while contents are being loaded.
function load_contacts() {
document.getElementById("contacts-container").innerHTML='<object type="text/html" data="contacts.php" ></object>';
}
I want solution in pure JavaScript.
What about some more JS?
function load_contacts() {
var el = document.createElement("object"),
target = document.getElementById("contacts-container")
target.innerHTML = "<span>Loading...</span>";
el.onload = function() {
target.firstChild.remove();
}
el.setAttribute("type","text/html");
el.setAttribute("data","contacts.php");
target.appendChild(el);
}
You can do with ajax. For this my suggestion, you must Jquery Ajax. For example,
$("#loadingElement").html("Loading");
$.load("#contacts-container",{},"contacts.php",function(){
$("#loadingElement").html("");
});

reload div javascript only ajax needed?

please refer to JSFiddle link: https://jsfiddle.net/s11oo2gg/.
We are not allowed to use jQuery and iframe here.
The problem right now if you click on resistor first and hover over different content images then come back out by clicking the X mark, the content image would get stucked where you left off and would not load the the other content images properly. It would show a broken image link.
I like to reload only the <div id="slider1_contain"> everytime I click on <span class="closeButton">(X mark) so the target content images can be loaded accordingly.
I dont not want to have location.reload(); to resolve this when the X is click. I dont want to reload the whole page but only the div.
I saw people were asking the same question and solve it with AJAX. Do I need AJAX for this case? Or is there something we can do in the following javascript?
Thank you in advance!!
<script type="text/javascript">
function showContent(target){
document.getElementById(target).style.display = 'block';
document.getElementById("boxThumb").style.display = 'none';
}
function hideContent(target){
document.getElementById(target).style.display = 'none';
document.getElementById("boxThumb").style.display = 'block'
}
</script>
<script type="text/javascript">
var children = document.querySelectorAll('.toggle > section[id]');
function showDetailContent(target) {
// Simply loop over our children and ensure they are hidden:
for (var i = 0, child; child = children[i]; i++) {
child.style.display = 'none';
}
// Now, show our child we want to show
document.getElementById(target).style.display = 'block';
}
</script>
If you want to reload just the div, you can use innerHTML.
document.getElementById(target).innerHTML = '<img src="image.jpg">';

Don't load scripts appended with innerHTML?

I'm appending a whole HTML page to a div (to scrape). How do I stop it from requesting script, and css files ? I tried immediately removing those nodes but they still get requested.
It's for a browser addon, I'm scraping with JS
As #adeneo wrote you don't have to add the html to a page in order to scrape information from it, you can turn it into DOM tree that is disconnected from the page DOM and process it there.
In jQuery it is simple $("html text here"). Then you can scrape it using the API,
eg.
function scrape_html(html_string) {
var $dom = $(html_string);
var name = $dom.find('.name').text();
return name;
}
without jQuery:
function scrape_html(html_string) {
var container = document.createElement('div');
container.innerHTML = html_string;
var name = container.getElementsByClassName('name')[0].innerText;
return name;
}
Setting the innerHTML of a temporary HTML element that has not been added to the document, will not execute scripts, and since it does not belong to your document, the style will not be applied either.
This will give you an opportunity to strip out any unwanted elements before copying the innerHTML to your own document.
Example:
var temp = document.createElement('div');
temp.innerHTML = html; // the HTML of the 'other' page.
function removeElements(element, tagName)
{
var elements = temp.getElementsByTagName(tagName);
while(elements.length > 0)
{
elements[0].parentNode.removeChild(elements[0]);
}
}
removeElements(temp, 'script');
removeElements(temp, 'style');
removeElements(temp, 'link');
container.innerHTML = temp.innerHTML;

How to prevent iframe load event?

I have an iframe and couple of tables on my aspx page. Now when the page loads these tables are hidden. The iframe is used to upload file to database. Depending on the result of the event I have to show a particular table on my main page (these tables basically have "Retry","next" buttons...depending on whether or not the file is uploaded I have to show respective button).
Now I have a JavaScript on the "onload" event of the iframe where I am hiding these tables to start with. When the control comes back after the event I show a particular table. But then the iframe loads again and the tables are hidden. Can any one help me with this problem. I don't want the iframe to load the second time.
Thanks
mmm you said you're on aspx page,
I suppose that the iframe do a postback, so for this it reload the page.
If you can't avoid the postback, you've to set a flag on the main page just before posting back, and check against that while you're loading...
...something like:
mainpage.waitTillPostBack = true
YourFunctionCausingPostBack();
..
onload=function(){
if(!mainpage.waitTillPostBack){
hideTables();
}
mainpage.waitTillPostBack = false;
}
I am not sure what your problem is, but perhaps your approach should be a little different. Try putting code into the iframe what would call functions of the parent. These functions would display the proper table:
<!-- in the main page --->
function showTable1() {}
<!-- in the iframe -->
window.onload = function () {
parent.showTable1();
}
This would put a lot of control into your iframe, away from the main page.
I don't have enough specifics from your question to determine if the iframe second load can be prevented. But I would suggest using a javascript variable to check if the iframe is being loaded a second time and in that case skip the logic for hiding the tables,
This is my code
function initUpload()
{
//alert("IFrame loads");
_divFrame = document.getElementById('divFrame');
_divUploadMessage = document.getElementById('divUploadMessage');
_divUploadProgress = document.getElementById('divUploadProgress');
_ifrFile = document.getElementById('ifrFile');
_tbRetry = document.getElementById('tbRetry');
_tbNext=document.getElementById('tblNext');
_tbRetry.style.display='none';
_tbNext.style.display='none';
var btnUpload = _ifrFile.contentWindow.document.getElementById('btnUpload');
btnUpload.onclick = function(event)
{
var myFile = _ifrFile.contentWindow.document.getElementById('myFile');
//Baisic validation
_divUploadMessage.style.display = 'none';
if (myFile.value.length == 0)
{
_divUploadMessage.innerHTML = '<span style=\"color:#ff0000\">Please select a file.</span>';
_divUploadMessage.style.display = '';
myFile.focus();
return;
}
var regExp = /^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.doc|.txt|.xls|.docx |.xlsx)$/;
if (!regExp.test(myFile.value)) //Somehow the expression does not work in Opera
{
_divUploadMessage.innerHTML = '<span style=\"color:#ff0000\">Invalid file type. Only supports doc, txt, xls.</span>';
_divUploadMessage.style.display = '';
myFile.focus();
return;
}
_ifrFile.contentWindow.document.getElementById('Upload').submit();
_divFrame.style.display = 'none';
}
}
function UploadComplete(message, isError)
{
alert(message);
//alert(isError);
clearUploadProgress();
if (_UploadProgressTimer)
{
clearTimeout(_UploadProgressTimer);
}
_divUploadProgress.style.display = 'none';
_divUploadMessage.style.display = 'none';
_divFrame.style.display = 'none';
_tbNext.style.display='';
if (message.length)
{
var color = (isError) ? '#008000' : '#ff0000';
_divUploadMessage.innerHTML = '<span style=\"color:' + color + '\;font-weight:bold">' + message + '</span>';
_divUploadMessage.style.display = '';
_tbNext.style.display='';
_tbRetry.style.display='none';
}
}
tblRetry and tblNext are the tables that I want to display depending on the result of the event.

Categories

Resources