Use jQuery to mirror height of a dynamic element - javascript

I have a sidebar on my page that I want to always be 100% of the container size. Sadly, I can't tell the element to do this via CSS alone as the page has a variable height due to dynamic content.
Is it possible to use jQuery to find the height of the content container, and adjust the sidebar height to match it?
I found a few jQuery plugins that kind of do what I want, but feel they are over complicated (and I can't seem to get them to work anyway!).

Assuming the id of your container is "container" and the id of your sidebar is "sidebar", you could try the following (untested!)
$(document).ready(function() {
$('#sidebar').height($('#container').height());
});
This should (on document load), resize the sidebar height to the same as the container height.

I'm going to continue on from Damovisa's answer.
$(document).resize(function(){
$('#sidebar').height($('#container').height());
});
However, this could fire an awful lot if you resize the page a lot. You could try this
$(document).resize(function(){
clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(function() {
$('#sidebar').height($('#container').height());
}, 100);
});
In the second example, it will only resize 100 microseconds after resizing.
This is also assuming that $(document).resize() will be triggered when the page size changes. You could always wrap it in a function, and call it on completion of any slideDown() etc

Related

Navigation bar doesn't work with Intersection Observer API

I have a problem when I use the Intersection Observer API. I am trying to use it for, once the nav-bar is not visible anymore when you scroll, make this latter appears with a white background and fixed to the viewport.
I first of all tried to console.log('visible') and console.log('visible') when the nav-bar is visible or not and I succeed ! But when I wanted to apply the new class when the navbar wasn't visible anymore, my page starting to get mad : the class was applied and removed, and the console was only displaying "visible", "not visible" all the time very frequently.
I think it is because when I apply the class, it moves the rootMargin (of the options object) but I don't know how to fix it.
My entire website (my code is in app.js) : https://replit.com/#Xeway/IntersectionObserver#app.js
PS : I only have build app.js, HTML and CSS are codes made by FreeCodeCamp.
PS : Sorry for the link, but I can't share this code here because my code uses backtick and it doesn't seems to work ^^ Also, try to open the website with a big width because it's responsive and you can see more precisely the problem when it's on a computer's screen width.
Thank you in advance for your answers guys :)
Intersection observer is not needed for your case.
You just need to apply class to your header, when window is scrolled beyond certain height.
In your case, it would be equal to the height of the header.
So, when the window scroll height > height of the header, then apply class
and in the else, remove the class.
Call the same function on document.ready as well (To check the window scroll position on the page load, if the window is already scrolled).
Here is the little script for your help:
$(window).scroll(function() {
var scroll = $(window).scrollTop();
// assume 100px is the height of the header
if (scroll >= 100) {
addScrolledClassToHeader();
} else {
removeScrolledClassToHeader();
}
});
function addScrolledClassToHeader() {
$('header.site-header').addClass('header-is-scrolled');
}
function removeScrolledClassToHeader() {
$('header.site-header').removeClass('header-is-scrolled');
}

Why does $(window).width() change while the page is loading?

I noticed that my scripts were setting widths incorrectly, so I tried the following snippet:
var prev;
setInterval(function(){
if($(window).width()!=prev)
console.log(prev=$(window).width());
},1);
This printed 2 different values: 1464 and 1481. Since these are 17px apart, I'm almost certain this is caused by scrollbars. The second value is the correct value.
Why does $(window).width() change without resizing the window? Shouldn't it return the browser window's width, which should be constant?
$(window).width() returns the width of the window object excluding scrollbars (otherwise known as the viewport width). Depending on the operating system and browser, the vertical scrollbar can often subtract from the viewport width. This means you should call this function once all your content has been loaded, and you'll need to call it again if the content changes.
Putting this in the $.ready() function won't guarantee that you'll get the correct width with respect to the final page content. This is because $.ready fires when the DOM is loaded, but there might still be images/fonts that can affect the layout. It's very possible that a scrollbar can get added after you call $.ready(). The easiest solution to this problem is to place your call inside the $(window).load() function instead, as this fires when all content has been loaded, and there's nothing more to render.
Generally speaking, it's a good idea to set the width on DOM ready, window load, window resize, and any time the content changes. This can be done like so:
$(function() {
var window_width;
function set_window_width() {
window_width = $(window).width();
// do something with window_width
}
set_window_width(); // set width on DOM ready
$(window).on('load resize', set_window_width); // set width on window load and resize
function custom_load_content() {
// load / change content
set_window_width();
}
});
Most (if not all) of the time, the viewport width is what you want. You're probably using the width to perform some calculations and/or resize some elements, and this should always be relative to the viewport, because your CSS is relative to the viewport. But, if for some reason you want to get the width including scrollbars, you can use window.innerWidth instead (source).
$(window).width() is affected by the margin, border and padding.
These can change as the DOM is being loaded.
As mentioned above, make sure you are waiting until $(document).ready() before you start looking at / twiddling with the DOM objects.
More info here http://api.jquery.com/width/
In most of the cases, the window width changes with the content, so there must be some ajax call coming which changes some content of the window. You can use browser debug tool and open the network traffic window to see what comes when the window width changes, debug into the javascript file to find which part of window changes with that ajax call, this may help you to find the reason.

css / jquery - need persistent footer without using position:fixed

