scroll to div ajax/javascript - javascript

Ok, for the life of me, I can't get this to work. I've searched for examples and I found tons. But none of them seem to work for me.
Question is simple, I have a div that loads content from the database.
I need to scroll to the bottom of the div when the page is loaded.
here's an example.
<body>
<div id="container">
<div id="messagewindow">
<?php
foreach($results as $r){
//content loop..
}
?>
<div id="scrolltome"></div>
</div>
</div>
</body>
I added the div id scrolltome in hopes it would work.
Thank you in advance!

Try using window.scrollTo(0, $(element).offset().top)
For example: https://jsfiddle.net/88uhpkx0/

Try below function
function scrollToElement(selector, time, verticalOffset) {
time = typeof(time) != 'undefined' ? time : 500;
verticalOffset = typeof(verticalOffset) != 'undefined' ? verticalOffset : 0;
element = $(selector);
offset = element.offset();
offsetTop = offset.top + verticalOffset;
$('html, body').animate({
scrollTop: offsetTop
}, time);}
Call this function by
scrollToElement('#scrolltome`, 750, -50); . Here 750 time set for animate and -50 is elements offset value. You can change these values according to your needs

Simply pass the top offset distance of #scrolltome div to body scrollTop on window load like this:-
$(window).load(function(e) {
var distance = $('#scrolltome').offset().top
$('html,body').animate({scrollTop:distance},1500);
});

First of all, your scrolltome div is missing >.
And you could try the following to make the scroll.
$('#messagewindow').animate({
scrollTop: divHeight
}, 1000);

Related

How to know what part of HTML is the user on

so I want to know how I can get what section or part of my html I’m currently on. An example
So how do I know if a user has already scrolled down over part 2 using JavaScript
Or if they’re currently at part 1
<html>
<head>
</head>
<body>
<section class=“part 1”>
</section>
<section class= “part2>
</section>
</body>
</html>
The following codes will give you a little idea about how to handle this situation. Essentially you are going to want to get the scrollbar position which you can do using:
document.documentElement.scrollTop
You also want to get a range where the element you are looking for resides, in our case, it is .part1 and .part2. We can get that range by using offsetTop as the beginning of the limit and offsetTop + clientHeight to determine the end.
You are going to have to keep track of the window scroll event.
The following example is generic:
$(window).scroll(function(e) {
if (document.documentElement.scrollTop > 0
&& document.documentElement.scrollTop < $('.part2').offset().top ) {
$('div').html("At part1")
} else {
$('div').html("At part2")
}
});
JSFiddle
Likewise, if you want a little bit of modularity:
$(window).scroll(function(e) {
let watchList = ['part1', 'part2', 'part3'];
let scrollTop = document.documentElement.scrollTop;
for (var classname of watchList) {
let el = document.getElementsByClassName(classname)[0];
if (scrollTop > el.offsetTop &&
scrollTop < el.offsetTop + el.clientHeight) {
$('div').html("At <strong>"+classname+"</strong>");
}
}
});
JSFiddle
The possibilities are limitless to continue and make this more useful, but I'll leave that up to you.
you can use is[":focus"] function to find which div has focus currently.
if($(".part1").is(":focus"))
{
//you code
}
else if($(".part2").is(":focus"))
{
//you code
}
you can use mouseenter function it fires when the mouse goes into that div for the first time.
$(".part1").on('mouseenter', function(){
//your command
});
you can use mouseover function to find where is mouse right now. it fires when mouse moves inside that div.
$(".part1").on('mouseover', function(){
//your command
});
You can use javascripts offsetTop functionality. This is a parameter that returns how far down from the top a div is in the number of pixels.
It can also return how far down the user has scrolled when called on the window object itself. Then it's just a matter of math. See if the user has scolled down far enough to be past the div in reference.
For example:
var part1DivOffset = document.getElementsByClassName("part 1")[0].offsetTop;
var part2DivOffset = document.getElementsByClassName("part2")[0].offsetTop;
var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
This code will get you 3 variables. The first 2 lines save the offsetTop of the div's. While the third line detects how far down the user has scrolled. Then you can do math with the variables:
if(scrollTop >= part1DivOffset){
//we are past part1
}
if(scrollTop >= part2DivOffset){
//We are past part 2
}
if(scrollTop >= part1DivOffset && scrollTop < part2DivOffset){
//We are past part 1 but not past part 2
}

jQuery script not being refreshed

I have been wondering why the following jquery script is not beeing run every 5 seconds.
The correct height of the DIV ".leistung" (there are multiple ".leistung" div's with different lenght of text thats why every block has to have the same height) is beeing applied on load. But the function is not beeing run every five seconds for some reason.
Does anyone know why this is happening?
<section class="leistung">
<div class="leistung-image">
<img src="http://www.myfico.com/Images/sample_overlay.gif"/>
<div class="leistung-image-titel">
<span>Title</span>
</div>
</div>
<div class="leistung-teaser">
Some more text
</div>
</section>
<script>
var maxHeight = 0;
window.setInterval(function(){
$('.leistung').each(function(){
var thisH = $(this).height();
if (thisH > maxHeight) { maxHeight = thisH; }
});
$('.leistung').height(maxHeight);
}, 5000);
</script>
Since the OP is looping using each and since there are no any other elements with the class name leistung, I don't think he wants only to take the <section class="leistung"> element. So I assume that he want to select all the elements with name starting leistung.
<script>
var maxHeight = 0;
window.setInterval(function(){
//added ^ selector here
$("[class^=leistung]").each(function(){
var thisH = $(this).height();
if (thisH > maxHeight) { maxHeight = thisH; }
console.log(maxHeight);
});
// and here
$("[class^=leistung]").height(maxHeight);
}, 1000);
</script>
I found my problem. I only run the fuction every 5 seconds. But when the height has been set once it will just fetch the set height again and set it again...
I will have to come up with something else to solve my problem

Problems with scrollTop animation

I have three divs, each one with some hidden content. When you click on a div, its content is being displayed by sliding down. And at the same time, I'm using scrollTop to make the browser scroll to the top of the block thats been clicked on. The HTML looks like this:
<div class="blocks block1"></div>
<div class="content block1_content"></div>
<div class="blocks block2"></div>
<div class="content block2_content"></div>
<div class="blocks block3"></div>
<div class="content block3_content"></div>
However, im having problems with parts of the scrollTop animation. Here is the JS:
$('.blocks').on("click", function() {
if (!$(this).hasClass('expanded')) {
collapseExpandedFunction();
$('html, body').animate({
scrollTop: $(this).offset().top
}, 500);
$(this).addClass('expanded');
$(this).next().slideDown();
} else if ($(this).hasClass('expanded')) {
collapseExpandedFunction();
}
});
collapseExpandedFunction = function() {
$('.blocks.expanded').removeClass('expanded');
$('.content').slideUp();
};
I made an jsfiddle to easier demonstrate the problem: https://jsfiddle.net/ss53ckyk/3/
Explaination:
If you start toggle the green block and then toggle the red or blue, it's all good. The greens content is being hidden, while the red/blue is displayed and scrolled to the top of the block.
The problem is if you start from the top and moving down. If you first toggle the red one and then either blue or green, the browser won't scroll down correctly.
Another thing i'd like is to make the slideDown happen after the scrollTop animation is done.
Hopefully someone can help me out!
EDIT:
There should only be one blocks content visible at a time. For example, if you click the red once and then the blue, the content of the red should slide up, while the blue is showing.
The asynchronous nature of javascript is causing your issues; namely .slidUp() function. When this event is triggered, it fires an asynchronous event, which is non-blocking to the rest of the function. Therefore, the animate top will take a snapshot of the DOM at a particular moment in time while the .slidUp() function is actioning. Replacing the .slidUp() and .slidDown() with .show() and .hide() to resolve this, but this doesn't provide the responsiveness you require. One thought would be to capture the offsets of each previous content div and use that in the scrollTop function.
EDIT :
Based on the edit, you need to make few adjustments in your code which calculates the scrolltop position based on scrollposition and adding margin based on the corresponding .content div
$(document).ready(function() {
var addMargin = false;
$('.blocks').on("click", function() {
if (!$(this).hasClass('expanded')) {
collapseExpandedFunction();
var doc = document.documentElement;
var ele = this;
var nextEle = $(ele).next();
$(this).addClass('expanded');
var margin = 0;
var scrollTo = 0;
if($(ele).hasClass('expanded'))
{
if(addMargin)
margin = $(nextEle).css('height').replace('px','');
scrollTo = $(ele).offset().top - margin;
}
if(doc.scrollTop != 0 && doc.scrollTop > scrollTo && addMargin)
{
console.log(margin);
scrollTo = scrollTo + 200;
}
$('html, body').animate({
scrollTop: scrollTo
}, 500, function()
{
$(ele).next().slideDown();
});
} else if ($(this).hasClass('expanded')) {
collapseExpandedFunction();
}
});
collapseExpandedFunction = function()
{
$('.blocks.expanded').removeClass('expanded');
$('.content').slideUp();
addMargin = false;
};
window.onscroll = function (e) {
addMargin = true;
}
});
Here's the working code : https://jsfiddle.net/ss53ckyk/13/

JQuery Add Class when bottom of div reaches top

I am trying to add a class when the bottom of a div reaches the top of the window, but am not sure of how to do it.
I have managed to add the class when the top of the div gets to the top of the window, but am not having much luck with the bottom of the div.
Code I am using:
$(document).ready(function() {
var menuLinksTop = $('.container').offset().top;
var menuLinks = function(){
var scrollTop = $(window).scrollTop();
if (scrollTop > menuLinksTop) {
$('header').addClass('black-links');
} else {
$('header').removeClass('black-links');
}
};
menuLinks();
$(window).scroll(function() {
menuLinks();
});
Any help is appreciated.
You should use javascript's getBoundingClientRect() method, watch $(window).scroll event, and look at element's rectangle, its bottom value will give you what you need (if it's negative, your element is all the way up)
$(window).scroll(function() {
console.log($("div.watch")[0].getBoundingClientRect());
if ($("div.watch")[0].getBoundingClientRect().bottom < 0)
alert ("i'm out :3");
});
see jsFiddle http://jsfiddle.net/ja5nnbwr/2/
Add the height of the div. Assuming it is the .container :
var menuLinksTop = $('.container').offset().top + $('.container').height();

Update scroll position on resize of window

I'm currently using a combination of smooth scroll and IDs/anchor tags to scroll to content on my site. The code below is getting the ID of the next 'section' in the DOM, and adding it's ID as the 'view next section' href, so once it's clicked, it'll scroll to the top of that div. Then, it iterates through, updating the href with the next ID each time etc until the last section is seen and it scrolls back to the top. Pretty straightforward.
The only problem is that the 'sections' are fullscreen images, so as it's scrolling to the top of the next section, if you resize the browser, the top position of that section (where we scrolled to) has moved, and means the position is lost.
I've created a JSFiddle. You can see this happening after you click the arrow to visit the next section then resize the window: http://jsfiddle.net/WFQ9t/3/
I'm wanting to keep this top position fixed at all times so even if you resize the browser, the scroll position is updated to reflect this.
Thanks in advance,
R
var firstSectionID = $('body .each-section').eq(1).attr('id');
$('.next-section').attr('href', '#' + firstSectionID);
var i = 1;
$('.next-section').click(function() {
var nextSectionID = $('body .each-section').eq(i).attr('id');
i++;
$('.next-section').attr('href', '#' + nextSectionID);
var numberOfSections = $('body .each-section').length;
var lastSectionID = $('body .each-section').eq(numberOfSections).attr('id');
if ($('.next-section').attr('href') == '#' + lastSectionID ) {
$('.next-section').attr('href', '#introduction');
i = 1;
}
});
Ok, Please check out this fiddle: http://jsfiddle.net/WFQ9t/9/
The few things I did were:
Made some global variables to handle the screen number (which screen you're on and also the initial window height. You will use this when the screen loads and also when you click on the .next-session arrow.
var initWinHeight = $(window).height();
var numSection = 0;
Then I tossed those variables into your resizeContent() function
resizeContent(initWinHeight, numSection)
so that it will work on load and resize
I made the body move around where it needs to, to accomodate for the movement of the divs (I still don't understand what divs are moving when the regular animation happens).
$('body').css({
top: (((windowHeight - initWinHeight)*numSection)*-1) + "px"
});
Then in your click function, I add 1 to the section number, reset the initial window height and then also reset the body to top:0. The normal animation you have already puts the next section at the top of the page.
numSection++;
initWinHeight = $(window).height();
$('body').css({top:"0px"}, 1000);
Finally, I reset the numSections counter when you reach the last page (You might have to make this 0 instead of 1)
numSection = 0;
The fiddle has all of this in the correct places, these are just the steps I took to change the code.
Here is a solution that i found, but I dont use anchor links at this point, i use classes
Here is my HTML code:
<section class="section">
Section 1
</section>
<section class="section">
Section 2
</section>
<section class="section">
Section 3
</section>
<section class="section">
Section 4
</section>
And here is my jQuery/Javascript code,
I actually used a preety simple way:
$('.section').first().addClass('active');
/* handle the mousewheel event together with
DOMMouseScroll to work on cross browser */
$(document).on('mousewheel DOMMouseScroll', function (e) {
e.preventDefault();//prevent the default mousewheel scrolling
var active = $('.section.active');
//get the delta to determine the mousewheel scrol UP and DOWN
var delta = e.originalEvent.detail < 0 || e.originalEvent.wheelDelta > 0 ? 1 : -1;
//if the delta value is negative, the user is scrolling down
if (delta < 0) {
next = active.next();
//check if the next section exist and animate the anchoring
if (next.hasClass('section')) {
var timer = setTimeout(function () {
$('body, html').animate({
scrollTop: next.offset().top
}, 800);
next.addClass('active')
.siblings().removeClass('active');
clearTimeout(timer);
}, 200);
}
} else {
prev = active.prev();
if (prev.length) {
var timer = setTimeout(function () {
$('body, html').animate({
scrollTop: prev.offset().top
}, 800);
prev.addClass('active')
.siblings().removeClass('active');
clearTimeout(timer);
}, 200);
}
}
});
/*THE SIMPLE SOLUTION*/
$(window).resize(function(){
var active = $('.section.active')
$('body, html').animate({
scrollTop: active.offset().top
}, 10);
});

Categories