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
Related
I'm not a JS developer, and I'm using Bootstrap to build a one-page site with anchor links.
I'm using whatever bits and pieces of JS code I find for some necessary features, such as adding smooth scrolling to the anchor links, with top offset because I'm using a fixed/sticky menu.
While it's a one-page website, I'm using Privacy and Terms as separate pages.
This is the code I'm using for the anchor links on the homepage. I think it's a mix of JS and jQuery. It works well and the way I want.
$('.navbar a, .smooth-scroll-contact').on('click', function(event) {
/* Make sure this.hash has a value before overriding default behavior */
if (this.hash !== "") {
/* Prevent default anchor click behavior */
event.preventDefault();
/* Store hash */
var hash = this.hash;
/* Using jQuery's animate() method to add smooth page scroll. */
$('html, body').animate({
scrollTop: $(hash).offset().top - 70
}, 800, function(){
/* Add hash (#) to URL when done scrolling (default click behavior). */
if (history.pushState) {
history.pushState(null, null, hash);
}
else {
window.location.hash = hash;
}
});
} // End if
});
While it works fine on the homepage, it prevents the menu links to open on the Privacy and Terms pages. It doesn't do anything when clicking the menu links there. It doesn't go to the homepage or any of the anchor links there.
This is the error that appears in the Console when clicking on the menu links, while on the Privacy or Terms page:
Uncaught TypeError: Cannot read property 'top' of undefined
at HTMLAnchorElement.<anonymous> (custom.js:39)
at HTMLAnchorElement.dispatch (jquery-3.4.1.min.js:2)
at HTMLAnchorElement.v.handle (jquery-3.4.1.min.js:2)
The 39th line is scrollTop: $(hash).offset().top - 70.
I searched for this error and tried to apply some fixes that I found, but they didn't work for me or I didn't know how to implement them correctly for this particular code.
Additional notes:
If I remove the smooth scrolling code, the problem is solved;
The custom.js file, where the code is found, is loaded before </body>;
jQuery is the first script loaded.
If you need more info, let me know.
I finally managed to find a solution after more research. Here's the new code, in case someone else will encounter the same issue:
$('a[href*="#"]')
// Remove links that don't actually link to anything
.not('[href="#"]')
.not('[href="#0"]')
.on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
// - 70 is the offset/top margin
$('html, body').animate({
scrollTop: $(hash).offset().top - 70
}, 800, function() {
// Add hash (#) to URL when done scrolling (default click behavior), without jumping to hash
if (history.pushState) {
history.pushState(null, null, hash);
} else {
window.location.hash = hash;
}
});
return false;
} // End if
});
event.preventDefault(); seems to have been the problem, so it was removed. return false; was added.
Also, as a bonus, here's a code that allows smooth scrolling with offset to anchor links from external pages:
$(window).on("load", function () {
var urlHash = window.location.href.split("#")[1];
if (urlHash && $('#' + urlHash).length) {
$('html,body').animate({
scrollTop: $('#' + urlHash).offset().top - 70
}, 800);
}
});
I would like to animate my page after the page was redirected using Jquery, the problem with my code is that it only redirects but ignores the animation code, how can I resolve this issue ?
$("#menu a:first-child").click(function() {
window.location.href = "https://www.mysite/blog";
$('html,body').animate({
scrollTop: $("#mainwrapper").offset().top - 70},
'slow');
});
(The animation just scrolls down to an anchor with fluid transition.)
When you redirect, your current script will stop. If you really one to do it, I think there is a way, I DO NOT recommend it, but it will do the job.
Before you redirect to the other page; I assume the new page is still in the same app, not a totally different website), you can set a localStorage variable. Then at be beginning of the JS file of the page you redirect to, check if that localStorage variable you have set in the earlier view is there, if it is, do the animation, then remove that localStorage variable.
// js file of current view
$("#menu a:first-child").click(function() {
localStorage.setItem("animation", true)
window.location.href = "https://www.mysite/blog";
});
// js file of redirected view
if (localStorage.animation && JSON.parse(localStorage.animation)) {
$('html,body').animate({
scrollTop: $("#mainwrapper").offset().top - 70},
'slow', 'linear', function() {
localStorage.removeItem("animation")
}
);
}
This JS creates a Smooth scroll, it works with jQuery 1.11.1, but break with jQuery 1.12.3. Using this with a Wordpress site and would prefer not to load two versions of jQuery.
Can't figure out what to update to make it work again.
<!--smooth scroll to anchors-->
<script>
(function($){
var jump=function(e){
if (e){
e.preventDefault(); //prevent the "normal" behavior which would be a "hard" jump
var mytarget = $(this).attr("href"); //get the target
}else{
var mytarget = location.hash; //sets the target to the anchor part of a URL
}
$('html,body').animate( //perform animated scrolling
{
scrollTop: $(mytarget).offset().top - 100 //get top-position of target-element and set it as scroll target and move down 100px for fixed nav
}, 1000,function(){ //scrolldelay: 2 seconds
location.hash = mytarget; //attach the hash (#jumptarget) to the pageurl
});
}
$('html, body').hide()
$(document).ready(function(){
$('a[href^=#]').bind("click", jump);
if (location.hash){
setTimeout(function(){
$('html, body').scrollTop(0).show()
jump()
}, 0);
}else{
$('html, body').show()
}
});
})(jQuery)
</script>
<!--End smooth scroll-->
jQuery 1.12.x does not like a[href^=#] without quotes around #.
It throws an unrecognized expression error.
Using quotes is recommended always.
$('a[href^="#"]').bind("click", jump);
Also there's an issue with your scrolltop in all jquery versions. $(..).offset() is null. This happens when your href is # or links to a non-existing id. You should also check that it's not an external link, and return, otherwise preventDefault will stop it from working.
See fiddle: https://jsfiddle.net/txau5yLf/
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();
I've built a scrolling homepage for my site that allows users to click a link in the header to scroll down to different sections of the site. I also have external links to new pages that allows users to view different projects.
For whatever reason, it works great, but as soon as I get to one of the project pages, then try to click the home page, or the work links it doesn't work properly. Without creating a second header.php,
how can I make the nav work globally.
<script>
$(document).ready(function(){
$('a.logo, ul.nav a, #mmenu a, a.mobileLogo').bind('click',function(event){
var $anchor = $(this);
href_arr = $anchor.attr('href').split("#");
$('html, body').stop().animate({
scrollTop: $('#'+href_arr[1]).offset().top - 0
}, 500); // it was -70
event.preventDefault();
});
});
});
</script>
My links looks like this...
Link
Work
Any thoughts on how to fix the jQuery so it works on external pages?
It sounds like #home and #work don't exist on your product pages, correct? If that's the case then calling event.preventDefault() will actually prevent the browser from going back to your home page. Try checking if the element exists before preventing the default behavior. If the element doesn't exist, the browser will visit the link normally. This is one way of doing it.
$(document).ready(function(){
$('a.logo, ul.nav a, #mmenu a, a.mobileLogo').bind('click',function(event){
var hash = '#' + $(this).attr('href').split('#')[1];
// check if the element exists on your page
if ($(hash).length) {
// if so, scroll to it and prevent the default behavior
$('html, body').stop().animate({
scrollTop: $(hash).offset().top - 0
}, 500);
event.preventDefault();
}
});
});