Scrolling Iframe - javascript

I have two windows: One is a page meant to be in an iframe, and one is the page meant to house the iframe. The objective of my project is to make an iframe that scrolls, but, when it is moused over, it pauses. I currently have the following code for the page meant to be in an iframe:
http://dabbler.org/edit/asdf/scrolling/index.html
and the code for the page meant to house the iframe:
http://dabbler.org/edit/asdf/scrolling/index2.html
What is wrong with my code? (Yes, I know I don't have body, head, HTML and the others, that isn't the problem, for those are thrust in automatically when the page is interpreted)

The window.onmouseover and window.onmouseout are not defined correctly.
You have this:
window.onmouseout = pageScroll();
window.onmouseover = unpageScroll();
You want to do this:
window.onmouseout = pageScroll;
window.onmouseover = unpageScroll;
You were setting onmouseout, and onmouseover to the return values of calling pageScroll and unpageScroll, but you wanted to set onmouseout/onmouseover the functions pageScroll and unpageScroll.
And finally, you're calling the wrong function in your setTimeout.
You are calling pageScroll, but you want to be calling pageScroller, which does the actual scrolling.
EDIT
function pageScroll(){
num = 150;
clearTimeout(scrolldelay);
pageScroller();
}
function unpageScroll(){num = 15000000;}
function pageScroller() {
window.scrollBy(0,50); // horizontal and vertical scroll increments
scrolldelay = setTimeout('pageScroller()',num); // scrolls every 100 millisecond
}
var num = 50;
window.onmouseout = pageScroll;
window.onmouseover = unpageScroll;
BTW, you should handle calling clearTimeout in pageScroller at some point in the future when the page is scrolled vertically as much as possible. There's no point in continuing to call scrollBy if the window is already scrolled as much as possible.

Related

How to clear these intervals?

I'm creating my own JSFiddle-like webapp and I want to implement elements resizing, but keep document height unchanged, so I have to recalculate elements dimensions on each resize.
I have this script:
var a = setInterval(setHeight, 1);
var b = setInterval(formsWidth, 1);
iframe.onResizeStart = a;
html.onResizeStart = b;
iframe.onResizeStop = clearInterval(a);
html.onResizeStop = clearInterval(b);
Iframe is an element where user codes are rendered and HTML is one of my three textareas. I want this script to recalculate textareas heights on iframe resize and recalculate their widths on changing width of one of them.
I managed to make this work, but I couldn't stop intervals and I need help with it.
The above code doesn't work now at all, probably because of calling a variable onResizeStart.
I'd be grateful if someone could help me.
I prefer not to use jQuery.
It doesn't work because you're calling clearInterval() almost immediately after calling setInterval(), so the intervals are never getting a chance to execute. You'll need to store away a and b and then call clearInterval() on them at a later time, after the resizing is all done.
EDIT: Looking at this more closely, just wrap each call to clearInterval() in a function. That way clearInterval won't get executed immediately, but rather when the onResizeStop event is fired.
iframe.onResizeStop = function() { clearInterval(a); };

How can I resize the iframe without page refresh?

