I have below code already and working well to scroll down to the ID ('expressRate') on page loading. But with change of requirement the page should scroll down to a point 50 pixels above the div ID 'expressRate'. Any help would be appreciated.
$location.hash('expressRate');
$anchorScroll();
try this javascript code after you scroll to the tag 'expressRate'
window.location('#expressRate');
window.scrollBy(0,-50);
//get the element
var $expressRate = $('#expressRate');
//get the vertical distance of the element from the top of the page
var verticalPositionOfElement = $expressRate.offset().top;
//added a timeout just so you could see the start and then the
//adjustment
setTimeout(function () {
//scroll the window down the element distance, minus whatever
$(window).scrollTop(verticalPositionOfElement - 50);
}, 1000);
html, body {
min-height: 5000px;
}
#expressRate {
min-height: 200px;
margin-top: 1000px;
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="expressRate">
window.scroll(0,findPos(document.getElementById("expressRate")) - 50);
function findPos(obj) {
var curtop = 0;
if (obj.offsetParent) {
do {
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return [curtop];
}
}
You don't need the framework for something so simple, you can use getBoundingClientRect() on the element you are trying to scroll to. Let's say:
The Element.getBoundingClientRect() method returns the size of an element and its position relative to the viewport.
Let's say that: result = b.getBoundingClientRect();
It will give you element's box in DOM related things but you really wanna only one thing: result.x coordinate representing x coordinate in pixels keeping in mind the VIEWPORT.
Now you can simply use window.scrollTo() to that element's x coordinate -50px to scroll where you wanted.
HTML:
<button id="but" onClick="scrol()">SCROLL TO 50px before</button>
<div id="a"><span id="b">WHERE AM I?</span></div>
<div id="tall"> </div>
<pre></pre>
CSS:
#but { position: fixed; }
#a { padding:16px; position: absolute; top:300px;}
#b { background:yellow;}
#tall { height:2000px }
JS:
function scrol(){
var b = document.querySelector('#b');
window.scrollTo(b.x, b.y - 200)
}
Voila, a 2-liner vanilla solution :)
For a quick demo, Please look at this Fiddle: http://jsfiddle.net/58gzv79h/1/
NOTE: In Fiddle, the solution is a bit bigger to show you how unlike other things in result, the X does not change from the time document was loaded.
Related
I want to try the same effect of this site but am getting lost in action on how to implement this animation.
When the user starts scrolling, the images in the header zoom in, the scrolling tab(vertical) does not move, up to a point which another image shows up, and only afterward the scroll bar starts working.
How can I achieve this animation when scrolling?
At the moment, what I thought was: to get the pixel value of the DOM when am scrolling, as well as the height of the div I want to target.
While the value of the DOM is less than the height of the box, the scale value should change based on the scrolling value.
The JS looks like this:
<script>
$(window).scroll(function() {
var initial_scroll = $('html').scrollTop();
var firstbox_height = $('#firstbox').height();
// console.log(firstbox_height);
while(initial_scroll < firstbox_height){
var sum = firstbox_height + ((firstbox_height * 0.01) / 100);
$('img').css({
// "transform": "scale(" + sum + ")"
});
}
});
</script>
I seem to be going into an infinite loop.
My pen is here
Here's a working sample. It's not flawless, it bugs when you scroll just a little back and forth at the top, the text size might change in the wrong direction. Also it doesn't work when scrolling with arrow keys. But what it does is that it should give you the idea on how to proceed.
There's probably a cleaner, nicer and more concise way to do this, but this is one way.
To get a perfectly working one, I think you might have to place a transparent <div> over the one that changes, just to keep track of the position and hence the direction.
Fiddle here: https://jsfiddle.net/codesam/nedj3ubx/53/
HTML:
<body>
<div id="box">
Text
</div>
<p id="direction">
</p>
</body>
CSS:
body {
height: 200vh;
}
#box {
width: 100%;
height: 50vh;
background-color: black;
color: white;
font-size: 72px;
}
jQuery:
$(document).ready(function(){
var initialScroll = -1;
var size;
$(window).on('scroll touchmove mousewheel', function(e){
var currentScroll = $(window).scrollTop();
if (currentScroll > initialScroll) {
$("#direction").text("down");
size = parseInt($("#box").css("font-size"));
if (size > 10) {
$("#box").css("font-size", "-=2");
e.preventDefault();
e.stopPropagation();
return false;
}
}
else if (currentScroll < initialScroll) {
$("#direction").text("up");
}
else if (currentScroll == 0 && initialScroll == 0) {
size = parseInt($("#box").css("font-size"));
if (size < 72) {
$("#box").css("font-size", "+=2");
e.preventDefault();
e.stopPropagation();
return false;
}
}
initialScroll = currentScroll;
});
});
I'm looking for a way in jQuery or pure JS to get the amount of pixels scrolled, not from the top of the page, but from the bottom of a div.
In other words I need to turn the amount scrolled beyond a div's height + its pixel distance from the top of the page into a variable.
I want to append this parallax code below so instead of calculating from the top of the page, calculates from a target div's distance from the top + its height.
/* Parallax Once Threshold is Reached */
var triggerOne = $('#trigger-01').offset().top;
$(window).scroll(function(e){
if ($(window).scrollTop() >= triggerOne) {
function parallaxTriggerOne(){
var scrolled = $(window).scrollTop();
$('#test').css('top',+(scrolled*0.2)+'px');
}
parallaxTriggerOne();
} else {
$('#test').css('top','initial');
}
});
I realize I didn't phrase this quite clear enough, I'm looking to only get the value of the amount of pixels scrolled since passing a div, so for example if I had a 200px tall div at the very top of the page and I scrolled 20 pixels beyond it, that variable I need would equal 20, not 220.
You can get a div's position by using div.offsetTop,
adding div.offsetHeight into div's distance from top of page will give you bottom of div, then you can subtract from window's scroll to get your desired value.
Feel free to ask if you have any doubts.
var div = document.getElementById('foo');
let div_bottom = div.offsetTop + div.offsetHeight;
var doc = document.documentElement;
var left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
var scroll_top, scroll_after_div;
setInterval(function(){
scroll_top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
scroll_after_div = scroll_top - div_bottom;
console.log(scroll_after_div);
}, 1000);
body { margin: 0; }
<div id="foo" style="position:relative; top: 100px; height: 30px; width: 100%; background-color: #000;"></div>
<div id="bar" style="position:relative; top: 700px; height: 30px; width: 100%; background-color: #000;"></div>
In this snippet setInterval method is printing the scroll value each second, you can scroll and see the change in value.
To work out the distance from the top of the page to the bottom of an element, you can add an elements outerHeight() with its offset().top.
Example: https://jsfiddle.net/dw2jwLpw/
console.log(
$('.target').outerHeight() + $('.target').offset().top
);
In pure JS you can get the bottom of the div directly with document.getElementById("my-element").getBoundingClientRect().bottom.
In jQuery you can use $('#my-element').offset().top + $('#my-element').height()
I'm trying to highlight some text in a div, with the highlight being a fixed line in said text. So far I've got a very simple solution that uses two divs, one that houses the text, and the other acting as the highlight, and as you scroll the text, it will pass through the highlight div.
HTML is as follows:
<div id="test">
text...
</div>
<div id="highlight"></div>
CSS is:
#highlight {
position: fixed;
top: 50%;
width: 100%;
background-color: #ccff00;
height: 30px;
opacity: 0.6;
}
#test{
position: absolute;
font-size: 30px;
top: 50%;
}
A demo of it can be found here
I was wondering if anyone knows how to make it so that scrolling the text can be done in a way where as a user scrolls, the next line becomes highlighted. Currently it scrolls normally, so the highlight may miss a line, or not highlight a complete line. Additionally, I was wondering how it would be best to make the text scroll all the way to the bottom. Would adding a margin of the same size as the offset at the top work? Alternative solutions for any of this would be appreciated as well.
Try adding an event listener to the window on scroll. Then calculate the offset by taking the scrollY % line-height and set the highlight top margin to the negative of that value.
JavaScript below:
var highlight = document.querySelector("#highlight");
window.addEventListener('scroll', function(e){
var y = window.scrollY;
var offset = y % 30;
highlight.style.marginTop = - y % 30 + "px";
});
See Working Fiddle
Not sure if this
https://jsfiddle.net/ok0x3apo/6/ is what you're looking for
You can see that I'm remodifying the entered text, to get line by line highlight as page scrolls.
var el = document.getElementById("text"),
content = el.innerHTML.replace(/ |^\s+|\s+$/g,""),
lines = content.split(/\./);
var html = "";
for(var i in lines){
html+="<p class='clear_display' id='id_"+i+"'>"+lines[i]+".</p>";
};
document.getElementById("text").innerHTML=html;
You can make changes to the "clear_display" class on how you prefer to have the text block.
function calledEveryScroll() {
var scrollPosition = $(window).scrollTop();
for(var i in lines){
var currentSection = document.querySelector("#id_"+i+"");
var sectionTop = currentSection.offsetTop;
if (scrollPosition<=0){
$(".clear_display").removeClass('active');
document.querySelector("#id_0").className += " active";
}
if (scrollPosition >= sectionTop-50) {
$(".clear_display").removeClass('active');
if (!$(currentSection).hasClass('active')) {
$(currentSection).addClass('active');
if(previous){
if(currentSection.offsetTop==previous.offsetTop){
$(previous).addClass('active');
}
}
var previous = currentSection;
}
//return false;
}
}
}
function resizing(){
var offset =100;
var bottom = $(window).height()-offset;
$('#text').css('margin-bottom',bottom);
}
This function checks each line when page scrolls.For the scroll to reach the bottom I'm calculating the margin-bottom.Hope it helps.
I have 2 divs, a navigation and a main content in a bootstrap grid system. The length of either can vary depending on amount of content. I need them both styled to fill 100% of the browser window IF neither has the content to reach the bottom naturally. But if at least one of the divs has more content than the length of the browser window, I need to be able to scroll down the page with the styles of both divs remaining in tact and both have a height of the longer of the 2 divs.
I'm currently using a javascript resize function which seems to work but not in the case where neither div is long enough to fill the height of the browser window. Any suggestions?
HTML
<div class="row">
<div id="nav" class="col-xs-2">
Variable Height Navigation
</div>
<div id="main" class="col-xs-10">
Variable Height Content
</div>
</div>
Javascript
function resize() {
var h = (document.height !== undefined) ? document.height : document.body.offsetHeight;
document.getElementById("nav").style.height = h + "px";
}
resize();
window.onresize = function () {
resize();
};
I am trying to understand you question, and if I'm correct what you are looking for is:
Both divs need to be equally high
They need be at least the height of the screen
They need to take the height of the highest div
So let's try to achieve this goal as simply as possible:
var main = document.getElementById('main');
var nav = document.getElementById('nav');
function resize(){
var highest;
// Set the divs back to autosize, so we can measure their content height correctly.
main.style.height = 'auto';
nav.style.height = 'auto';
// Find the highest div and store its height.
highest = main.clientHeight > nav.clientHeight
? main.clientHeight
: nav.clientHeight;
// Check if the highest value is the div or the window.
highest = highest > window.innerHeight
? highest
: window.innerHeight;
// Assign the newly found value
main.style.height = highest + 'px';
nav.style.height = highest + 'px';
}
resize();
// Also, you don't need to wrap it in a function.
window.resize = resize;
// However, better would be:
window.addEventListener('resize', resize, false);
#main, #nav {
width: 100%;
height: auto;
}
#main { background: red; }
#nav { background: green; }
<div id="main"></div>
<div id="nav"></div>
Now, If you aren't bothered with the actual sameness in heiught of both divs but just want them to at least be one screenful, you should consider using CSS:
html, body { height: 100%; }
#nav, #main { min-height: 100%; }
I think that is the better solution (no Javascript!) and sort-of does what you want, bar the fact that you won't have to equally high div elements. However, you would barely notice it as each will at least fill the page.
You could try using viewport height:
For example:
#nav {
min-height: 100vh;
}
#main {
min-height: 100vh;
}
See Bootply.
This will also remove the need for JavaScript.
Let's say I have a single HTML page. 2000 pixels long for example. I want to detect if a visitor reaches a certain point on the page.
The page structure:
0px = begin of the page;
500px = about us page;
1000px = contactpage;
Is there a way with jQuery to detect if a user reaches the points described above?
You probably want jQuery's scroll event-binding function.
Yes, I would create three divs and then have a mouse over event on each. Example:
$("#begin").mouseover(function(){
alert("over begin");
});
$("#about").mouseover(function(){
alert("over about");
});
$("#contact").mouseover(function(){
alert("over contact");
});
You can see a working fiddle here: http://jsfiddle.net/ezj9F/
Try THIS working snippet.
Using this code you don't have to know position of the element you want to check if it is visible.
JQuery
var $window = $(window);
// # of pixels from the top of the document to the top of div.content
var contentTop = $("div.content").offset().top;
// content is visible when it is on the bottom of the window and not at the top
var contentStart = contentTop - $window.height();
// content is still visible if any part of his height is visible
var contentEnd = contentTop + $("div.content").height();
$window.scroll(function() {
var scrollTop = $window.scrollTop();
if(scrollTop > contentStart && scrollTop < contentEnd) {
console.log('You can see "HELLO"!');
} else {
console.log('You cannot see "HELLO"!');
}
});
HTML
<div class="scroll"></div>
<div class="content">HELLO</div>
<div class="scroll"></div>
CSS
div.scroll {
background-color: #eee;
width: 100px;
height: 1000px;
}
div.content {
background-color: #bada55;
width: 100px;
height: 200px;
}
EDIT: Now the algorithm is checking if any part of the div.content is visible (it is considering height of the element). If you are not interested in that change contentEnd to var contentEnd = contentTop.