Is there a way to start the page at certain div without scrolling using jQuery?
For now i'm using this code:
$('html, body').animate({
scrollTop: $('.here').offset().top
}, 500);
But this, of course, scrolls to that div on page loading, i want it to just load the page straight to that div(if there is a certain cookie set)
You don't need to use animate to change the scroll position. Just do $('html, body').scrollTop($('.here').offset().top).
Or probably even simpler, just give the desired element an id and then set the window.location.hash to be that id.
You can use window.scrollTo():
const target = $('.here').offset().top;
window.scrollTo({
top: target,
behavior: 'instant'
});
.block {
height: 49vh;
background: red;
margin-bottom: 1vh;
}
.here {
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="block"></div>
<div class="block"></div>
<div class="block here"></div>
<div class="block"></div>
"if there is a certain cookie set"
If you're using any server-side scripting language to get/set that cookie, you could also append the id to the div as a hash to make it jump to that div.
So for example, if my page is
....
<div id="somecontent">...</div>
<div id="jumphere">...</div>
<div id="someothercontent">...</div>
...
and the url is http://www.myawesomewebsite.com/page#jumphere, then in most browsers, your page will jump to that point after load
You can run this javascript when the page loads. It will take you to the specified div with the id specified. Take a look at the snippet below:
let boxTop = $("#orange-div").offset().top;
window.scrollTo(0, boxTop);
.padding-div {
height: 200vh;
width: 200px;
background-color: red;
}
.box {
height: 100px;
width: 200px;
background-color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="padding-div">
</div>
<div id="orange-div" class="box">
</div>
<div class="padding-div">
</div>
Related
How do I make scrollIntoView only scroll the immediate parent (e.g. div with overflow-y: scroll;) and not the whole page?
I have a web interface I'm making for an internal, very-specific purpose. Among other elements on my page is a div with a specified height and overflow-y is scroll.
I have data which will periodically appear in this area and I want it to always be scrolled to the bottom (e.g. the console output of a subprocess on some remote server).
If I use scrollIntoView, it scrolls the overflow-y div..... but also scrolls the whole page.
On a computer with a large monitor, this isn't an issue, but on my laptop with a smaller screen it also scrolls the whole window, which is definitely not the intended/desired behavior.
I think what you might be looking for is
.scrollIntoView({block: "nearest", inline: "nearest"});
Where supported (basically anywhere except IE and SafarIE) this will do the 'least' movement to show the element; so if the outer container is visible, but the target element is hidden inside that container -- then it should scroll the inner container but not the page.
I think you're looking for a combination of scrollTop and scrollHeight. You can use the first to set where you want the div to scroll to, and the second to get the height of all the info in the div:
var scrollyDiv = document.getElementById("container");
scrollyDiv.scrollTop = scrollyDiv.scrollHeight
setInterval(() => {
var textnode = document.createElement("P");
textnode.innerHTML = "Whatever"
scrollyDiv.appendChild(textnode);
scrollyDiv.scrollTop = scrollyDiv.scrollHeight
}, 1000)
#container {
height: 200px;
overflow-y: scroll;
}
#big-content {
height: 400px;
background-color: green;
}
<div id="container">
<div id="big-content"></div>
<p>The bottom</p>
</div>
I tried to reproduce your case and I think that scrollIntoView() will not work as you wish. Try to use scrollTop instead.
Hope it will save your time.
const btn = document.getElementById('js-scroll');
btn.addEventListener('click', () => {
const targets = document.querySelectorAll('.scrollable');
targets.forEach(t => {
// Scroll each item
t.scrollTop = t.scrollHeight;
});
});
.scroll-btn {
position:fixed;
left: 10px;
top: 10px;
padding: 10px;
font-weight: 700;
font-size: 16px;
}
.content {
min-height: 100vh;
background-color: #efefef;
padding: 35px 10px;
}
.scrollable {
margin: 15px; 5px;
padding: 5px;
background-color: #fafafa;
height: 500px;
overflow-y: scroll;
overflow-x: hidden;
}
.scrollable-data {
padding: 10px;
margin-bottom: 1px;
min-height: 600px;
background-color: #55b7ab;
}
<button id="js-scroll" class="scroll-btn">Scroll</button>
<section class="content">
<div class="scrollable">
<div class="scrollable-data">Some data 1</div>
<div class="scrollable-data">Some data 1</div>
</div>
<div class="scrollable">
<div class="scrollable-data">Some data 2</div>
<div class="scrollable-data">Some data 2</div>
</div>
<div class="scrollable">
<div class="scrollable-data">Some data 3</div>
<div class="scrollable-data">Some data 3</div>
</div>
</section>
Solution for React 16
Here is an answer for this problem using React 16, for people who want to have a scrollable element scroll to its bottom upon some event. I was having the problem that scrollIntoView() was causing the whole window to adjust, which was undesirable; just need the scrolling element to scroll to the bottom (like a terminal) on demand.
Add a ref to the element with overflowY: "scroll", and use the formula this.body.current.scrollTo(0, this.body.current.scrollHeight) like so:
constructor() {
...
this.body = React.createRef() // Create a ref to your scrollable element
}
...
componentDidUpdate(prevProps, prevState) { // or whatever action you want
// The Important Part, where you scroll to the y-coord
// that is the total height, aka the bottom.
// .current is important, as you want the version of
// that ref that is rendered right now.
this.body.current.scrollTo(0, this.body.current.scrollHeight)
...
}
...
render() {
return (
<div style={style.container}>
<div ref={this.body} style={style.body}> // React ref tagged here
....
</div>
</div>
}
I'm trying to use scrollIntoView() in my application, but because I have a top fixed bar, when I use the scrollIntoView(), the elements will be scroll to the fixed bar back.
This means that when I try to put some element visible to the user, by scrolling the element to a visible area, it will be scrolled, but to another invisible ate that is were this fixed bar is.
Follows an example of what I'm trying to do:
let element = document.getElementsByClassName('second-element')[0];
element.scrollIntoView();
.fixed-element{
height: 30px;
width: 100%;
background-color:black;
position:fixed;
}
.parent-element {
width: 100%;
height: 40000px;
background-color:blue;
}
.element {
width: 100%;
height:100px;
background-color: yellow;
margin-top:10px;
}
.second-element{
width: 100%;
background-color: red;
height:200px;
}
<div class="fixed-element"></div>
<div class='parent-element'>
<div class='element'></div>
<div class='element'></div>
<div class='element'></div>
<div class='element'></div>
<div class='element'></div>
<div class='element'></div>
<div class='element'></div>
<div class='element'></div>
<div class='second-element'></div>
<div class='element'></div>
<div class='element'></div>
<div class='element'></div>
<div class='element'></div>
<div class='element'></div>
<div class='element'></div>
<div class='element'></div>
<div class='element'></div>
<div class='element'></div>
</div>
There is any way that I could use this function in a way that the scroll elements not became invisible because of the fixed bar?
I would like a vanilla JavaScript solution. Also, and only if it is possible, a solution that doesn't need to know the existent of any fixed elements.
You can make the window scrollTo x position 0 and y position the element's offsetTop subtracted by the fixed element's offsetHeight.
JSFiddle with your code: http://jsfiddle.net/3sa2L14k/
.header{
position: fixed;
background-color: green;
width: 100%;
top: 0;
left: 0;
right: 0;
}
html, body{
height: 1000px;
}
#toBeScrolledTo{
position: relative;
top: 500px;
}
<div class="header">
Header
</div>
<div id="toBeScrolledTo">
Text Text Text
</div>
<script>
window.scrollTo(0, document.getElementById('toBeScrolledTo').offsetTop - document.getElementsByClassName('header')[0].offsetHeight);
</script>
Your question is answered in this link.
var node = 'select your element';
var yourHeight = 'height of your fixed header';
// scroll to your element
node.scrollIntoView(true);
// now account for fixed header
var scrolledY = window.scrollY;
if(scrolledY){
window.scroll(0, scrolledY - yourHeight);
}
Also you can use this way:
let item = // what we want to scroll to
let wrapper = // the wrapper we will scroll inside
let count = item.offsetTop - wrapper.scrollTop - xx // xx = any extra distance from top ex. 60
wrapper.scrollBy({top: count, left: 0, behavior: 'smooth'})
Source: https://github.com/iamdustan/smoothscroll/issues/47
A great simple solution (inspired by Sanyam Jain's comment in this link) is to use {block: 'center'} to vertically center the selection like this:
scrollIntoView({block: 'center'})
Edit - I sadly found on MDN page that this features is 'experimental - should not be used in production'. Also, IE doesn't support it (if that's a need).
Try scroll padding. It is not a JavaScript solution (it is a CSS property) but it can be helpful with your problem.
MDN
CSS Tricks
This is 2021, so you could solve this by just using scroll-margin-top. It exists for this express purpose!
I want to detect scroll change into dom element, for example:
<div id="box">
...
</div>
Imagine a box 300x200, and I want to know if someone do a scroll inside it, and how much it is. How can I know?
I prefer only use Javascript and not JQuery, because I'm not loading it and I think it's a lot for too little, but I'm open to other opinions
Here is a working snippet with the current scrolled value:
document.getElementById('scroll-box').onscroll = function() {
console.log(this.scrollTop);
};
#scroll-box {
background-image: url(http://placekitten.com/g/300/200);
overflow: scroll;
width: 300px;
height: 200px;
border: 1px solid black;
}
#elements {
overflow: hidden;
height: 1000px;
}
<div id="scroll-box">
<div id="elements"></div>
</div>
I hope it helps.
Copied from below post, and edited for your id:
How to capture scroll event?
<div id="box" onscroll="Onscrollfnction();">
<script>
function Onscrollfnction() {
alert("scroll");
};
</script>
You can use target.addEventListener("scroll", functionName);
I have a parent div "total" in which, there are two children divs namely, "some" and "box". When I click on the link in the div "some" (child-1), the "box"(child-2) must be displayed with width: 100%; and if I click on other parent link, the current "box" (child-2) must be hidden. Also, the paragraph tag must not be hidden when the click button is clicked(as in position: relative).
Here is the fiddle to work this out.
The following lines are the code I tried.
$('.box').hide();
$(".click-btn").on('click', function() {
$('.box').hide();
$(this).parent().parent().children(".box").toggle(1000);
});
check this if it solve your problem jsfiddle
i added this
$('.box').hide();
$(".click-btn").on('click', function() {
$('.box').hide();
$(this).parent().parent().children(".box").toggle(1000);
});
add the css
.box {
width: 100%;
float: left;
position: absolute;
height: 200px;
background: orange;
top: 70px;
left: 0px;
clear: both;
}
My solution would be putting each .box outside of the floating .single and reference them with an data attribute.
<div class="total">
<div class="single">
<div class="some"><a class="click-btn" href="#" data-box="box1">click</a></div>
</div>
<div class="clearfix"></div>
<div class="box" data-id="box1">Box 1</div>
</div>
And the box css
.box {
width: 100%;
height: 200px;
background: orange;
display:none;
}
If you set the display none in css you don't have to use $('.box').hide(); on dom ready.
Since you hide all .box elements on click, the toggle function won't work. To toggle the box if you click the active link again you can use the .not() function of jQuery which will take out an element of the collection.
Alltogether the JS would look like:
$(".click-btn").on('click', function(e) {
e.preventDefault();
var boxId = $(this).data('box');
var activeBox = $('[data-id="'+boxId+'"]');
$('.box').not(activeBox).hide();
activeBox.toggle(1000);
});
I'm using e.preventDefault(); what will prevent the default browser action for clicking a link.
Here is a fiddle: http://jsfiddle.net/mrvtwpjp/40/
I have JavaScript that makes it so that when you click on a string of text it creates a div that slides down and expands an area bellow it to show more information. I want to be able to have a link on a different page of my website that when clicked takes you to the page with the string of text ALREADY clicked on and expanded. How would I do this?
JSFidldle: http://jsfiddle.net/hr07tn16/2/
JavaScript:
$('.moreInfo').on('click', function(){
var target = $(this).data('target');
$('.expandable').not('.' + target).slideUp(500, function(){
$('.' + target).slideDown(500, function(){
});
});
});
HTML
<div class="moreInfo" data-target="red">More Info</div>
<div class="moreInfo" data-target="green">More Info</div>
<div class="expandable red" style="display: none;">RED</div>
<div class="expandable green" style="display: none;">GREEN</div>
CSS:
.expandable {
width: 997px;
height: 300px;
}
.red {
color: white;
position: relative;
top: 380px;
border: 1px solid rgba(0,0,0,.1);
}
.green {
color: white;
position: relative;
top: 380px;
border: 1px solid rgba(0,0,0,.1);
}
You could add a hash to the link on your other page and, if the hash is present trigger the click. You could also use a flag to use the animation or not depending on whether is an automatic trigger or a manual one.
One thing you can try is redirecting to that page with a POST variable set indicating the element you would like expanded. Then on the page being directed to, have an onLoad() function which checks if the variable is set and then does what you want if it is.
onLoad()