Binding a jquery value to a specific DIVs height - javascript

Sorry, I'm a jquery/js apprentice. I have a jquery sticky nav setup with skrollr set to "stick" at a top offset of 590px. This seemed okay but I came to find I need that offset to be unique on some pages and instead of having to manually apply the unique offset I wanted to know if I can bind the offset value to a specific DIVs height? This would help make things easier to manage in the future.
Here is my codez:
$(document).ready(function() {
var stickyNavTop = $('#navmenu').offset().top+590;
var stickyNav = function(){
var scrollTop = $(window).scrollTop();
if (scrollTop > stickyNavTop) {
$('#navmenu').addClass('sticky');
} else {
$('#navmenu').removeClass('sticky');
}};
stickyNav();
$(window).scroll(function() {
stickyNav();
});
});
The DIV in question with the height value I need to bind it to has a class of .custom-hero-background
It has a global height applied of 600px but on some pages I override this with unique heights.

Just add this in your script, outside of all the other functions, except for $(document).ready(function(
var theHeight = $('.custom-hero-background').height();
and then instead of having a fixed +590 for the offeset, just do + theHeight. If you need it to be 10 pixels less than theHeight, just do theHeight - 10
var stickyNavTop = $('#navmenu').offset().top+theHeight;

Related

Change height of element on resize

Hello guys I'm trying to change height of my element dynamically.
These are my variables.
var windowWidth = 1440;
var currentWidth = $(window).width();
var elementHeight = $('#line4').height();
Now what I want is when difference between window width and current width is lower then 6 I want to change height of my element. I want to do this every time when (windowWidth - currentWidth)<6. So every time when window resizes and it's lower then 6 I want to change height of element by minus 14px. This is what I've tried.
$( window ).bind("resize", function(){
if((windowWidth - currentWidth)<6) {
$("#line4").css('height', elementHeight-14);
}
});
It does not work and I don't know what I'm missing. Also follow up question can I change other CSS properties this way. For this particular problem I will also need to change css top property in the same way, because I have some div with absolute position.
You need to measure the current width of the window on every resize event, since it's changing too.
var windowWidth = 1440;
var currentWidth = $(window).width();
var elementHeight = $('#line4').height();
$( window ).bind("resize", function(){
currentWidth = $(window).width()
if((windowWidth - currentWidth)<6) {
$("#line4").css('height', elementHeight-14);
}
});
You need to get windowWidth each time resize event called
And you should add debounce into resize event for better performance.
I often do like this, maybe you can search any better way:
var resizeTimer;
$(window).on('resize', function(e) {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(function() {
// Run code here, resizing has "stopped"
currentWidth = $(window).width()
if((windowWidth - currentWidth)<6) {
$("#line4").css('height', elementHeight-14);
}
}, 250);
});
and I created this to test, you can try it. Btw i increase from 6 to 600 to check easier :D
https://codepen.io/huytran0605/pen/NgBEVO

Issue calculating table scrollbar location

So I have a script that adds a slight shadow to table edge where you can scroll, depending on the location of the scrollbar, but it sometimes doesn't work.
This is one part of it:
$('table').on('scrollstart scrollstop', function(){
if($(this).parent().hasClass('table-wrap')){
var elem = $(this),
elemBody = elem.find('tbody'),
elemParent = elem.parent('.table-wrap');
var scrolled = (elemBody.outerWidth() - elemParent.outerWidth() - elem.scrollLeft());
if(scrolled === 0){
elemParent.addClass('left_active');
elemParent.removeClass('right_active');
} else if(elem.scrollLeft() === 0) {
elemParent.removeClass('left_active');
elemParent.addClass('right_active');
} else {
elemParent.addClass('left_active');
elemParent.addClass('right_active');
}
}
});
This part sometimes I have to add "+1" to "elem.scrollLeft() --here---); to make it work.
var scrolled = (elemBody.outerWidth() - elemParent.outerWidth() -
elem.scrollLeft());
But then I noticed, some tables it helps and on others, it stops working. Meaning when I scroll to right the 'right_active' class will not disappear.
Any suggestions?
Have you tried including scrollbar width in your calculation for var scrolled?
var scrolled = (elemBody.outerWidth() - elemParent.outerWidth() - elem.scrollLeft());
I think you are on the right track but the width is probably not precise since .outerWidth() doesn't include scrollbar width. Hence, the maximum scroll width is always greater than the actual element width.

How to make an element become fixed when 50px from the top of the screen

I have a html div element that scrolls with the page but I would like it to become fixed once it reaches 50px from the top of the screen...
How is this done?
My div id is #box
Thanks!
-Ina
If you want it to be fixed at the top of the page at some distance from the top, you can check the top offset of the element and change the class when it reach the distance you want.
Here is the jquery code for your reference
jQuery(document).scroll(function() {
var documentTop = jQuery(document).scrollTop();
console.log('this is current top of your document' + documentTop );
//box top is 891
if (documentTop > 841) {
//change the value of the css at this point
jQuery("#box").addClass("stayfix");
}
else
{
jQuery("#box").removeClass("stayfix");
}
});
You need to be more specific about what have you done so far. For eg, how did you make the div element to scrolls inside the page. using css or js/jquery animation features?That will help us to give more specific answer.
**Edited According to your fiddle.
They are right, this question is duplicate. Here is a code I made with answers from the forum.
var box_top = $("#box").offset().top;
$(window).scroll(function (event) {
if ($(window).scrollTop() >= (box_top - 50)) {
$("#box").css({position:"fixed",top:"50px"});
} else {
$("#box").css({position:"relative"});
}
});
Hope it helps anyway.
https://jsfiddle.net/ay54msd5/1/
Try something like this. It's a solution using jquery (hopefully not a problem) that checks the scrollHeight of the page every time the page scrolls. If the scrollHeight is greater than a certain threshold, the element becomes fixed. If not, the element is positioned relatively (but you can do whatever you want in that case.
$(document).ready(function() {
var navFixed = false;
var $box = $("#box");
var topHeight = 50;
$(document).scroll(function() {
if ($(document).scrollTop() >= topHeight && !navFixed) {
$box.css("position", "fixed");
navFixed = true;
}
else if ($(document).scrollTop() < topHeight && navFixed) {
$box.css("position", "relative");
navFixed = false;
}
});
});
You would have to write some additional CSS targeting the #box element that tells it what coordinates you'd like it to be fixed to.

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

function equalHeight , set a minimum Height to apply?

I have tried everything, but without javascript I cannot achieve the bad layout my designer gave to me!!
As you can see I have the div #backgr-box that has to be absolute positioned with z-index to be properly behind the #contenuto (which holds the page content!!)
Now to solve the extensibilty trouble of #backgr-box I have the below code that works if the content of #contenuto is longer than the sidebar #barra-laterale , but it is not ok in opposite case, see page: http://demo.liquidfactory.it/secondopolo/per-informarti
So how can I tell javascript to apply that calculation only over a minimum height of div sidebar #barra-laterale ??
Need help.. please!
function equalHeight(group) {
tallest = 0;
group.each(function() {
thisHeight = $(this).height();
if(thisHeight > tallest) {
tallest = thisHeight = $("#contenuto").height() - 380;
}
});
group.height(tallest);
}
$(document).ready(function() {
equalHeight($(".column"));
});
The problem is likely with this line:
tallest = thisHeight = $("#contenuto").height() - 380;
Currently it is setting both the variables tallest and thisHeight to the height of the content region minus 380 pixels. Change it to:
tallest = thisHeight;
And it will resize all the columns to the height of the tallest one.
Edit: It looks like your right-hand column actually consists of multiple columns with a class of .barra-laterale in this case you may want to take another tack altogether:
// calculate the total height of the content are and sidebar
var contentHeight = $("#contenuto").height();
var sidebarHeight = 0;
$(".barra-laterale").each(function() { sidebarHeight += $(this).height(); })
if (sidebarHeight > contentHeight) {
$("#contenuto").height(sidebarHeight);
} else {
// extend the last sidebar column to cover the difference between the
// height of the content and the sum of the sidebar heights
var lastSideBarHeight = $(".barra-laterale").last().height();
var heightDifference = contentHeight - sidebarHeight;
$(".barra-laterale").last().height(lastSideBarHeight + heightDifference)
}

Categories

Resources