Repositioning element on scroll with jQuery - javascript

I am trying to reposition an element on scroll using jQuery scroll event and just adjusting margin-top property.Element is inside bootstrap nav so its showed along all other elements inside nav on desktop and for mobiles its just fixed positioned in upper left corner.element contains two flag links for different page languages.
My code is:
Html:
<div class="navbar yamm navbar-default">
<div class="flags">
<img src="UK_flag.png" alt="English">
<img src="DK_flag.png" alt="Danish">
</div>
<div class="navbar-header">
....
js:
var scrollingDiv = $(".flags").offset().top - $(window).scrollTop();
$(window).scroll(function(){
if(scrollingDiv > 100) {
$(".flags").css("margin-top", "24px");
}
if(scrollingDiv == 92) {
$(".flags").css("margin-top", "10px");
}
console.log(scrollingDiv);
});
console log displays always 92 as its position.One note page contains 1 more navigation which is above bootstrap nav so I need this margin-top fix for that.Whan nav goes down it reposition itself nicely,but whan it comes back it keeps margin-top property at 10px and flags jump out of aligment.
Thanks for all future ansers :)

Put var scrollingDiv = $(".flags").offset().top - $(window).scrollTop(); this inside you're $(window).scroll(function(){});
When you declare it like its current state. The scrollingDiv will keep 92px because it only sets it on page load.
If inside the scroll() function, it will update the value when the user is scrolling.
Small Demo (I dont know you're actual layout)
$(window).scroll(function(){
var scrollingDiv = $(".flags").offset().top - $(window).scrollTop();
if(scrollingDiv > 100) {
$(".flags").css("margin-top", "24px");
}
if(scrollingDiv >= 92 && scrollingDiv < 100) {
$(".flags").css("margin-top", "10px");
}
console.log(scrollingDiv);
});
.scroll-container {
height: 2000px;
overflow: auto;
}
.scroll-container .flags {
position: relative;
top: 120px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="scroll-container">
<div class="flags">
<img src="UK_flag.png" alt="English">
<img src="DK_flag.png" alt="Danish">
</div>
</div>

Related

How do I trigger jQuery when an anchor reaches the top of the viewport?

I need to trigger a jQuery function on a div when an anchor reaches the top of the viewport.
There are a lot of posts on StackOverflow based on an element entering the viewport (i.e the bottom of the viewport) see here for example.
Is it possible to trigger jQuery for the .nav-down element when the anchor #trigger hits the top of the view port?
HTML:
<div class="spacer"></div>
ANCHOR
<div class="nav-down"></div>
<div class="spacer"></div>
jS:
function scroll_style() {
var window_top = $(window).scrollTop();
var div_top = $('#trigger').offset().top;
if (window_top > div_top){
$('.nav-down').css("background","green");
}
}
$(function() {
$(window).scroll(scroll_style);
scroll_style();
});
This jS/jSFiddle doesn't work as intended, but it'll give an idea of the thought process I have:
https://jsfiddle.net/vanstone/s643m85b/14/
Can anyone assist me with getting this to work?
You can try using the getBoundingClientRect() to get the position of <a> with respect to the viewport and then implement your logic.
In the below example, I am checking for top < 10 to factor in the height of <a>
function scroll_style() {
if ($('#trigger')[0].getBoundingClientRect().top < 10) {
$('.nav-down').css("background", "green");
} else {
$('.nav-down').css("background", "yellow");
}
}
$(function() {
$(window).scroll(scroll_style);
scroll_style();
});
.spacer {
height: 700px;
background: red;
}
.nav-down {
height: 250px;
width: 100%;
background: blue;
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<div class="spacer"></div>
ANCHOR
<div class="nav-down"></div>
<div class="spacer"></div>

Sticky header after some scrolling?

okay here's an example of what i am trying to ask,
the nav bar of usatoday.
I'm using bootstrap affix. here's my code
<div class="header">
<div class="header-1">
<h1>this is some logo</h1>
</div>
<div class="header-2">
<h3>this is some heading</h3>
</div>
</div>
<div class="content" style="height:2500px;">
</div>
<div class="footer">
this is a footer
</div>
JavaScript
$('.header-2').affix({
});
how can I make the div header-2 to be fixed on the top, (when there is some scrolling and the div header-2 just reach the top position) as of the site I've mentioned earlier?
I would love to see the header-1 and header-2, but some scrolling should hide header-1 and stick header-2 to the top most.
thanks
See this Jsfiddle
you can check the position of the slider and add class accordingly
$(window).scroll(function () {
if( $(window).scrollTop() > $('#header-2').offset().top && !($('#header-2').hasClass('posi'))){
$('#header-2').addClass('posi');
} else if ($(window).scrollTop() == 0){
$('#header-2').removeClass('posi');
}
});
use jquery look at this example
http://jsfiddle.net/5n5MA/2/
var fixmeTop = $('.fixme').offset().top; // Get initial position
$(window).scroll(function() { // Assign scroll event listener
var currentScroll = $(window).scrollTop(); // Get current position
if (currentScroll >= fixmeTop) { // Make it fixed if you've scrolled to it
$('.fixme').css({
position: 'fixed',
top: '0',
left: '0'
});
} else { // Make it static if you scroll above
$('.fixme').css({
position: 'static'
});
}
});
Bootstrapped answer using Bootstrap.affix()
$('.header-2').affix({
offset: {
top: function () {
return (this.top = $(".header-2").offset().top);
}
}
});
This also needs CSS for the fixed positioning (see the Docs).
The affix plugin toggles between three classes, each representing a
particular state: .affix, .affix-top, and .affix-bottom. You must
provide the styles for these classes yourself (independent of this
plugin) to handle the actual positions.
.header-2.affix {
top: 0;
}
Working example at Bootply: http://www.bootply.com/S03RlcT0z0
<style>
.header {
top: 0%;
left: 0%;
width: 100%;
position:fixed;
}
</style>
I'm sorry didnt look at your problem carefully.
This may helps you Issue with Fixed Header and Bootstrap Affix / Scrollspy - Not jumping to correct location

Change margin-top position of an fixed positioned element after reaching the bottom of the page?

I need to change top-margin of an fixed div element from margin-top: 200px to margin top 0px after reaching the bottom of the page (or 200px from bottom) using vertical scrollbar.
And toggle return back if scrolling back to the top.
I guess some javascript/jQuery code code do that.
my html/layout code:
<div id="header" style="position: fixed; margin-top: 0px;">
Header content
</div>
<div id="main">
<div id="left" style="position: fixed; margin-top: 200px;">Google Ads here</div>
<div id="right">Content posts here</div>
</div>
<div id="footer">
Footer content
</div>
EDIT: Here are some images to make my question more clear.
normal state when you load the page:
problem when you scroll down, and the google ads column is in conflict with footer:
how it needs to be solved:
Derfder...
Voila, my proposed solution:
http://jsfiddle.net/YL7Jc/2/
The animation's a tad jerky, but I think it does what you want
(It's my take on an earlier s/o post:
Can I keep a DIV always on the screen, but not always in a fixed position? )
Let me know what you think!
Try below code which binds an event to window.scroll to check if the page hits the bottom (bottom in 200px) and moves the #left to top (margin-top: 0)..
DEMO: http://jsfiddle.net/6Q6XY/4/ ( added some demo code to see when it hits the bottom.)
$(function() {
var $left = $('#left');
$(window).bind('scroll', function() {
if (($(document).height()
- (window.pageYOffset + window.innerHeight)) < 200) {
$left.css('marginTop', 0);
} else {
$left.css('marginTop', 200);
}
});
});
Reference: https://stackoverflow.com/a/6148937/297641
You need to implement the window scroll function, this is a jquery implementation so please ensure you include the latest jquery libaries
$(window).scroll(function () {
if ($(window).scrollTop() + $(window).height() == $(document).height()) {
//if it hits bottom
$('#left').css("margin-top", "0px");
}
else {
$('#left').css("margin-top", "200px");
}
});
HTML
<div id="main" style="width: 960px; margin: 0px auto;">
<div id="left" style="position: fixed; top: 200px; left: 0px; background: #000; width: 100%; color: #fff;">Google Ads here</div>
<div id="right"></div>
</div>
JAVASCRIPT
<script type="text/javascript">
$(function() {
var documentHeight = $(document).height();
var windowHeight = $(window).height();
var left = $('#left');
var leftTopPosition = $('#left').css('top');
leftTopPosition = parseInt(leftTopPosition.substring(0, leftTopPosition.length-2));
$(window).scroll(function(){
var pageOffsetY = window.pageYOffset;
if((documentHeight - pageOffsetY - windowHeight) <= 200 && leftTopPosition == 200) {
left.stop().animate({
'top': '0px'
});
leftTopPosition = 0;
}
else if((documentHeight - pageOffsetY - windowHeight) > 200 && leftTopPosition == 0) {
left.stop().animate({
'top': '200px'
});
leftTopPosition = 200;
}
});
});
</script>
Hi Firstly you should have been more clearer in the first place before marking people down, as everyone give similar answers then it shows the question was not clear.
See Js Fiddle for a potential fix, please tweak as you need it with the pixels etc
for this problem you should use z-index in css
Try somethins like this
if ($(window).scrollTop() == $(document).height() - $(window).height())
{
document.getElementById(yourid).setAttribute("style","margin-top:0px");
}
Try this:
$(window).bind('scroll', function(){
if(($(window).height()-$(window).scrollTop())<200)
{
$('#left').css('margin-top',$(window).scrollTop());
}
else
{
$('#left').css('margin-top',200);
}
});

make a div element stick to the top of the screen

I have wrote a script to detect when I reach the div element which is a navigation bar and then I change it's css to position fixed and top 0 so it will be fixed to the top, the problem that it doesn't do that, it acts like scroll to top and it jumps to the beginning of the screen. (it's flickers)
Javascript
var currentScrollTop = 0;
var barMenuOriginalTopPos = $('#navigation').offset().top;
console.log('original:' + barMenuOriginalTopPos);
$(window).scroll(function() {
currentScrollTop = $(window).scrollTop();
console.log(currentScrollTop);
if(currentScrollTop >= barMenuOriginalTopPos && $('#navigation').hasClass('fixElementToTop') == false){
$('#navigation').addClass('fixElementToTop');
}
else if(currentScrollTop < barMenuOriginalTopPos && $('#navigation').hasClass('fixElementToTop') ){
$('#navigation').removeClass('fixElementToTop');
}
});
CSS
.fixElementToTop { position: fixed; top:0; z-index:100;}
Why
Here an non flickering solution via a jQuery plugin:
$(document).ready(function() {
$('#fixedElement').scrollToFixed({ marginTop: 0 });
});
Live example: http://bigspotteddog.github.com/ScrollToFixed/
Plugin's website: https://github.com/bigspotteddog/ScrollToFixed/
a css fixed bar on top of the screen
<div style="position:fixed;top:10px;left:10px">Nav bar</div>
Review:
sorry i didn't understand your initial question, here it goes, to avoid it flicking you should start the object with a fixed position, lets say:
<div style="height:120px">XXX</div>
<div id="navigation" style="position: fixed; top:120; z-index:100;">Navigation</div>
<div class="win" style="border: 1px solid; height: 900px;"></div>
the code:
$(window).scroll(function() {
currentScrollTop = 120-$(window).scrollTop();
console.log(currentScrollTop);
if (currentScrollTop<0) currentScrollTop=0
$("#navigation")[0].style.top=currentScrollTop+"px";
});​
Set this line
var barMenuOriginalTopPos = $('#navigation').offset().top;
as
var barMenuOriginalTopPos = $('#navigation').offset().top + 6;
Refer LIVE DEMO

Once user reaches a particular point on a page, automatically scroll to particular point/achor

So, here it is:
I'll have 4 divs. Example below. Each div a particular height (around 1500px) but have a width of 100%. Each div is a different colour.
I want it so that when the user scrolls the page and reach a particular point, javascript will kick in and automatically scroll the user to the next div.
So, say the user is vertically scrolling and div #2 is appear and div #1 is disappearing. When div #1 has about 200px left, the page will automatically scroll down so that div #2 is flush with the top of the browser window.
A good example: http://thejuly16.com/ Which basically does it but can't work out how.
1
Content here
2
Content here
3
Content here
4
Content here
That page isn't doing anything for me :/
Anyway, if I get what you mean, you should have some anchors on top of every div, hook some code to the scroll event, check scrollTop() value on it, and scroll to the anchors when this value is in a desired range. You can check this fiddle and the relevant jQuery code:
$(window).bind('scroll', function(){
if (($(window).scrollTop() > 1300) && ($(window).scrollTop() < 1350)) {
window.scrollTo(0,1500);
}
});
This might be a strange behavior for the user, since scrolling up is pretty messed up. However, we can fix this by checking if the user is going up or down in the page, like in this fiddle, just checking if the last scroll position was higher or lower than the current scroll position:
var currentScroll = 0;
var previousScroll = 0;
$(window).bind('scroll', function(){
currentScroll = $(window).scrollTop();
if (($(window).scrollTop() > 1300) && ($(window).scrollTop() < 1350) && currentScroll > previousScroll) {
window.scrollTo(0,1500);
}
previousScroll = $(window).scrollTop();
});
Obviously, you'd need to add as many if statements as "jumps" you want in your page.
I have a solution as given in the code below. Somehow its not working on jsFiddle but working on my machine. Please try it in your own editor
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
var isWorking = false;
var lastScrollPosition
function adjust(oDiv) {
if(oDiv.scrollTop > lastScrollPosition && !isWorking && oDiv.scrollTop % 400 > 300) {
isWorking = true
scroll(oDiv);
} else
lastScrollPosition = oDiv.scrollTop;
}
function scroll(div) {
if(div.scrollTop % 400 > 10) {
div.scrollTop = div.scrollTop + 10;
lastScrollPosition = div.scrollTop;
setTimeout(function(){scroll(div);}, 10);
} else
isWorking = false;
}
</SCRIPT>
</HEAD>
<BODY>
<div style="height: 440px; border: solid 1px red; overflow-Y: auto" onscroll="adjust(this)">
<div style="height: 400px; border: solid 1px green"></div>
<div style="height: 400px; border: solid 1px green"></div>
<div style="height: 400px; border: solid 1px green"></div>
<div style="height: 400px; border: solid 1px green"></div>
<div style="height: 100px"></div>
</div>
</BODY>
</HTML>
I think this functionality is available with jQuery. I have tried this but I was doing this on OnClick event in Javascript. In your case, onFocus or any other suitable event like mouseover etc should work.
Hope this helps.

Categories