Efficiently Find Page Max Dimensions - javascript

I am currently running a script on a third-party page to determine the maximum dimensions of the page. At first, this may seem as if I could just use outerWidth() and outerHeight() on my parent wrapper, #base but the problem is that the page wrapper isn't sized from its children. So I might have a parent that is 0x0 and its child is 400x400 and a child inside of that which is 500x500. It seems they just allow overflow. I have tried some CSS tricks in attempt to force the parent #base to size itself correctly, but the children don't seem to drive this change and modifying their CSS causes actual alignment issues on the page. Additionally, there are many hidden items on the page that do not become visible until later or during page interaction so this further prevents me from just grabbing the outer dimensions of #base or something like that.
My current approach is to iterate through every single element on the page. I check to see where it is positioned and what its dimensions are. Based on those, I update my maximum dimensions. I also have to check for horizontal and vertical scrolling elements because those may be on the page too. If a wrapper is 500px wide and the child has a width of 1000px, but is scrolled, I wouldn't want that to affect my maximum dimensions. Anyways, this approach works but it's slow. Sometimes the page may have +15k elements. With these numbers, it takes 10 seconds on my machine. I might be able to optimize some of the conditional statements to use booleans instead of evaluating values, but I don't think this will make a significant difference. I'm hoping there is some process I'm completely overlooking. Below is my current code snippet and a demo showing how the page looks prior to running the code and after the code has been run.
Demo: https://p826ni.axshare.com/#g=1&p=without_code
$('#base *').not('script, style').each(function () {
currentElement = $(this);
// Initialize on first loop.
if (parentElementHorizontal === undefined && parentElementVertical === undefined) {
parentElementHorizontal = currentElement;
parentElementVertical = currentElement;
}
width = currentElement.outerWidth();
height = currentElement.outerHeight();
scrollWidthHidden = currentElement[0].scrollWidth;
scrollHeightHidden = currentElement[0].scrollHeight;
top = currentElement.offset().top;
left = currentElement.offset().left;
// Check if we're still within the parent containing horizontal-scrolling overflow.
if (!$.contains(parentElementHorizontal[0], currentElement[0])) {
hiddenWidth = false;
}
// Check if we're still within the parent containing vertical-scrolling overflow.
if (!$.contains(parentElementVertical[0], currentElement[0])) {
hiddenHeight = false;
}
// Check if we've found an element with horizontal-scrolling content.
if (!hiddenWidth) {
maxWidth = maxWidth < left + width ? left + width : maxWidth;
} else if (currentElement.width() > maxWidth) {
currentElement.addClass('redline-layer');
}
if (scrollWidthHidden > width && !hiddenWidth && width > 0) {
hiddenWidth = true;
parentElementHorizontal = currentElement;
}
// Check if we've found an element with vertical-scrolling content.
if (!hiddenHeight) {
maxHeight = maxHeight < top + height ? top + height : maxHeight;
} else if (currentElement.height() > maxHeight) {
currentElement.addClass('redline-layer');
}
if (scrollHeightHidden > height && !hiddenHeight && height > 0) {
hiddenHeight = true;
parentElementVertical = currentElement;
}
});

Related

How to check if the height of one of the elements with class exceeds a threshold?

I have some sections that have a min-height of 100vh.
How do i setup an if statement that checks when óne of the elements exceeds the viewport height? Currently i have the following but that does not work for some reason:
var section = $('.fh-section');
var height = $(window).height();
if (section.height() > height) {
execute code
}
I feel like it will only execute if all the elements with the .fw-section class exceed the height it results true. How do i set it up so it results true if at least one of the elements exceeds the window height?
You could loop through all elements with the specified class like this:
var height = $(window).height();
$('.fh-section').each(function(index) {
if ($(this).height > height)
{
// CODE
return false; // stops the loop
}
});

jQuery each() function not working after if/else statement has been completed for both if and else outputs

