Make two elements have the same size - javascript

I want two elements in different locations and different "parents" in the DOM tree to have the same height and width, even if one changes.
Is there a solution that will support all browsers including IE 8?
EDIT: If there is a solution that will not work on IE 8 I would still like to hear about it, but it will not be accepted as the solution I'm looking for.
Clarification: I want to solution to handle any cause for the size change: Window size change, content size change, etc.

You can use setInterval to do what you want.
var changeIndex = -1; // record element width or height is change or not
function setToSame() {
if(changeIndex!=-1) {
console.log("test");
$('.same').height($('.same').eq(changeIndex).height());
$('.same').width($('.same').eq(changeIndex).width());
changeIndex = -1;
}
}
// set your own function to change size, but reserve changeIndex setting
$('input').change(function() {
$(this).parent().children('.same').css($(this).attr('id'), $(this).val() +'px');
// set the changeIndex to the current change div
changeIndex = $('.same').index($(this).parent().children('.same'));
console.log(changeIndex);
});
setInterval(setToSame, 4);
See jsfiddle here.

You can use jQuery to get a solution that works for IE8.
Suppose the two element that you want to have same height and width are,
<div id="fir">
</div>
<div id="sec">
</div>
Now specify height and width of just one element as,
#fir{
height: 50px;
width: 100px;
}
There is no predefined method in CSS to detect height or width change but you can achieve the results using jQuery as,
$(document).ready(function(){
$('#fir').bind('heightChange', function(){
var h = $("#fir").height();
$("#sec").height(h);
});
$('#fir').bind('widthChange', function(){
var w = $("#fir").width();
$("#sec").width(w);
});
$('#sec').bind('heightChange', function(){
var h = $("#sec").height();
$("#fir").height(h);
});
$('#sec').bind('widthChange', function(){
var w = $("#sec").width();
$("#fir").width(w);
});
});
This will detect the height and width change for both element and set the height and width of other element likewise.
To check if the above code works properly you can create a test script that changes width of element with id="fir" by creating a button,
<button id="btn">Change width</button>
Now include the below function,
$("#btn").click(function() {
$("#fir").css('width', '400px');
$("#fir").trigger('widthChange');
});
Here is the fiddle for it

<html>
<head>
<style>
div{}
#A{background: red}
#B{background: blue}
</style>
<script>
mBlockChange = false; //Required for IE9-
function equalSize(f, t){
mBlockChange = true;
f = (f || document.getElementById('A'));
t = (t || document.getElementById('B'));
//We take the larger dimension of both since it is better than clipping.
//Change on your demands.
t.style.height = '';
t.style.width = '';
f.style.height = '';
f.style.width = '';
t.style.height = Math.max(f.offsetHeight, t.offsetHeight).toString() + 'px';
t.style.width = Math.max(f.offsetWidth, t.offsetWidth).toString() + 'px';
f.style.height = Math.max(f.offsetHeight, t.offsetHeight).toString() + 'px';
f.style.width = Math.max(f.offsetWidth, t.offsetWidth).toString() + 'px';
setTimeout(function(){mBlockChange = false}, 100);
}
//This one for IE9+, FFox, Chrome and Safari
//http://help.dottoro.com/ljrmcldi.php
function bindEvents(){
var tA = document.getElementById('A');
var tB = document.getElementById('B');
//The addEventListener() method is not supported in Internet Explorer 8 and earlier versions with resize.
//Resizing the body
document.body.onresize = function(){
//We only do this once the resizing is actually finished.
if (this.Timer) clearTimeout(this.Timer);
this.Timer = setTimeout(function(){
//console.log('Resize', this);
equalSize()
}, 300)
};
//If supported, we listen on dom changes.
if ('MutationEvent' in window){
document.addEventListener('DOMSubtreeModified', function(){
if (document.Timer) clearInterval(document.Timer);
//console.log('DOMSubtreeModified', this);
if (!mBlockChange) equalSize()
}, false);
}
//We set an interval for browsers which do not support DOMSubtreeModified
//If you do not want to rely on ('MutationEvent' in window) put it out of else and cancel the timer (scenario B)
//Can not bind parameters to setInterval in IE8- :s
else{
document.Timer = setInterval(function(){
//console.log('Interval', 'Document');
equalSize()
}, 1000);
}
}
</script>
</head>
<body onload = 'bindEvents()'>
<div id = 'A'><p contenteditable = 'true'>A</p></div>
<div id = 'B'><p contenteditable = 'true'>B</p></div>
</body>
</html>
https://jsfiddle.net/5cn7maqe/
Yet your elements height and width should not magically change, it always requires some interactions, like changing dom by ajax, oninput with contenteditable or resizing the window. You would be better off to just adjust it after those actions manually.
Edit: Made some minor changes.
https://jsfiddle.net/5cn7maqe/1/

