Find dimensions of object that has display: none - javascript

On the right side of my page I have a list of sponsors.
My active page area (left side) height varies from page to page, depending on the story it contains every time.
I want the list's height to match the live pages height, so I thought I'd always show the main sponsors, and for the rest of them, I'd hide them, and show exactly as many as I can each time.
My markup looks like this:
<div id="xorigoi">
<a class="basic"><img src="/views/images/adjustable/sideXorigoi/1.png"></a>
<a class="basic"><img src="/views/images/adjustable/sideXorigoi/2.png"></a>
<a class="basic"><img src="/views/images/adjustable/sideXorigoi/3.png"></a>
<a class="rest"><img src="/views/images/adjustable/sideXorigoi/4.png"></a>
<a class="rest"><img src="/views/images/adjustable/sideXorigoi/5.png"></a>
<a class="rest"><img src="/views/images/adjustable/sideXorigoi/6.png"></a>
<a class="rest"><img src="/views/images/adjustable/sideXorigoi/7.png"></a>
<a class="rest"><img src="/views/images/adjustable/sideXorigoi/8.png"></a>
</div>
Every image is a link to each sponsor's site. Every image has it's own height.
Elements that have the class .rest are hidden using display: none
I'm trying to calculate if adding the new image will make the list longer than the page, but since the elements are hidden, offsetHeight = 0.
What can I do?
My javascript/jquery code so far looks like this:
$(
function(){
var containerHeight = $('#mainPageContainer')[0].offsetHeight; // total height of page
var xorigoi = $('#mainRightSide .rest'); // select the sponsors
var newHeight = 1062; // this is the right side height I am already using
$.each( xorigoi , function( index ){
if( newHeight + heightOfNewElement > containerHeight ){
return false; // break each
}
xorigoi.eq(index).css('display','block'); // display the sponsor
newHeight = newHeight + heightOfNewElement;
})
}
)
So bottomline, how can I get heightOfNewElement in the function above?

Since JavaScript is single-threaded, the browser will not redraw while it is executing. As such, you can safely set the elements to display:block, measure them, then hide them again and the user will be none the wiser.

Instead of display none, you could consider moving your elements outside the viewport. For example:
.rest {position:absolute;top:-9999px;}

Guess this will help you.
console.log(getDimensions($('#myElement')));
function getDimensions(element){
var tempElement = $(element).clone();
$(tempElement).css('display','block').css('visibility','hidden');
$(document.body).append(tempElement);
var obj = new Object();
obj.width = $(tempElement).width();
obj.height = $(tempElement).height();
$(tempElement).remove();
return obj;
}

Related

scroll to a div when scrolling, and scroll to top when div disappear