I am using jQuery & javascript to switch the classes for images based on whether the viewport width is less than or greater than twice the width of the image.
I am using $(window).resize to detect when the widow is resized and then the each() function to iterate through all images of a certain class.
An if statement checks whether the width of the viewport is less than twice the width of the image and if so removes one class and adds another. The else statement does the reverse.
One page load it works fine for as many widow width changes as I do, until both the if and the else have been executed, then they stop working. Any suggestions would be greatly appreciated!
Thanks
Here's my code:
function updateViewportDimensions() {
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName("body")[0],
x = w.innerWidth || e.clientWidth || g.clientWidth,
y = w.innerHeight || e.clientHeight || g.clientHeight;
return { width: x, height: y };
};
jQuery(window).resize(function() {
var viewport = updateViewportDimensions();
var viewport_width = viewport['width'];
console.log('Viewport width = ' + viewport_width);
jQuery(document).ready(function($) {
$('.alignright').each(function(i, obj){
// get the width of each image
var image_width = $(this).width();
// if the viewport width is less than twice the image width then switch the classes
if(viewport_width < (image_width * 2)) {
$(this).removeClass('alignright');
$(this).addClass('aligncenter');
console.log('Viewport is less than twice image width');
} else {
console.log('Viewport is more than twice image width');
$(this).addClass('alignright');
$(this).removeClass('aligncenter');
};
});
});
});
If I am reading this correctly, (this).removeClass('alignright'); is changing your dom. Because of this all the link to the class alignright is now new but your jquery is still looking for the instances that have been removed.
Update $('.alignright').each(function(i, obj){ to be one level higher than what is being altered.
if the code is
<div id="outer-wrapper">
<div class="alignright">
content
</div>
</div>
use $('#outer-wrapper .alignright').each(function(i, obj){

How to get exact measurements of a div scroll and height, using em units makes it harder

I have a chat for mobile website, and for the chat bubbles sizes we are using em units. Because of that, the elements seem to always be not-round numbers (like 510.673). I need to know the exact sizes, so I can know when to show a certain button, and when can I start loading older chat messages in that conversation.
Here is the html
<div class="chat-window">
<div id="chatWindow" class="item-content" style="height: 100%; overflow: auto;">
</div>
The overflow: auto; is needed because without it, I don't receive a call when the top of the div is reached.
Here is the javascript, that is attached as an event to the chatWindow element
$('#chatWindow').on('scroll', onScroll);
and this is the onScroll function
onScroll() {
const chatWindow = $('#chatWindow');
const scrollTop = chatWindow.scrollTop();
const scrollHeight = chatWindow[0].scrollHeight;
const clientHeight = chatWindow[0].clientHeight;
if (scrollTop <= 0) {
// When top is reached
isInBottom = false;
// more code
} else if (scrollTop + clientHeight >= scrollHeight) {
// When bottom is reached
isInBottom = true;
// more code
} else {
// When anywhere else
isInBottom = false;
}
}
So this is what the chat bubbles look like, when they are with em units
They are not round numbers, so the scroll function can't calculate them accurately.
I tried with the chatWindow[0].getBoundingClientRect().height instead of chatWindow[0].clientHeight, it works, but only for that one parameter, I also need the other two to be with exact numbers with floating point.
How can I do it?
Could you please explain more?
chatWindow[0].getBoundingClientRect() will return an object which will have 'height' as of the keys.
chatWindow[0].getBoundingClientRect().height === chatWindow[0].clientHeight
Plus rest of the values in the objects are relative to ViewPort. This will impact your calculation too.
https://developer.mozilla.org/en/docs/Web/API/Element/getBoundingClientRect

Jquery horizontal slide based on div width

I have jquery script where you can click a left and right button and it will scroll horizontally to show more content.
The content that needs to be scrolled are in a div with a width of 1296px, but i want to set my jquery code to automatically get the width of the div and when you press on one of the left or right scroll button it will scroll exactly 1296px.
I want to do it this way because I need to later on optimize the design for all screen size and this would be the easier way.
My code:
var $item2 = $('div.group'), //Cache your DOM selector
visible2 = 1, //Set the number of items that will be visible
index2 = 0, //Starting index
endIndex2 = ( $item.length ); //End index
$('#arrowR').click(function(){
index2++;
$item2.animate({'left':'-=1296px'});
});
$('#arrowL').click(function(){
if(index2 > 0){
index2--;
$item2.animate({'left':'+=18.5%'});
}
});
This Javascript should work:
var $item2 = $('div.group'), //Cache your DOM selector
visible2 = 1, //Set the number of items that will be visible
index2 = 0, //Starting index
endIndex2 = ( $item2.length ); //End index
var w = $("#group").width();
$('#arrowR').click(function(){
index2++;
$item2.animate({'left':'-=' + w + 'px'});
});
$('#arrowL').click(function(){
if(index2 > 0){
index2--;
$item2.animate({'left':'+=' + w + 'px'});
}
});
Check this fiddle. Basically we calculate the width initially to not do the same thing repeatedly and the reuse it whenever we need it.
Why not get the width of the visible container first, and then use that value later? Quick example:
var width = $('container').width();
And then during animations:
var left = $item2.css('left') + width;
$item.animate({'left',left});
As a note, innerWidth and outerWidth may be more beneficial than just width depending on how you've set everything up, so if values aren't quite right take a look at those documents.
I've created a fiddle that I think solves your problem:
http://jsfiddle.net/77bvnw3n/
What I did was to create another variable (called width) which on page load, dynamically gets the width of the container.
var width = $('.group-container').width(); //Container Width
This variable is also reset whenever the Next or Previous buttons are pressed (in case the window has been resized since the page loaded).
$('#arrowR').click(function(){
index2++;
//recheck container width
width = $('.group-container').width();
$item2.animate({'left':'-=' + width + 'px'});
});
Take a look and let me know if it helps.
Note: I replaced the 'Next' and 'Previous' images with coloured boxes in my Fiddle and I think you also had a typo in your code, should
endIndex2 = ( $item.length )
be changed to:
endIndex2 = ( $item2.length )

Get divs within viewport inside a wrapper div

Is there a way to get elements which is:
Inside a div with overflow: scroll
Is in viewport
Just like the following picture, where active div (5,6,7,8,9) is orange, and the others is green (1-4 and >10) :
I just want the mousewheel event to add "active" class to div 5,6,7,8,9 (currently in viewport). View my JSFiddle
$('.wrapper').bind('mousewheel', function (e) {
//addClass 'active' here
});
You could do something like this. I would have re-factored it, but only to show the concept.
Firstly I would attach this to scroll event and not mousewheel. There are those among us that likes to use keyboard for scrolling, and you also have the case of dragging the scrollbar. ;) You also have the case of touch devices.
Note that with this I have set overflow:auto; on wrapper, thus no bottom scroll-bar.
With bottom scrollbar you would either have to live with it becoming tagged as in-view a tad to early, or tumble into the world of doing a cross-browser calculating of IE's clientHeight. But the code should hopefully be OK as a starter.
»»Fiddle««
function isView(wrp, elm)
{
var wrpH = $(wrp).height(),
elmH = $(elm).height(),
elmT = $(elm).offset().top;
return elmT >= 0 &&
elmT + elmH < wrpH;
}
$('.wrapper').bind('scroll', function (e) {
$('div.box').each(function(i, e) {
if (isView(".wrapper", this)) {
$(this).addClass('active');
} else {
$(this).removeClass('active');
}
});
});
Note that you should likely refactor in such a way that .wrapper height is only retrieved once per invocation, or if it is static, at page load etc.
Update; a modified version of isView(). Taking position of container into account. This time looking at dolphins in the pool.
»»Fiddle««
function isView(pool, dolphin) {
var poolT = pool.offset().top,
poolH = pool.height(),
dolpH = dolphin.height(),
dolpT = dolphin.offset().top - poolT;
return dolpT >= 0 && dolpT + dolpH <= poolH;
}

Categories