On my webpage I have a piece of JavaScript to reload/refresh an iframe every three seconds.
window.setInterval(function() {
reloadIFrame()
}, 3000);
function reloadIFrame() {
var frame = document.getElementById("iframe");
var len = frame.getElementsByTagName("TABLE").length;
if ( len == 0 ){
console.log('reloading..');
document.getElementById('iframe').contentWindow.location.reload();
}
}
However, I don't want the function to work when there is a table present in the iframe, and it still runs when there is a table. Please let me know if there is something I am missing or your suggestions for alternative solutions.
(I do believe that the iframe which I am referencing is local on localhost:8000. I'm working with Django, if that matters, and this is part of a template.)
For anyone with a similar problem:
As in charlietfl's comments on the original post, the contentWindow was not being referenced. My code as modified below works now:
window.setInterval(function() {
reloadIFrame()
}, 3000);
function reloadIFrame() {
var frame = document.getElementById("iframe");
var len = frame.contentWindow.document.getElementsByTagName("TABLE").length;
if ( len == 0 ){
console.log('reloading..');
document.getElementById('iframe').contentWindow.location.reload();
}
}
I simply needed to add contentWindow.document after frame.
Related
I try to combine 2 defer functions init to 1 Java script.
I actually try now combine another one but he make conflict and the JS very heavy. this is 2 different script + 1 is not so important (but if you guys succeed help me combine all of them perfectly is be better).
This the code I try put after I edit him 2( 2 functions init ):
function init() {
var imgDefer = document.querySelectorAll('div[data-src]');
var style = "background-image: url({url})";
for (var i = 0; i < imgDefer.length; i++) {
imgDefer[i].setAttribute('style', style.replace("{url}", imgDefer[i].getAttribute('data-src')));
}
imgDefer = document.getElementsByTagName('img');
for (var i = 0; i < imgDefer.length; i++) {
if (imgDefer[i].getAttribute('data-src')) {
imgDefer[i].setAttribute('src', imgDefer[i].getAttribute('data-src'));
}
}
}
window.onload = init;
I make him a short too... he defers the images but slower the site:
function init(){for(var t=document.querySelectorAll("div[data-src]"),e=0;e<t.length;e++)t[e].setAttribute("style","background-image: url({url})".replace("{url}",t[e].getAttribute("data-src")));t=document.getElementsByTagName("img");for(e=0;e<t.length;e++)t[e].getAttribute("data-src")&&t[e].setAttribute("src",t[e].getAttribute("data-src"))}window.onload=init;
(you can look the code is deferred on the website: locksmithunit.com)
but he very slow on the page load.
and this all the original codes... these codes are for deferring images
and the last one is for "frame"
the frame not so important. and if you can give me him separately because
have pages I don't have iframe.
please help me guys, i very lost.
I most combine at least the first 2 scripts from all the 3 I send now:
<script>
function init() {
var imgDefer = document.getElementsByTagName('img');
for (var i=0; i<imgDefer.length; i++) {
if(imgDefer[i].getAttribute('data-src')) {
imgDefer[i].setAttribute('src',imgDefer[i].getAttribute('data-src'));
} } }
window.onload = init;
<script>
<script>
function init() {
var imgDefer = document.querySelectorAll('div[data-src]');
var style = "background-image: url({url})";
for (var i = 0; i < imgDefer.length; i++) {
imgDefer[i].setAttribute('style', style.replace("{url}", imgDefer[i].getAttribute('data-src')));
}
}
window.onload = init;
</script>
<script>
function init() {
var vidDefer = document.getElementsByTagName('iframe');
for (var i=0; i<vidDefer.length; i++) {
if(vidDefer[i].getAttribute('data-src')) {
vidDefer[i].setAttribute('src',vidDefer[i].getAttribute('data-src'));
} } }
window.onload = init;
</script>
ok. so I try to defer images on my website... on 120 pages...
now, when i start, i was able to defer only images.
after that, I succeed defer the background-image: url().
but it is different JS as you see on the example I post before.
I succeed combine them but still, the JS no give full power.
after that, I start to fix again pages and i notice have google maps iframe
in couple of pages. ( something like 40 pages).
and I try to defer the iframe as well but it was too much for the javascript and the website loses the page load...
the JS needs to rewriting again...
i try a couple of variations as I post before, but none of them really improve the page load.
if we sucssed fix the Javascript at least put the 2 functions inside JS, JS of the background and images you will save me because I already edit all the 120 pages and the JS work and defer, but damage the page load because the JS is not written well.
(iframe is not so important like the images and the background)
I got X DIV (TopRowRight1, TopRowRight2, TopRowRight3...) , each containing a different Google Geochart generated by a php page : GeochartPerProvince.php?template=X.
function getResult(template){
jQuery.post("GeochartPerProvince.php?template="+template,function( data ) {
jQuery("#TopRowRight"+template).html(data);
});
}
jQuery().ready(function(){
getResult(1);
setInterval("getResult(1)",10000);
getResult(2);
setInterval("getResult(2)",10000);
getResult(3);
setInterval("getResult(3)",10000);
});
jQuery(function () {
var $els = $('div[id^=TopRowRight]'),
i = 0,
len = $els.length;
$els.slice(1).hide();
setInterval(function () {
$els.eq(i).fadeOut(function () {
i = (i + 1) % len
$els.eq(i).fadeIn();
})
}, 5000)
});
Every 5 seconds, i fade out one and fade in the next one. This works perfectly.
For now, the php page in the DIV is refreshed every 10 seconds. This works too.
But what i dream about is that the php page in the DIV is reloaded AFTER the DIV is faded out instead of every 10 seconds. How to do it?
Solved. How it works properly:
function getResult(template){
jQuery.post("GeochartPerProvince.php?template="+template,function( data ) {
jQuery("#TopRowRight"+template).html(data);
});
}
$(document).ready(function(){
getResult(0);
getResult(1);
getResult(2);
//setInterval("getResult(2)",10000); <== keep this piece of code in case of need.
});
$(document).ready(function () {
var $els = $('div[id^=TopRowRight]'),
i = 0,
len = $els.length;
$els.slice(1).hide();
setInterval(function () {
$els.eq(i).fadeOut(function () {
i = (i + 1) % len
getResult(i);
$els.eq(i).fadeIn();
})
}, 10000)
});
You're already using a callback function after the element has been faded out. So why not call your getResult function inside it?
$el.fadeOut(function(){
// stuff
getResult(i)
})
I have a few suggestions and an example code for you to achieve what you need :
Use $ instead of jQuery for easier reading / writing
$(document).ready is the proper start point for dom related functions
If only one div is visible at a time, do not use too many divs. Most of the time one div is enough for alternating / refreshing content. If there is in/out animation or cross-fading, two divs would be needed. (Example below uses two divs)
Avoid using setInterval except you really really need. Logics with setTimeout better handles unexpected delays such $.post may cause.
start with html code something like this:
...
<div class="top-row-right" style="display:block"></div>
<div class="top-row-right" style="display:none"></div>
...
js:
$(document).ready( function() {
var len = 4; // 'I got X DIV..' This is where we put the value of X.
var template = -1;
function refreshChart() {
template = (template + 1) % len;
$.post("GeochartPerProvince.php?template="+template, function(data) {
var offscreenDiv = ('.top-row-right:hidden');
var onscreenDiv = ('.top-row-right:visible');
offScreenDiv.html(data);
onScreenDiv.fadeOut('slow', function() {
offScreenDiv.fadeIn();
setTimeout(refreshChart, 10000);
});
});
}
refreshChart();
});
Can someone please help me with this script? It is to detect adblock. I have <script src="/js/ads.js"></script> in the head (a empty ads.js in the folder). Adblock will block this from loading thus not being on the page. Then I have the code below that will detect if the script is loaded or not. For some reason it is not working properly and still displays images. I had someone write the script below as well for it to check for ads 3 times with a 1 second interval but it seems to check infinitely 3 times at once. Can someone please help me work this properly? And also if it detects that it does load properly it won't keep pasting images into the div?
<script>
$(document).ready(function () {
var count = 3;
for (var i = 0; i < count; i++) {
setInterval(function () {
if (window.canRunAds === undefined) {
$('#StEQBidTjU').prepend('<img src="/miscimg/mZKoARJXcF.jpg" id="PtZZtkYjaR" />')
$('#AbHPbbbxyl').prepend('<img src="/miscimg/6hZ4nqcBZd.jpg" id="PLyCMzOHpx" />');
}
}, 1000);
}
});
</script>
You need to keep track of the count in each interval, and clear it once it's ran 3 times.
$(document).ready(function () {
var count = 3,
interval = setInterval(function () {
if (--count < 0) {
clearInterval(interval);
}
if (window.canRunAds === undefined) {
$('#StEQBidTjU').prepend('<img src="/miscimg/mZKoARJXcF.jpg" id="PtZZtkYjaR" />')
$('#AbHPbbbxyl').prepend('<img src="/miscimg/6hZ4nqcBZd.jpg" id="PLyCMzOHpx" />');
}
}, 1000);
});
Now you don't even need to do all these to detect AdBlock users, You can achieve this using a simple JS script called ABDetector
Here's how to use it:
- Download/Clone the project, upload the file abDetector.min.js
- Put this in your <head>:
<script type="text/javascript" src="abDetector.min.js"></script>
- Use this wherever you want to display a message to AdBlock users:
<div id="ab-message" style="display: none">Your message here!</div>
Then you're done. Check out the project on Github.
I'm a beginner in JS and want to know a way to simplify this code. There are 7 different divs with iframes, and also 7 different links. I have shown 1 div with iframe and 1 link. I have no idea where to start. Any help would be greatly appreciated.
NOTE: The code works to my needs, but I just need to simplify it (less js code in html, and more in js file).
JavaScript in .js file:
function show_visibility(){
for(var i = 0,e = arguments.length;i < e;i++){
var myDiv = document.getElementById(arguments[i]).style;
myDiv.display = "block";}
}
function hide_visibility(){
for(var i = 0,e = arguments.length;i < e;i++){
var myDiv = document.getElementById(arguments[i]).style;
myDiv.display = "none";}
}
function refFrame() {
for(var i = 0,e = arguments.length;i < e;i++){
document.getElementById(arguments[i]).src = document.getElementById(arguments[i]).src;
}
}
Div/iframe to be modified:
<div id="r1-box">
<iframe id="frame-box1" class="work" src="youtubelink" width="720" height="405" frameborder="0"></iframe>
</div>
Link to execute JS:
<a id="r1" href="javascript:refFrame('frame-box2','frame-box3','frame-box4','frame-box5','frame-box6','frame-box7');show_visibility('r1-box');hide_visibility('r2-box','r3-box', 'r4-box','r5-box','r6-box','r7-box');">
</a>
As a beginner you shouldn't start using jQuery until you understand Javascript more.
There are a few ways you could simplify this, the most immediate one would be to get the Javascript out of the link and into a Javascript file, or at the top of the page:
window.onload = function() {
document.getElementById('#r1').onclick = function() {
refFrame('frame-box2','frame-box3','frame-box4','frame-box5','frame-box6','frame-box7');
show_visibility('r1-box');
hide_visibility('r2-box','r3-box', 'r4-box','r5-box','r6-box','r7-box');
};
// more...
};
window.onload is an event which fires once the page has - you guessed it - finished loading. There are better ways of doing this, but this is about as basic as it gets. I'd advise you look at javascript domready?
After looking at your code a bit more, I realised all your seven links will do essentially the same thing. You can simply this by using a single function:
function refClick(id) {
var i = 7,
frames = [],
boxes = [];
while(i--) {
if(i != id) {
frames.push('frame-box' + i);
boxes.push('r' + i + '-box');
}
}
refFrame.apply(null, frames);
hide_visibility.apply(null, boxes);
show_visibility('r' + id + '-box');
}
What I'm doing here is looping through 7 times, and building an array of arguments for the refFrame and hide_visibility functions. The id variable tells the loop not to put in that id into the arrays.
Using the .apply method, I can apply an array as the arguments and call it normally.
For each of your links, you can apply the following function
document.getElementById('#r1').onclick = function() {
refClick(1);
};
document.getElementById('#r2').onclick = function() {
refClick(2);
};
//.....
You could start using jQuery.
http://jquery.com/
I had written one JS in asp.net. I had called that from body onload, but the JS doesn't get called where I have put my debugger. What could be possible reasons for this? I'm developing website in dotnetnuke.
The JS I have written is syntactically and logically correct.
<script type="text/javascript">
var displayTime, speed, wait, banner1, banner2, link1, link2, bannerIndex, bannerLocations, bannerURLs;
function initVar() {
debugger;
displayTime = 10; // The amount of time each banner will be displayed in seconds.
speed = 5; // The speed at which the banners is moved (1 - 10, anything above 5 is not recommended).
wait = true;
banner1 = document.getElementById("banner1");
banner2 = document.getElementById("banner2");
//link1 = document.getElementById("link1");
//link2 = document.getElementById("link2");
//banner1 = document.getElementById("banner1");
//banner2 = document.getElementById("banner2");
banner1.style.left = 0;
banner2.style.left = 500;
bannerIndex = 1;
/* Important: In order for this script to work properly, please make sure that the banner graphic and the
URL associated with it have the same index in both, the bannerLocations and bannerURLs arrays.
Duplicate URLs are permitted. */
// Enter the location of the banner graphics in the array below.
//bannerLocations = new Array("internet-lg.gif","jupiterweb.gif","jupitermedia.gif");
bannerLocations = new Array("image00.jpg", "image01.jpg", "image02.jpg", "admin_ban.bmp");
// Enter the URL's to which the banners will link to in the array below.
bannerURLs = new Array("http://www.internet.com","http://www.jupiterweb.com","http://www.jupitermedia.com");
}
function moveBanner() {
//debugger;
if(!wait){
banner1.style.left = parseInt(banner1.style.left) - (speed * 5);
banner2.style.left = parseInt(banner2.style.left) - (speed * 5);
if(parseInt(banner1.style.left) <= -500){
banner1.style.left = 500;
bannerIndex = (bannerIndex < (bannerLocations.length - 1)) ? ++bannerIndex :0;
banner1.src = bannerLocations[bannerIndex];
//link1.href = bannerURLs[bannerIndex];
wait = true;
}
if(parseInt(banner2.style.left) <= -500){
banner2.style.left = 500;
bannerIndex = (bannerIndex < (bannerLocations.length - 1)) ? ++bannerIndex :0;
banner2.src = bannerLocations[bannerIndex];
//link2.href = bannerURLs[bannerIndex];
wait = true;
}
setTimeout("moveBanner()",100);
} else {
wait = false;
setTimeout("moveBanner()", displayTime * 1000);
}
}
</script>
REGISTRATION IN JS
<body onload="initVar(); moveBanner();">
</body>
I ran your code. Both methods executed without me having to make any modifications to the posted code. Is there possibly some other code that is overwriting the onload method?
The DotNetNuke best practice for binding to the "onload" property in JavaScript is to hook into JQuery's ready() method:
jQuery(document).ready( function() {
// put your code here
initVar();
moveBanner();
});
DotNetNuke 4.9.x and later ship with the jQuery JavaScript library included.
Have you edited DNN's Default.aspx? Otherwise, there isn't any way for you to have access to the body tag to add the onload attribute like you show.
How are you injecting this script? Are you using a Text/HTML module, are you using the Page Header Text setting for the page, are you adding it directly to the skin, have you written a custom module, or something else?
Instead of using the onload attribute on the body tag, I would suggest wiring up to that event in the script itself. If you're using any code to inject the script, you can ask DNN to register jQuery or a ScriptManager (for ASP.NET AJAX) so that you can use those libraries to wire the event up easily. If you can't guarantee that those are on the page, use the following:
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(function () {
initVar();
moveBanner();
});
I don't know much about asp.net but if you can put javascript code in your page, then you can try this alternative:
window.onload = function()
{
// any code here
}
This is the same as what you put in body tag.
The CSS left property takes a length, not an integer. You must have units for non-zero lengths. (Even when setting it using JavaScript!).