I have 2 divs on my webpage. first div is "#pattern" (red one), and second on is "#projets".(blue one)
when use scrolls for the first time, the window scrolls automaticaly to the the second div "#projets". I'm using jquery scroll-To plugin.
it works nice, even if when the users scroll with a large amount of scroll there could be on offset from the "#projets" div... If someone has an idea to correct this would be nice, but that's not my main trouble...
Now i'm trying to scroll back to the top of the page ("#pattern" div) as soon as "#pattern" div reappears when scrolling, the red one. so basically it should be as soon as the offset from the top of my screen of my div "#projets" is supperior to 1.
I've tried so many solutions without results, using flags, multiple conditions... it can be the same kind of thing as on this page, but user should be abble to scroll freely inside the page, not scrolling from hash to hash :
http://www.thepetedesign.com/demos/onepage_scroll_demo.html
here is my html :
<div id="pattern"></div>
<div id="projets"></div>
my css :
#pattern {
height:300px;
width: 100%;
background-color:red
}
#projets {
height:800px;
width: 100%;
background-color:blue
}
and my jquery :
var flag=0 ;
$(window).on('scroll',function(){
var top_projets_position = $("#projets").offset().top - $(window).scrollTop();
if((flag==0) && $(window).scrollTop()>1){
$(window).scrollTo('#projets', 500);
flag=1;
}
if($(window).scrollTop()==0){
flag=0;
}
});
here is jsfiddle :
http://jsfiddle.net/jdf9q0sv/
hope someone can help me with this, I can't figure out what I'm doing wrong, maybe a wrong method ! thanks
It looks like you need to track 3 things:
The scroll direction occurs.
The area you are currently viewing.
If scroll animation is currently happening (we need to wait until it's done, or problems will occur).
http://jsfiddle.net/vx69t5Lt/
var prev_scroll = 0; // <-- to determine direction of scrolling
var current_view ="#pattern"; // <-- to determine what element we are viewing
var allowed = true; // <-- to prevent scrolling confusion during animation
var top_projets_position = $("#projets").offset().top + 1;
$(window).on('scroll',function(){
var current_scroll = $(window).scrollTop();
if(current_scroll < top_projets_position && current_view=="#projets" && current_scroll < prev_scroll){
scrollToTarget("#pattern");
}
if($(window).height() + current_scroll > top_projets_position && current_view=="#pattern" && current_scroll > prev_scroll){
scrollToTarget("#projets");
}
prev_scroll = current_scroll;
});
function scrollToTarget(selector){
if(allowed){
allowed = false;
$(window).scrollTo(selector, {
'duration':500,
'onAfter': function(){ allowed = true; current_view = selector;}
});
}
}
This is just a quick solution based on your original code. A better solution would be to do something more Object Oriented (OOP) and track values in an object. Perhaps take an array of elements on object creation, grab all the boundaries and use the boundaries in your scroll handler to determine when to scroll to the next div.

Count visible elements in a scrolled div

I would like to calculate how many items are visible (including the last one visible even if there is 10px shown) in a scrollable div to animate it in an AJAX callback transition.
Depending on screens sizes, that can vary and I'm looking for detect that.
The goal is to do something like that (but I don't know the lt(n))
$(".box:lt(n)")...
Example:
— http://jsfiddle.net/gy4uLu7x/
This code will do
$(function () {
var total_width = $(".box").length * $(".box").outerWidth(true);
$(".scroll").width(total_width);
var scroll = $('.scroll');
var viewport_w = scroll.parent().width();
var box1 = $('.box:first');
var boxw = box1.outerWidth(true);
var view_items = Math.ceil(viewport_w/ boxw);
console.log(boxw, viewport_w, view_items);
});
this code works on the fact that all boxes' (outer)width is equal. It calculates with of the immediate parent of .scroll which happens to be the body element and checks how many elements will fit into it. It converts the decimal part of the division result into and integer to accommodate for your _ even if there is 10px shown_ requirement. i.e., even 0.1 is converted into a 1.
Update
margin collapse won't happen :D
Calculate the width of scroll's parent (since this is the "viewport" in this case). Then count the boxes that start at a position less than above calculated width. This will work only in the above mentioned scenario.
var parentContainerWidth = $(".scroll").parent().width();
var containedBoxesCount = $('.box').filter(function () {
return $(this).offset().left <= parentContainerWidth;
}).length;
alert(containedBoxesCount);
Here is a demo

why the width of elements are different after page load and after that moment?

The situation is that I want to change the size of an element right after the page load. The problem is that the element did not change because the result returned by the function getSearchBarWidth was negative number. Something strange here is that console prints incorrect values of the width of the two element web_logo and menu; their width should be small, but in the console, the width of both elements are equal the parent element, which is a navigation bar. But later, I print out again the width of two element in console, the result was correct. Can someone explain this?
update: it seems because I don't specify the width of the navigation bar. So is there any other except specify the width of the parent element to get the correct width of its children right after page loads?
<script src="js/function.js" defer></script>
Content of file js
// calculate the width of window and relevant element
function getSearchBarWidth(){
var wWidth = $(window).width();
var offset = 20; // distance between the search bar and each of the two next elements
var offset_1 = 15; // padding of each sides of the navi bar
var searchBarWidth = wWidth - $("#navi_bar > .web_logo").width() - $("#navi_bar > .menu").width() - 2*offset - 2*offset_1;
return searchBarWidth;
}
// change the size of search bar
if($("#navi_bar > .search_bar").length > 0){
console.log("window: "+ $(window).width());
console.log("logo: "+ $("#navi_bar > .web_logo").width());
console.log("menu: "+ $("#navi_bar > .menu").width());
$("#navi_bar > .search_bar").css("width", getWindowWidth());
}
My problem is solved. Just call setTimeout and then the width of element would be correct.

Getting Coordinates of an element on page scroll

I am having this problem where i have a set of 6 UL's having a common class x.Each of them consist of a specific section of the page.Now i have 6 menus that are related to each of the section.What i have to do is highlight the menu when its related section is in users view.
For this i thought that may be jQuery position(); or offset(); could have helped but they give the top and left of the element.I also tried using jQuery viewport plugin but apparently view port is big it can show more than one UL at a time hence i cant apply element specific logic here.I am not familliar to this but does anything changes of an element on scrolling?If yes then how to access it?
Please share your views.
Regards
Himanshu Sharma.
Is very easy to do it using jQuery and a dummy fixed HTML block that helps you find the current position of the viewport.
$(window).on("scroll load",function(){
var once = true;
$(".title").each(function(ele, index){
if($(this).offset().top > $("#viewport_helper").offset().top && once){
var index = $(this).index(".title");
$(".current").removeClass('current')
$("#menu li").eq(index).addClass('current')
once = false;
}
});
})
Check out a working example: http://jsfiddle.net/6c8Az/1/
You could also do something similar with the jQuery plugin, together with the :first selector:
$(window).on("scroll load",function(){
$(".title:in-viewport:first").each(function(){
var index = $(this).index(".title");
$(".current").removeClass('current')
$("#menu li").eq(index).addClass('current')
});
})
You can get the viewport's width and height via $(document).width() and $(document).height()
You can get how many pixels user scrolls via $(document).scrollTop() and $(document).scrollLeft
Combining 1 and 2, you can calculate where the viewport rectangle is
You can get the rectangle of an element using $(element).offset(), $(element).width() and $(element).height()
So the only thing left to you is to determine whether the viewport's rectangle contains (or interacts) the elements's rectangle
So the whole code may look like:
/**
* Check wether outer contains inner
* You can change this logic to matches what you need
*/
function rectContains(outer, inner) {
return outer.top <= inner.top &&
outer.bottom >= inner.bottom &&
outer.left <= inner.left &&
outer.right >= inner.right;
}
/**
* Use this function to find the menu related to <ul> element
*/
function findRelatedMenu(element) {
return $('#menu-' + element.attr('id'));
}
function whenScroll() {
var doc = $(document);
var elem = $(element);
var viewportRect = {
top: doc.scrollTop(),
left: doc.scrollLeft(),
width: doc.width(),
height: doc.height()
};
viewportRect.bottom = viewportRect.top + viewportRect.height;
viewportRect.right = viewportRect.left + viewportRect.width;
var elements = $('ul.your-class');
for (var i = 0; i < elements.length; i++) {
var elem = $(elements[i]);
var elementRect = {
top: elem.offset().top,
left: elem.offset().left,
width: elem.width(),
height: elem.height()
};
elementRect.bottom = elementRect.top + elementRect.height;
elementRect.right = elementRect.left + elementRect.width;
if (rectContains(viewportRect, elementRect)) {
findRelatedMenu(elem).addClass('highlight');
}
}
}
$(window).on('scroll', whenScroll);
Let's see if i understood well. You have a page long enough to scroll, and there is an element that when it appears in the viewport, you wanna do something with it. So the only event that's is triggered for sure on the time the element gets in the viewport is the 'scroll'. So if the element is on the page and the scroll is on the viewport, what you need to do is bind an action to the scroll event to check if the element is in the view each time the event is trigger. Pretty much like this:
$(window).scroll(function() {
check_element_position();
});
Now, in order for you to know if the element is in the viewport, you need 3 things. The offset top of that element, the size of the viewport and the scroll top of the window. Should pretty much look like this:
function check_element_position() {
var win = $(window);
var window_height = win.height();
var element = $(your_element);
var elem_offset_top = element.offset().top;
var elem_height = element.height();
var win_scroll = win.scrollTop();
var pseudo_offset = (elem_offset_top - win_scroll);
if (pseudo_offset < window_height && pseudo_offset >= 0) {
// element in view
}
else {
// elem not in view
}
}
Here, (elem_offset_top - win_scroll) represent the element position if there was no scroll. Like this, you just have to check if the element offset top is higher then the window viewport to see if it's in view or not.
Finally, you could be more precise on you calculations by adding the element height (variable already in there) because the code i just did will fire the event even if the element is visible by only 1 pixels.
Note: I just did that in five minutes so you might have to fix some of this, but this gives you a pretty darn good idea of what's going on ;)
Feel free to comment and ask questions

Find DOM elements at top and bottom of scrolling div with jQuery

I have a scrolling div containing list items. I have this boilerplate scroll event defined
$("#scrollingDiv").scroll(function(e) {
});
Inside of this scroll event function, how can I figure out which elements are at the top and bottom of the currently visible area?
You could try computing the positions of the list items with respect to the scrolling <div> and then scan the positions to see which ones match up with the scrollTop of the <div>.
Something like this perhaps:
var base = $('#scrollingDiv').offset().top;
var offs = [ ];
$('li').each(function() {
var $this = $(this);
offs.push({
offset: $this.offset().top - base,
height: $this.height()
});
});
$("#scrollingDiv").scroll(function() {
var y = this.scrollTop;
for(var i = 0; i < offs.length; ++i) {
if(y < offs[i].offset
|| y > offs[i].offset + offs[i].height)
continue;
// Entry i is at the top so do things to it.
return;
}
});
Live version (open your console please): http://jsfiddle.net/ambiguous/yHH7C/
You'd probably want to play with the fuzziness of the if to get something that works sensibly (1px visible hardly makes an element the top one) but the basic idea should be clear enough. Mixing in the height of #scrollingDiv will let you see which <li> is at the bottom.
If you have a lot of list items, then a linear search might not be what you want but you should be able to solve that without too much effort.

Categories

Resources