I have some swf embedded in iframe but only if the page is refreshed the iframe is resized, then if I select other one then will show as all swf not only the animation the background as well. This is what I am using
if ( 'resizeIframe' === $('#onPlayAction').val() ) {
var ifrEl = $('div.player-container iframe.page-iframe')[0];
$(ifrEl).show();
ifrEl.src = htmlPageBrowserUri;
ifrEl.onload = function() {
ifrEl.width = ifrEl.contentWindow.document.body.scrollWidth;
ifrEl.height = ifrEl.contentWindow.document.body.scrollHeight;
}
}
There are three ways to do this.
You can change the size on every window resize
$(window).on('resize', function (){
ifrEl.width = ... ;
ifrEl.height = ... ;
})
You can use some jQuery plugins like iFrame Resizer
You can use some nifty css tricks. Go search for responsive iframes using css and you will find a ton of good answers.
I hope this all helps you.
I suspect the issue with your code might be thses two lines :
ifrEl.src = htmlPageBrowserUri;
ifrEl.onload = function() {
The problem being that the first line set s the frame address, but second line sets the onload event immediately, probably before the page has loaded ? So when the page does load, the line setting onload event has already run & so doens't get set.
I don't quite understand the text in your question (sorry!) but the code below successfully resizes an iframe - it's run 'onload' in the frame's page:
<body onload="setParent()">
In case it's relevant, the iframe itself has attributes:
<iframe id="neckfinishframe" style="width:100%;overflow-x:hidden" src=".. etc">
In my case I'm only concerned about height. Width is 100%.
In the iFrame page, this code runs from the onload event to amend the iframe height to be whatever the height of the page is, plus a bit. This is intended to avoid showing a set of scroll bars within the iframe.
function setParent() {
// runs onload in iframe page
// in my case I have to run it from the frame page because I need to know the page rendered height in order to set the iframe height
var f;
try {f = parent.getElementById("neckfinishframe")} catch (e) {};
if (f != null) f.style.height=(this.document.body.scrollHeight+30)+"px";
}
Note - I haven't tried this cross- browser but I know it works in IE.

How to properly scroll IFrame to bottom in javascript

For a mockup-webpage used for research on interaction on websites, I created a mockup message-stream using JavaScript. This message stream is loaded in an IFrame and should show images at pre-set intervals and scroll to the bottom of the page after placing a new image at the bottom of the page. Getting the images to appear is working quite well with the provided script. However, both Chrome and IE seem to have trouble scrolling the page to the bottom. I would like to scroll to the bottom of the page as soon as the image is attached, but have for now added a 5 ms delay because that seemed to work sometimes. My questions are:
Is it okay to use document.body.scrollHeight for this purpose?
Can I make the scroll occur directly, or do I need a small interval before scrolling?
How to make the code scroll to the bottom of the IFrame directly after adding an image?
The following functions are used and trypost() is started onLoad:
function scrollToBottom(){
window.scrollBy(0,document.body.scrollHeight);
}
function trypost(){
point = point + 1;
if(point < interval.length){
//create and append a new image
var newImg = document.createElement("IMG");
newImg.src = "images/"+images[point]+".png";
document.getElementById('holder').appendChild(newImg);
//create and append a return
var br = document.createElement("br");
document.getElementById('holder').appendChild(br);
//time scroll to bottom (after an arbitrary 5 seconds)
var stb = window.setTimeout(scrollToBottom, 5);
//time next post
var nextupdate = interval[point]*400;
var tp = window.setTimeout(trypost, nextupdate);
}
}
My script section contains at least the following variables:
var point = -1;
var interval = [10, 10, 15];
var images = ["r1", "a1", "r2"];
This questions is a continuation of the project described in How to proper use setTimeout with IE?
To answer one of your questions, document.body.scrollHeight is appropriate for this purpose, but not if you're actually calling for document. That'll give you the scroll height of the document the iFrame is in, not the iFrame's document. The iFrame's document can be called upon by [insert variable for iFrame here].contentDocument.
Here's how I did it (and by that, I mean I tested it out with my own stuff to make sure it worked):
let i = document.querySelector('iframe')
i.contentWindow.scrollTo(0, i.contentDocument.body.scrollHeight);
That being said, the other answer by Thomas Urban will also work most of the time. The difference is only if your page has a really long scroll height. Most pages won't be longer than 999999 (for all I know that's impossible and that's why they chose that number), but if you have a page longer than that, the method I showed here would scroll to the bottom and the 999999 would scroll to somewhere not yet at the bottom.
Also note, if you have more than one iFrame, you're gonna want to query it in a different way than I did, like by ID.
Scrolling to bottom is always like scrolling to some ridiculously large top offset, e.g. 999999.
iframe.contentWindow.scrollTo( 0, 999999 );
In addition see this post: Scrolling an iframe with javascript?
If scrolling occurs too early it's probably due to images not being loaded yet. Thus, you will have to scroll as soon as added image has been loaded rather than on having placed it. Add
newImg.onload = function() { triggerScrolling(); };
after creating newImg, but before assigning property src.
If several events are required to trigger scrolling you might need to use some "event collector".
function getEventCollector( start, trigger ) {
return function() {
if ( --start == 0 ) { trigger(); )
};
}
You can then use it like this:
var collector = getEventCollector( 2, function() { triggerScrolling(); } );
newImg.onload = collector;
window.setTimeout( collector, 100 );
This way triggerScrolling() is invoked after 100ms at least and after image has been loaded for collector has to be invoked twice for triggerScrolling() being invoked eventually.

Load (Lazy Loading) a Div whenever the DIV gets visible for the first time

I want to enable a lazy loading for the contents of my website.
Just like Jquery Image loading http://www.appelsiini.net/projects/lazyload that is valid only for images.
I want to do it for the content (DIV's).
Suppose we have a long page then i want to download the div as they becomes visible.
I will download the content using JSON or PageMethods. But i want the code that will execute the function for loading contents.
So whether we can somehow find this that div is visible only scrolling down.
Means i need to use some scroll events but dont know how.
Any help is appreciated.
I was looking for this to load advertising from my openX server only when the advertising should be visible. I'm using the iFrame version of openX which is loaded in a div. The answer here put me on my way to solving this problem, but the posted solution is a bit too simple. First of all, when the page is not loaded from the top (in case the user enters the page by clicking 'back') none of the divs are loaded. So you'll need something like this:
$(document).ready(function(){
$(window).scroll(lazyload);
lazyload();
});
Also, you'll need to know what defines a visible div. That can be a div that's fully visible or partially visible. If the bottom of the object is greater or equal to the top of the window AND the top of the object is smaller or equal to the bottom of the window, it should be visible (or in this case: loaded). Your function lazyload() might look like this:
function lazyload(){
var wt = $(window).scrollTop(); //* top of the window
var wb = wt + $(window).height(); //* bottom of the window
$(".ads").each(function(){
var ot = $(this).offset().top; //* top of object (i.e. advertising div)
var ob = ot + $(this).height(); //* bottom of object
if(!$(this).attr("loaded") && wt<=ob && wb >= ot){
$(this).html("here goes the iframe definition");
$(this).attr("loaded",true);
}
});
}
I tested this on all major browsers and even on my iPhone. It works like a charm!!
The code below does not cover cases where the user scrolls up from the bottom (read patrick's comment below). Also, it allows multiple event executions because of several concurrent onscroll events (in most browsers you won't see this, most of the time).
$(document).ready(function(){
$(window).scroll(function() {
//check if your div is visible to user
// CODE ONLY CHECKS VISIBILITY FROM TOP OF THE PAGE
if ($(window).scrollTop() + $(window).height() >= $('#your_element').offset().top) {
if(!$('#your_element').attr('loaded')) {
//not in ajax.success due to multiple sroll events
$('#your_element').attr('loaded', true);
//ajax goes here
//in theory, this code still may be called several times
}
}
});
});
Proper solution, that takes into consideration scrolling from bottom here.
You may consider way point library :)
http://imakewebthings.com/waypoints/api/waypoint/
Its use cases and api's are defined in above link
It is of 9 kb when compressed. It will add an additional -100 ms- 50ms timelag while loading page on 3g/ 4g
Edit :-
It can be used standalone and it also supports all major frameworks.
Here is a solution that lazy loads images when they come within 500px of view. It can be adapted to load other types of content. The images themselves have an attribute data-lazy="http://..." with the image url in it, and then we just put a dummy transparent image for the src attribute.
var pixelLoadOffset = 500;
var debouncedScroll = debounce(function () {
var els = app.getSelector(el, 'img[data-lazy]');
if (!els.length) {
$(window).unbind('scroll', debouncedScroll);
return;
}
var wt = $(window).scrollTop(); //* top of the window
var wb = wt + $(window).height(); //* bottom of the window
els.each(function () {
var $this = $(this);
var ot = $this.offset().top; //* top of object
var ob = ot + $this.height(); //* bottom of object
if (wt <= ob + pixelLoadOffset && wb >= ot - pixelLoadOffset) {
$this.attr('src', $this.attr('data-lazy')).removeAttr('data-lazy');
}
});
}, 100);
$(window).bind('scroll', debouncedScroll);
The debounce function I'm using is as follows:
function debounce(func, wait, immediate) {
var timeout;
return function () {
var context = this, args = arguments;
clearTimeout(timeout);
timeout = setTimeout(function () {
timeout = null;
if (!immediate) func.apply(context, args);
}, wait);
if (immediate && !timeout) func.apply(context, args);
};
}
You need to keep in mind that this isn't very effective on iOS, as the scroll event doesn't fire until after the user has finished scrolling, by which time they will already have seen the blank content.

Why is the resize event constantly firing when I assign it a handler with a timeout?

I assigned a timeout to my window.resize handler so that I wouldn't call my sizable amount resize code every time the resize event fires. My code looks like this:
<script>
function init() {
var hasTimedOut = false;
var resizeHandler = function() {
// do stuff
return false;
};
window.onresize = function() {
if (hasTimedOut !== false) {
clearTimeout(hasTimedOut);
}
hasTimedOut = setTimeout(resizeHandler, 100); // 100 milliseconds
};
}
</script>
<body onload="init();">
...
etc...
In IE7 (and possibly other versions) it appears that when you do this the resize event will constantly fire. More accurately, it will fire after every timeout duration -- 100 milliseconds in this case.
Any ideas why or how to stop this behavior? I'd really rather not call my resize code for every resize event that fires in a single resizing, but this is worse.
In your //do stuff code, do you manipulate any of the top,left,width,height,border,margin or padding properties?
You may unintentionally be triggering recursion which unintentionally triggers recursion which unintentionally triggers recursion...
How to fix the resize event in IE
also, see the answer for "scunliffe" "In your ... properties?
IE does indeed constantly fire its resize event while resizing is taking place (which you must know, as you are already implementing a timeout for a fix).
I am able to replicate the results you are seeing, using your code, on my test page.
However, the problem goes away if I increase the timeout to 1000 instead of 100. You may want to try with different wait values to see what works for you.
Here is the test page I used: it has a nicely dynamic wait period already set up for you to play with.
I stumbled on the same problem, but solved it differenly, and I think it's more elegant than making a timeout....
The context: I have an iframed page, loaded inside the parent page, and the iframe must notify the parent when its size changes, so the parent can resize the iframe accordingly - achieving dynamic resizing of an iframe.
So, in the iframed HTML document, I tried to register a callback on the body tag. First, on the onchange - it didn't work. Then on resize - it did work, but kept firing constantly. (Later on I found the cause - it was apparently a bug in Firefox, which tried to widen my page to infinity). I tried the ResizeObserver - for no avail, the same thing happened.
The solution I implemented was this:
<body onload="docResizePipe()">
<script>
var v = 0;
const docResizeObserver = new ResizeObserver(() => {
docResizePipe();
});
docResizeObserver.observe(document.querySelector("body"));
function docResizePipe() {
v += 1;
if (v > 5) {
return;
}
var w = document.body.scrollWidth;
var h = document.body.scrollHeight;
window.parent.postMessage([w,h], "*");
}
setInterval(function() {
v -= 1;
if (v < 0) {
v = 0;
}
}, 300);
</script>
So how it works: each time the callback fires, we increment a variable v; once in every 300 ms, we decrement it; if it's too big, the the firing is blocked.
The big advantage of this over the timeout-based solution, is that it introduces to lag for a user experience, and also clear in how exactly it does block the recursion. (Well, actually not )))

Categories

Resources