Related

Synchronized scrolling using jQuery?

I am trying to implement synchronized scrolling for two DIV with the following code.
DEMO
$(document).ready(function() {
$("#div1").scroll(function () {
$("#div2").scrollTop($("#div1").scrollTop());
});
$("#div2").scroll(function () {
$("#div1").scrollTop($("#div2").scrollTop());
});
});
#div1 and #div2 is having the very same content but different sizes, say
#div1 {
height : 800px;
width: 600px;
}
#div1 {
height : 400px;
width: 200px;
}
With this code, I am facing two issues.
1) Scrolling is not well synchronized, since the divs are of different sizes. I know, this is because, I am directly setting the scrollTop value. I need to find the percentage of scrolled content and calculate corresponding scrollTop value for the other div. I am not sure, how to find the actual height and current scroll position.
2) This issue is only found in firefox. In firefox, scrolling is not smooth as in other browsers. I think this because the above code is creating a infinite loop of scroll events.
I am not sure, why this is only happening with firefox. Is there any way to find the source of scroll event, so that I can resolve this issue.
Any help would be greatly appreciated.
You can use element.scrollTop / (element.scrollHeight - element.offsetHeight) to get the percentage (it'll be a value between 0 and 1). So you can multiply the other element's (.scrollHeight - .offsetHeight) by this value for proportional scrolling.
To avoid triggering the listeners in a loop you could temporarily unbind the listener, set the scrollTop and rebind again.
var $divs = $('#div1, #div2');
var sync = function(e){
var $other = $divs.not(this).off('scroll'), other = $other.get(0);
var percentage = this.scrollTop / (this.scrollHeight - this.offsetHeight);
other.scrollTop = percentage * (other.scrollHeight - other.offsetHeight);
// Firefox workaround. Rebinding without delay isn't enough.
setTimeout( function(){ $other.on('scroll', sync ); },10);
}
$divs.on( 'scroll', sync);
http://jsfiddle.net/b75KZ/5/
Runs like clockwork (see DEMO)
$(document).ready(function(){
var master = "div1"; // this is id div
var slave = "div2"; // this is other id div
var master_tmp;
var slave_tmp;
var timer;
var sync = function ()
{
if($(this).attr('id') == slave)
{
master_tmp = master;
slave_tmp = slave;
master = slave;
slave = master_tmp;
}
$("#" + slave).unbind("scroll");
var percentage = this.scrollTop / (this.scrollHeight - this.offsetHeight);
var x = percentage * ($("#" + slave).get(0).scrollHeight - $("#" + slave).get(0).offsetHeight);
$("#" + slave).scrollTop(x);
if(typeof(timer) !== 'undefind')
clearTimeout(timer);
timer = setTimeout(function(){ $("#" + slave).scroll(sync) }, 200)
}
$('#' + master + ', #' + slave).scroll(sync);
});
This is what I'm using. Just call the syncScroll(...) function with the two elements you want to synchronize. I found pawel's solution had issues with continuing to slowly scroll after the mouse or trackpad was actually done with the operation.
See working example here.
// Sync up our elements.
syncScroll($('.scroll-elem-1'), $('.scroll-elem-2'));
/***
* Synchronize Scroll
* Synchronizes the vertical scrolling of two elements.
* The elements can have different content heights.
*
* #param $el1 {Object}
* Native DOM element or jQuery selector.
* First element to sync.
* #param $el2 {Object}
* Native DOM element or jQuery selector.
* Second element to sync.
*/
function syncScroll(el1, el2) {
var $el1 = $(el1);
var $el2 = $(el2);
// Lets us know when a scroll is organic
// or forced from the synced element.
var forcedScroll = false;
// Catch our elements' scroll events and
// syncronize the related element.
$el1.scroll(function() { performScroll($el1, $el2); });
$el2.scroll(function() { performScroll($el2, $el1); });
// Perform the scroll of the synced element
// based on the scrolled element.
function performScroll($scrolled, $toScroll) {
if (forcedScroll) return (forcedScroll = false);
var percent = ($scrolled.scrollTop() /
($scrolled[0].scrollHeight - $scrolled.outerHeight())) * 100;
setScrollTopFromPercent($toScroll, percent);
}
// Scroll to a position in the given
// element based on a percent.
function setScrollTopFromPercent($el, percent) {
var scrollTopPos = (percent / 100) *
($el[0].scrollHeight - $el.outerHeight());
forcedScroll = true;
$el.scrollTop(scrollTopPos);
}
}
If the divs are of equal sizes then this code below is a simple way to scroll them synchronously:
scroll_all_blocks: function(e) {
var scrollLeft = $(e.target)[0].scrollLeft;
var len = $('.scroll_class').length;
for (var i = 0; i < len; i++)
{
$('.scroll_class')[i].scrollLeft = scrollLeft;
}
}
Here im using horizontal scroll, but you can use scrollTop here instead. This function is call on scroll event on the div, so the e will have access to the event object.
Secondly, you can simply have the ratio of corresponding sizes of the divs calculated to apply in this line $('.scroll_class')[i].scrollLeft = scrollLeft;
I solved the sync scrolling loop problem by setting the scroll percentage to fixed-point notation: percent.toFixed(0), with 0 as the parameter. This prevents mismatched fractional scrolling heights between the two synced elements, which are constantly trying to "catch up" with each other. This code will let them catch up after at most a single extra step (i.e., the second element may continue to scroll an extra pixel after the user stops scrolling). Not a perfect solution or the most sophisticated, but certainly the simplest I could find.
var left = document.getElementById('left');
var right = document.getElementById('right');
var el2;
var percentage = function(el) { return (el.scrollTop / (el.scrollHeight - el.offsetHeight)) };
function syncScroll(el1) {
el1.getAttribute('id') === 'left' ? el2 = right : el2 = left;
el2.scrollTo( 0, (percentage(el1) * (el2.scrollHeight - el2.offsetHeight)).toFixed(0) ); // toFixed(0) prevents scrolling feedback loop
}
document.getElementById('left').addEventListener('scroll',function() {
syncScroll(this);
});
document.getElementById('right').addEventListener('scroll',function() {
syncScroll(this);
});
I like pawel's clean solution but it lacks something I need and has a strange scrolling bug where it continues to scroll and my plugin will work on multiple containers not just two.
http://www.xtf.dk/2015/12/jquery-plugin-synchronize-scroll.html
Example & demo: http://trunk.xtf.dk/Project/ScrollSync/
Plugin: http://trunk.xtf.dk/Project/ScrollSync/jquery.scrollSync.js
$('.scrollable').scrollSync();
If you don't want proportional scrolling, but rather to scroll an equal amount of pixels on each field, you could add the value of change to the current value of the field you're binding the scroll-event to.
Let's say that #left is the small field, and #right is the bigger field.
var oldRst = 0;
$('#right').on('scroll', function () {
l = $('#left');
var lst = l.scrollTop();
var rst = $(this).scrollTop();
l.scrollTop(lst+(rst-oldRst)); // <-- like this
oldRst = rst;
});
https://jsfiddle.net/vuvgc0a8/1/
By adding the value of change, and not just setting it equal to #right's scrollTop(), you can scroll up or down in the small field, regardless of its scrollTop() being less than the bigger field. An example of this is a user page on Facebook.
This is what I needed when I came here, so I thought I'd share.
From the pawel solution (first answer).
For the horizzontal synchronized scrolling using jQuery this is the solution:
var $divs = $('#div1, #div2'); //only 2 divs
var sync = function(e){
var $other = $divs.not(this).off('scroll');
var other = $other.get(0);
var percentage = this.scrollLeft / (this.scrollWidth - this.offsetWidth);
other.scrollLeft = percentage * (other.scrollWidth - other.offsetWidth);
setTimeout( function(){ $other.on('scroll', sync ); },10);
}
$divs.on('scroll', sync);
JSFiddle
An other solution for multiple horizontally synchronized divs is this, but it works for divs with same width.
var $divs = $('#div1, #div2, #div3'); //multiple divs
var sync = function (e) {
var me = $(this);
var $other = $divs.not(me).off('scroll');
$divs.not(me).each(function (index) {
$(this).scrollLeft(me.scrollLeft());
});
setTimeout(function () {
$other.on('scroll', sync);
}, 10);
}
$divs.on('scroll', sync);
NB: Only for divs with same width
JSFiddle

Resize iframe to content with Jquery

I'm trying to resize an iframe dynamicly to fit its content. To do so I have a piece of code:
$("#IframeId").height($("#IframeId").contents().find("html").height());​
It doesnt work. Is it because of cross-domain issue? How do I get it to fit? Please take a look at Fiddle: JsFiddle
ps I have set the html and body of the link height:100%;
You just need to apply your code on the iframe load event, so the height is already known at that time, code follows:
$("#IframeId").load(function() {
$(this).height( $(this).contents().find("body").height() );
});
See working demo . This demo works on jsfiddle as I've set the iframe url to a url in the same domain as the jsfiddle result iframe, that is, the fiddle.jshell.net domain.
UPDATE:
#Youss:
It seems your page for a strange reason don't get the body height right, so try using the height of the main elements instead, like this:
$(document).ready(function() {
$("#IframeId").load(function() {
var h = $(this).contents().find("ul.jq-text").height();
h += $(this).contents().find("#form1").height();
$(this).height( h );
});
});
Not sure why #Nelson's solution wasn't working in Firefox 26 (Ubuntu), but the following Javascript-jQuery solution seems to work in Chromium and Firefox.
/**
* Called to resize a given iframe.
*
* #param frame The iframe to resize.
*/
function resize( frame ) {
var b = frame.contentWindow.document.body || frame.contentDocument.body,
cHeight = $(b).height();
if( frame.oHeight !== cHeight ) {
$(frame).height( 0 );
frame.style.height = 0;
$(frame).height( cHeight );
frame.style.height = cHeight + "px";
frame.oHeight = cHeight;
}
// Call again to check whether the content height has changed.
setTimeout( function() { resize( frame ); }, 250 );
}
/**
* Resizes all the iframe objects on the current page. This is called when
* the page is loaded. For some reason using jQuery to trigger on loading
* the iframe does not work in Firefox 26.
*/
window.onload = function() {
var frame,
frames = document.getElementsByTagName( 'iframe' ),
i = frames.length - 1;
while( i >= 0 ) {
frame = frames[i];
frame.onload = resize( frame );
i -= 1;
}
};
This continually resizes all iframes on a given page.
Tested with jQuery 1.10.2.
Using $('iframe').on( 'load', ... would only work intermittently. Note that the size must initially be set to 0 pixels in height if it is to shrink below the default iframe height in some browsers.
What you can do is the following:
Within the iFrame use document.parent.setHeight(myheight) to set the height within the iFrame to the parent. Which is allowed since it is a child control. Call a function from the parent.
Within the parent you make a function setHeight(iframeheight) which resizes the iFrame.
Also see:
How do I implement Cross Domain URL Access from an Iframe using Javascript?
Just do it on the HTML tag, works perfect
$("#iframe").load(function() {
$(this).height( $(this).contents().find("html").height() );
});
As the answer to the question use an already outdated jquery (load has been deprecated and replaced with .on('load',function(){}), below is the latest code for the answer in the question.
Note that I use the scrollHeight and scrollWidth, which I think will load much nicer than using Height and Width like the answer provided. It will totally fit, without scroll anymore.
$("#dreport_frame").on('load',function(){
var h = $('#dreport_frame').contents().find("body").prop('scrollHeight');
var w = $('#dreport_frame').contents().find("body").prop('scrollWidth');
$('#dreport_frame').height(h);
$('#dreport_frame').width(w);
})
Adjust height of an iframe, on load and resize, based on its body height.
var iFrameID = document.getElementById('iframe2');
var iframeWin = iFrameID.contentWindow;
var eventList = ["load", "resize"];
for(event of eventList) {
iframeWin.addEventListener(event, function(){
if(iFrameID) {
var h = iframeWin.document.body.offsetHeight + "px";
if(iFrameID.height == h) {
return false;
}
iFrameID.height = "";
iFrameID.height = iframeWin.document.body.offsetHeight + "px";
}
})
}
At end, I come with this cross-domain solution that work also for resize...
(resize not triggering : Auto resize iframe height when the height of the iframe contents change (same domain) )
Iframe :
(function() {
"use strict";
var oldIframeHeight = 0,
currentHeight = 0;
function doSize() {
currentHeight = document.body.offsetHeight || document.body.scrollHeight;
if (currentHeight !== oldIframeHeight) {
console.log('currentHeight', currentHeight);
window.parent.postMessage({height:currentHeight}, "*");
oldIframeHeight = currentHeight;
}
}
if (window.parent) {
//window.addEventListener('load', doSize);
//window.addEventListener('resize', doSize);
window.setInterval(doSize, 100); // Dispatch resize ! without bug
}
})();
Parent page :
window.addEventListener('message', event => {
if (event.origin.startsWith('https://mysite.fr') && event.data && event.data.height) {
console.log('event.data.height', event.data.height);
jQuery('#frameId').height(event.data.height + 12);
}
});

How to change the height of div with the content of other div

I have two div in my website page one beside the other(one left and one right),I want to change the height of the left one with the content of the right one using javascript
I tried to have the dynamic height of the right div :
function getHeight() {
var doc = document.getElementById('div.right');
if (document.all) // ok I.E
{
H = doc.currentStyle.height;
}
else // ok FF
{
H = document.defaultView.getComputedStyle(doc, null).height;
}
}​
But I stopped here because I don't know how to pass the javascript variable to my page of style CSS,I mean I dont know how to apply this value in the other div(left div) in the same page automatically.
Any Idea?
Just use
document.getElementById('div.left').style.height = H;
Edit
AFAIK you cant modify an external stylesheet from javascript
Is the height of the div determined at the time the document is served, loaded or or any arbitrary time after the document has loaded?
The code I suggested above was to be used like this(I'm assuming your IE code is correct)
function getHeight() {
var doc = document.getElementById('div.right');
if (document.all) // ok I.E
{
H = doc.currentStyle.height;
}
else // ok FF
{
H = document.defaultView.getComputedStyle(doc, null).height;
}
document.getElementById('div.left').style.height = H;//✔
}
Just to help people I found a great code to change the height of two div autoamtically using a little of Jquery :
<script type='text/javascript'>
$(window).load(function(){
var lh = $('#div.right').height();
var rh = $('#div.left').height();
if (lh >= rh){
//alert('left : ' + lh);
$('#div.left').height(lh);
} else {
//alert('right : ' + rh);
$('#div.right').height(rh);
};
});
</script>
It's works for all navigators.

How to do an infinite scroll in plain Javascript

I want to avoid using jQuery or another library for the sake of keeping my code minimal, I need very little in the way of features, I just want to append to a list when the user scrolls to the bottom. How would I do this in plain Javascript?
Basicaly you just need to hook the event scroll, check if the user scrolled down enough and add some content if so:
<html><body>
<div id="test">scroll to understand</div>
<div id="wrapper" style="height: 400px; overflow: auto;">
<div id="content"> </div>
</div>
<script language="JavaScript">
// we will add this content, replace for anything you want to add
var more = '<div style="height: 1000px; background: #EEE;"></div>';
var wrapper = document.getElementById("wrapper");
var content = document.getElementById("content");
var test = document.getElementById("test");
content.innerHTML = more;
// cross browser addEvent, today you can safely use just addEventListener
function addEvent(obj,ev,fn) {
if(obj.addEventListener) obj.addEventListener(ev,fn,false);
else if(obj.attachEvent) obj.attachEvent("on"+ev,fn);
}
// this is the scroll event handler
function scroller() {
// print relevant scroll info
test.innerHTML = wrapper.scrollTop+"+"+wrapper.offsetHeight+"+100>"+content.offsetHeight;
// add more contents if user scrolled down enough
if(wrapper.scrollTop+wrapper.offsetHeight+100>content.offsetHeight) {
content.innerHTML+= more;
}
}
// hook the scroll handler to scroll event
addEvent(wrapper,"scroll",scroller);
</script>
</body></html>
For achieving this behaviour you don't need jQuery or a jQuery plugin. You can use only CSS or JavaScript (if you want to cover all browsers).
But don't use onScroll: you can do all of this with just vanilla JS and the Intersection Observer API.
All you need to do is place elements and listen for when they become available in the screen. The Intersection Observer API is very customisable to fit all your needs.
In summary: you accomplish that with a few JavaScript & HTML lines and it's much more performant than listening for scroll events in the browser.
Excellent demo code for infinite scroll. Goes to show that you don't need jQuery and Angular for any browser independent work. But new boys today are out of touch with pure Javascript that we old guys still trust and use. Here I have simplified the code further:
// we will add this content, replace for anything you want to add
var wrapper, content, test;
var more = '<div style="height:1000px; background:#EEE;"></div>';
// this is the scroll event handler
function scroller() {
// print relevant scroll info
test.innerHTML = wrapper.scrollTop + " + " + wrapper.offsetHeight + " + 100 > " + content.offsetHeight;
// add more contents if user scrolled down enough
if (wrapper.scrollTop + wrapper.offsetHeight + 100 > content.offsetHeight) {
content.innerHTML += more; // NK: Here you can make an Ajax call and fetch content to append to content.innerHTML
}
}
wrapper = document.getElementById("wrapper");
content = document.getElementById("content");
test = document.getElementById("test");
content.innerHTML = more;
// hook the scroll handler to scroll event
if (wrapper.addEventListener) // NK: Works on all new browsers
wrapper.addEventListener("scroll", scroller, false);
else if (wrapper.attachEvent) // NK: Works on old IE
wrapper.attachEvent("onscroll", scroller);
<div id="test">scroll to understand</div>
<div id="wrapper" style="height: 400px; overflow: auto;">
<div id="content"> </div>
</div>
domElem.addEventListener(
'scroll',
function(evt) { ... },
false
);
and handle evt/scroll position appropriately.
I see great answers to your question, but for a scrolling that is not associated with any HTML element or content (just an empty HTML page), here is how I did it:
document.querySelector("body").style.height = "1000px";
window.addEventListener("scroll", function() {
var body = document.querySelector("body");
var height = body.style.height;
height = height.slice(0, -2);
height = Number(height);
return function() {
if(height - window.scrollY < 700) {
height += height / 2;
}
body.style.height = height + "px";
};
}());
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
I hope this helps someone out there :)
Assume HTML:
<div class="container"></div>
let container = document.querySelector('.container');
// when user scrolls to last list item in view, wait for 1.5seconds and load next 10 list items, and continue thus.
window.addEventListener('scroll', function(){
setTimeout(() => {
loadMoreList(5);
}, 1500);
});
loadMoreList(20); // load first 20 list items.
function loadMoreList(num) {
let scrollY = window.scrollY;
let innerHeight = window.innerHeight;
let offsetHeight = document.body.offsetHeight;
if (scrollY + innerHeight > offsetHeight - 100) {
let item = 1;
let ul = document.createElement('ul');
for (var i = 0; i < num; i++) {
let li = document.createElement('li');
li.innerText = 'List Item ' + item++;
ul.appendChild(li);
container.appendChild(ul);
}
}
}
Note: The more important parts are: the scroll event listener and the loadMoreList function. You don't necessarily need the argument num.
The for loop just ensures that on load, the function is called and 20 items are uniquely created and displayed.

Check block visibility

We have code like:
<body>
<div class="blocks">some text here</div>
<div class="end"></div>
</body>
Text can fit in current browser visible part or not.
How to detect, does the block is in visible part of browser window?
I mean, if resoution is 1024x768 and .block height bigger than 768, then .end is invisible.
we should detect this on window.ready and also on browser window change.
if block is visible, then run some function.
Any help is appreciated.
Something like this:
$.fn.viewport = (function() {
var vp = function(el, opts){
this.el = $(el);
this.opts = opts;
this.bind(); // bind resize and scroll
this.change(); // init change
};
vp.prototype = {
bind: function(){
$(window).bind('resize scroll',
$.proxy(this.change, this));
},
change: function(e){
var p = this.el.position(),
o = this.el.offset(),
d = { w: this.el.width() +o.left, h: this.el.height()+o.top },
win = $(window),
winD = {w:win.width() + win.scrollLeft(), h:win.height()+win.scrollTop()};
if(d.w <= winD.w && d.h <= winD.h){
console.log('inview');
} else {
console.log('out of view');
this.opts.outOfView.call(this);
}
}
};
return function(opts){
return $(this).each(function(){
$(this).data('vp', new vp(this, opts));
});
};
})();
And use like this:
$('#el').viewport({
outOfView: function(){
alert('out of view');
}
});
First grab the window dimensions.
var windowSize = {width: $(window).width(), height: $(window).height() + $(window).scrollTop()};
Next grab the div position in relation to the document:
var position = $('.block').offset()
Then make your if's:
if(position.top > windowSize.height){ /* here we go */ }
You might want to also grab div dimensions in case there is a possibility it will be out of bounds on the top or left side.
You could make it into a function that returns a boolean value and then call it on the window.resize and document.ready events.
EDIT: Added scrollTop to account for scrolling.
As a quick answer you'll have to do some computation on load (psuedocode assumes jQuery).
Find the window height $(window).outerHeight(true)
Find the offset of the ".end" element $(".end").offset()
Find the scroll distance of the window $(window).scrollTop()
Calculate! It should roughly be:
if ((step1 + step3) > step2) {
//do stuff here
}
Note that that does not check if you are scrolled past the ".end" element. I didn't verify this one, so hopefully I'm not missing something big.
Get the offsetTop and offsetLeft attributes of the element
Get the width of the element in question
Get the width of screen
Do the relevant maths and see if the element is in the viewport or now.
in jQuery you can do something like
$("#element").attr("offsetTop")
EDIT:
Simple and Effective: http://jsfiddle.net/hPjbh/

Categories

Resources