I am programming a mobile site and I want an element to be fixed at a certain position on the screen and stay there even as the user scrolls down the page. I can't use position:fixed as far as I know because iPhone doesn't support it. How would I accomplish this? I do not want to use jquery mobile.
you might want to make use of jquery mobile, in particular check out the section "persistent footer navigation bar"
http://jquerymobile.com/test/docs/toolbars/footer-persist-a.html
Im ganna start off by saying iOS5 will have support for fixed.
but for now, you're ganna have to use javascript to move it.
Lets assume ur footer's ID is "myFooter"
window.addEventListener(
'scroll',
function() {
document.getElementById('myFooter').style.top =
(window.pageYOffset + window.innerHeight - footerHeight) + 'px';
},
false
);
that should move it when you scroll (footerHeight is your footer's height and can also be retrieved with document.getElementById("myFooter").style.height if the style object was used to define the height
If there is something I have not forseen in the above solution, you can always divide the viewport into two sections, the content and footer. Just absolutely position the footer and use the touch events (touchmove,touchend,targetTouches etc) in combination with scrollTo (scrollTo(destination, duration)) on your content area

How does one move html elements with scroll?

I want to create scroll behavior like what can be found here. If you scroll down the page you will notice the crabs, sharks, waves etc are animated whenever the page moves. How can this be achieved? Is this a script or CSS animation?
Edit: text bubbles also appear and disappear at different scroll points.
If you would like a more robust jQuery script to help you out: Per the answer at Loading a long page with multiple backgrounds based on vertical scroll value in jQuery?:
A slightly more full fat solution to the already great one suggested
by Justin is to use jQuery Waypoints to manage the in viewport events.
...
(the answer by Nicholas Evens)
It is a script, just bind a function to the window 'scroll' event with a callback function to do whatever you want. You can tell how far you've scrolled with window.scrollY.
$(window).bind('scroll', function () {
console.log(window.scrollY);
});
You need to subscribe scroll event using jQuery and move your element basing on the scrolling offset whitch can be reached using .scrollTop() property
$(window).scroll(function () {
var scrollOffset = $(this).scrollTop();
// move element to the offcet
});
I didn't look at the site's source code, but I believe it depends on JS. Javascript is necessary to listen to the scroll event of the page, and act according to the current value of document.scrollTop. Then the elements can be positioned with JS, and images can be switched either directly in JS, or by using CSS to change some element's CSS class.
That is definitly a script, you can attach an onscroll event and get the percentage of the current scroll and just position your "crabs" depending on that.
There was already a lot of scripts of how to get the percentage here

How to scroll to an element in jQuery?

I have done the following code in JavaScript to put focus on the particular element (branch1 is a element),
document.location.href="#branch1";
But as I am also using jQuery in my web app, so I want to do the above code in jQuery. I have tried but don't know why its not working,
$("#branch1").focus();
The above jquery (focus()) code is not working for div, whereas If i am trying the same code with textbox, then its working,
Please tell me, how can I put focus on a div elemnt using jQuery?
Thanks!
For my problem this code worked, I had to navigate to an anchor tag on page load :
$(window).scrollTop($('a#captchaAnchor').position().top);
For that matter you can use this on any element, not just an anchor tag.
Like #user293153 I only just discovered this question and it didn't seem to be answered correctly.
His answer was best. But you can also animate to the element as well.
$('html, body').animate({ scrollTop: $("#some_element").offset().top }, 500);
You can extend jQuery functionalities like this:
jQuery.fn.extend({
scrollToMe: function () {
var x = jQuery(this).offset().top - 100;
jQuery('html,body').animate({scrollTop: x}, 500);
}});
and then:
$('...').scrollToMe();
easy ;-)
Check jQuery.ScrollTo, I think that's the behavior that you want, check the demo.
Check out jquery-scrollintoview.
ScrollTo is fine, but oftentimes you just want to make sure a UI element is visible, not necessarily at the top. ScrollTo doesn't help you with this. From scrollintoview's README:
How does this plugin solve the user experience issue
This plugin scrolls a particular element into view similar to browser
built-in functionality (DOM's scrollIntoView() function), but works
differently (and arguably more user friendly):
it only scrolls to element when element is actually out of view; if element is in view (anywhere in visible document area), no scrolling
will be performed;
it scrolls using animation effects; when scrolling is performed users know exactly they're not redirected anywhere, but actually see
that they're simply moved somewhere else within the same page (as well
as in which direction they moved);
there's always the smallest amount of scrolling being applied; when element is above the visible document area it will be scrolled to the
top of visible area; when element is below the visible are it will be
scrolled to the bottom of visible area; this is the most consistent
way of scrolling - when scrolling would always be to top it sometimes
couldn't scroll an element to top when it was close to the bottom of
scrollable container (thus scrolling would be unpredictable);
when element's size exceeds the size of visible document area its top-left corner is the one that will be scrolled to;
Use
$(window).scrollTop()
It'll scroll the window to the item.
var scrollPos = $("#branch1").offset().top;
$(window).scrollTop(scrollPos);
If you're simply trying to scroll to the specified element, you can use the scrollIntoView method of the Element.
Here's an example :
$target.get(0).scrollIntoView();
I think you might be looking for an "anchor" given the example you have.
This link will jump to the anchor named jump
<a name="jump">This is where the link will jump to</a>
The focus jQuery method does something different from what you're trying to achieve.
For the focus() function to work on the element the div needs to have a tabindex attribute. This is probably not done by default on this type of element as it is not an input field. You can add a tabindex for example at -1 to prevent users who use tab to focus on it. If you use a positive tabindex users will be able to use tab to focus on the div element.
Here an example: http://jsfiddle.net/klodder/gFPQL/
However tabindex is not supported in Safari.
maybe you want to try this simple one
$(document).ready(function() {
$(".to-branch1").click(function() {
$('html, body').animate({
scrollTop: $("#branch1").offset().top
}, 1500);
});
});

Categories

Resources