Jquery scroll to offset target div on page load - javascript

I'm trying to scroll to the div that is in the URL. It could be one of 21 IDs like:
url.com/test#lite1
url.com/test#lite2
url.com/test#lite3
I need this to happen on page load (user is coming from an ebook and should see the exact item they clicked on).
Here is the code I currently have:
$(document).ready(function(){
$('a[href^="#"]').load(function() {
e.preventDefault();
var target = this.hash;
var $target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top -150
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});
</script>
It doesn't work and I think it's because of this part (I have no idea what I'm doing here):
$('a[href^="#"]').load(function() {
I also want it to be in the center of the page (not at the top cut off like browsers do when scrolling to divs). Please let me know if this is correct:
$target.offset().top -150
Thanks so much in advance!

window.location.hash contains the current hash in the URL so use that. As the hash is already in the URL(as you said that they come to page by clicking on link with hash) so you don't need to add it manually.
Try using this :
$(document).ready(function(){
$('html,body').animate({
scrollTop: $(window.location.hash).offset().top-150
}, 900, 'swing');
});
Using wordpress, it seems the $ needs to be replaced by jQuery so it comes out to:
jQuery(document).ready(function(){
jQuery('html,body').animate({
scrollTop: jQuery(window.location.hash).offset().top-150
}, 900, 'swing');
});

As an alternative, you could try using the following jQuery plugins. I've used them on multiple projects. They're customizable and provide nice, smooth animation:
scrollTo (download, documentation) allows you to scroll to a specific element on the page. Basic usage: $(element).scrollTo(target);
localScroll (download, documentation) requires scrollTo as a dependency, and handles anchors for you. You can apply it to specific set of links by selecting their container: $('#link-container').localScroll();, or you can activate it globally: $.localScroll();

Related

jQuery scroll to section on another page

I have a website which uses jQuery to scroll between a few sections (in page1.html). Now, I added another page to the website (page2.html).
I would like the links in the header of page2.html to link back to the corresponding section in page1.html.
In page2.html I wrote:
<li>Home</li>
This links back to page1.html#splash. But on page1, the site does not scroll to the respective section.
My JavaScript is:
$(document).ready(function(){
$('a[href=\\#]').click(function(e){
e.preventDefault();
$('nav').removeClass('visible');
$('html,body').stop().animate({scrollTop: $('.'+$(this).data('scrollto')).offset().top-65 }, 700, 'easeInOutExpo', function(){});
});
What I already tried:
I attempted to add the following code, found elsewhere, to page1.html:
<script>
$(document).ready(function(){
// Add smooth scrolling to all links
$("a").on('click', function(event) {
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
}
});
});
</script>
But there is no scrolling to the right section and the console put out the following error: index.html:19 Uncaught ReferenceError: $ is not defined
Frankly, I am stuck at this point due to lack of expertise in this field.
How do I manage that the site actually scrolls to the right section when coming from another page?
Once you have left the page, the JavaScript from the previous page can't control it. So, you'll need to use jQuery to handle it on the new page when it loads. Place this code on page1.html, changing the comment to the scroll command:
$(document).ready(function() {
if (window.location.href.includes('#splash')) {
let animationTime = 100;
$('html, body').animate({
scrollTop: $('.splash').offset().top
}, animationTime);
}
});
Uncaught ReferenceError: $ is not defined
gives this type of error when your page doesn't get the JQuery

jQuery smooth scroll for WordPress not working

I've been trying to make my links work on my theme I am creating but I have no knowledge of jQuery for the smooth scrolling. In my theme I used the following jQuery I saw was working online:
$(document).ready(function(){
$('a[href^="#"]').on('click',function (e) {
e.preventDefault();
var target = this.hash;
var $target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});
In my dynamic WordPress menu I set the urls to #values, #about, #contact etc. and the links to it on the specific places on the page I used <span id="values"></span>, <span id="about"></span> and <span id="contact"></span>
It works, but the smooth scrolling doesn't work. I see that anchors are used for smooth scrolling online in the parts of the page but I want to be able to target the id of the span tags. I tried to make an anchor tag to test if it works but it still doesn't.
How do I get this to work?
Miro replied in the comments the correct answer - "In Wordpress you need to add external jquery or equate the dollar sign to the one already in use. Try adding $ = jQuery; above all your scroll code. If that doesn't work replace all $ with jQuery."

Scroll to the element id that is supposed to be loaded via Ajax (Infinite Scroll)

So, I have two pages, notifications and topic. Topic page has comments, every comment has an unique id. When user presses on the comment link in the notifications page it takes him to the topic page that is scrolled to the exact comment user pressed on. The link after that looks something like topic/titleoftopic#comment_627. It worked pretty good, but now, when I have added infinite scroll and started showing only first few comments (rest of it is loaded on the scroll to bottom) it won't scroll to the comment and I receive an error in the console Uncaught TypeError: Cannot read property 'top' of undefined, obviously this is because the comment is not loaded yet. Is there any way to make it work? I have an idea - start scrolling to the bottom until it finds the exact comment, but not sure how to implement this. Here is my code on how do I make it scroll:
//Scroll to the comment from notifications
$(document).ready(function() {
$('html, body').hide();
if (window.location.hash) {
$('html, body').scrollTop(0).show();
$('html, body').animate({
scrollTop: $(window.location.hash).offset().top
}, 800);
} else {
$('html, body').show();
}
});
Thanks everyone for any advice or suggestion!
For dynamically added items you have to find that id from whole document.
$(document).ready(function () {
$('html, body').hide();
if (window.location.hash) {
$('html, body').scrollTop(0).show();
$('html, body').animate({
scrollTop: $(document).find(window.location.hash).offset().top
}, 800);
} else {
$('html, body').show();
}
});

jQuery scroll to anchor with variable speed

I have a very basic HTML site with a few anchor tags. On click each anchor leads to the other, using a little bit of smooth scroll with this function:
$(document).ready(function(){
$('a[href^="#"]').on('click',function (e) {
e.preventDefault(); var target = this.hash; var $target = $(target);
$('html, body').stop().animate(
{
'scrollTop': $target.offset().top - 300
},
900,
'swing',
function () {
window.location.hash = target - 300 ;
}
);
});
});
The gaps between the anchors will be quite big and I am trying to figure out a way to get the speed to vary - when clicked on an anchor, to start slower, than speed up, when close to the next anchor to slow down again before it stops.
Could not find any JQuery docs on it, does someone has a suggestion?
FIDDLE: https://jsfiddle.net/koteva/ovf9ywb3/
I believe you would want to use an easing function to handle this. By default, jQuery only handles swing easing, which you have already passed into your animate function. However, you can include additional easing functions with a plugin.
George Smith has a lightweight js plugin for download that may help you, called jquery.easing.1.3.js. I think easeInOutQuart sounds like the closest thing to what you are looking for
Here is a demo fiddle
By including jQuery UI (after jQuery) you will be able to use the easings listed here
Your code should look like:
$('html, body').stop().animate(
{
'scrollTop': $target.offset().top - 300
},
900,
'easeInOutCubic',
function () {
window.location.hash = target - 300 ;
}
);

Best method for Auto scrolling to previous place without jquery (PHP and Javascript)

I have done my homework and seen allot of different methods of accomplishing this. But what is the most effective way that is cross-browser error "proof".
Some things I have tried...
body.onload = function(){
window.scrollTo(0,<?php echo $_POST['scrolltext'];?>);
};
With scrolltext coming from a hidden input filled by a document.getElementById('scrolltext').value = window.pageYOffset || docElem.scrollTop || body.scrollTop
Also...
$(document).ready(function() {
$('#<?php echo $_POST['site']; ?>').scrollIntoView(true);
});
with many otherr forms of this, where the posted site being a ID linked by php on the page based on the button pushed. But I found Jquery's methods very unreliable and Ipad's especially seem to hate everything to do with jquery(especially panels)...
So i figured the best way to do it would be javascript? some PHP methods I cant really think of?
Thanks in advance.
Scroll to the top of a document
$("html, body").animate({ scrollTop: $(document).height() }, 300);
Scroll to the top of an element
$('html, body').animate({ scrollTop: $("#itemid").offset().top }, 800);
Scroll to the top of a specified element
var itemid = $("#daitemid2").val(); //method 1
var itemid = $(this).attr("itemid"); //method 2
$('html, body').animate({ scrollTop: $("#itemid"+itemid+").offset().top }, 800);

Categories

Resources