I am trying to learn jQuery and I'm having a mental blank at the moment. The following code scrolls my page to the top with a smooth transition, but I would like this smooth transition to work for all anchor/ID links on my site (it's only a one pager).
$(document).ready(function() {
$('a[href="#the-top"]').click(function (e) {
$("html, body").animate({ scrollTop: $('#the-top').offset().top }, 1000);
return false;
});
});
How can I change my code to achieve this?
jQuery(function($) {
$('a[href^=#]').bind('click', function (evt) {
var $what = $('#' + $(this).attr('href').split('#')[1]);
$('html, body').stop().animate({ scrollTop: $what.offset().top }, 1000);
evt.preventDefault();
});
});
Changes suggested in this code:
Change global $ object to jQuery
Just jQuery(fn) as document.ready(fn)
Closure: use jQuery as $ inside that function
Prevent default event from anchor instead of return false (source: http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/)
Use of $what asking for the #something part of anchor href, in order to prevent misbehaviors in IE (because if you have href="#some" sometimes it become href="http://yoursite.com/yourcurrentpage/#some instead)
All of these are kind of optional. You get the idea. Feel free to change.
DEMO AT: http://jsfiddle.net/Nm3cT/
Take a look at Chris Coyier's smooth Scrolling script. It does exactly that and needs no further configuration. Plus, it updates the address on the browser.
Related
I'm trying to use jQuery scrollTop animation to scroll to a specific target. But for some reason, no matter what easing i use, it starts very slow and then speeds up. It just looks very odd and ugly.
Additionally, it stops the id "Beauty-target" like planned when it is on top of the screen, but stops the "Fashion-target" , "Artists-target" and "Actors-target" when they are on the bottom of the screen.
To scroll you need to click the "Beauty", "Fashion", "Artists" or "Actors" svg under der "Preise" banner. I used Wordpress and the twenty-tweny theme. The problem occurs on the following website: https:anna-samlidou.com/example
To scroll, I use the same function i use all the time:
jQuery(document).ready(function(){
jQuery('a[href^="#"]').on('click',function (e) {
e.preventDefault();
console.log("scroll function started");
var target = this.hash;
var $target = jQuery(target);
jQuery('html, body').animate({
'scrollTop': $target.offset().top
}, 1000, 'swing', function () {
console.log("scroll function finished");
window.location.hash = target;
});
});
});
After some investigation i found out that when i remove the
<?php wp_head(); ?>
from the header.php file, the scrolling works as intended. Also the Website looks very broke.
So i used
<?php wp_deregister_script('jquery'); ?>
to remove just the jQuery. Which didn't have the same effect, the scrolling was still buggy.
I also installed the Plug In "Remove jQuery Migrate", which didn't help as well.
So which part of the wp_head() function causes this issue? Or how else can i fix this scrolling-issue?
Best regards and thanks a lot in advance,
AlphaLeviathan
HOW TO FIX: Thank you #SaschaM78
To fix the problem of the odd animation, i added jQuery with noConflict() like this:
<?php wp_head(); ?>
<script type="text/javascript" src="https://anna-samlidou.com/wp-content/uploads/jquery/jquery-3.5.1.min.js"></script>
<script>
var j = jQuery.noConflict();
j(document).ready(function(){
j('a[href^="#"]').on('click',function (e) {
e.preventDefault();
console.log("scroll function started");
var target = this.hash;
var $target = j(target);
j('html, body').animate({
'scrollTop': $target.offset().top
}, 1000, 'easeInOutQuad', function () {
console.log("scroll function finished");
window.location.hash = target;
});
});
});
</script>
In Safari and Firefox this worked fine, but to make it work in Google Chrome i had to unset the scroll-behavior of the html, because it conflicted with the animation.
html{scroll-behavior:unset;}
The Problem of scrolling to the wrong position was caused by not properly clearing float and with this, messing up the structure. Adding the following html code after every section solved the problem:
<br style="clear:both;>
All Credits go to #SaschaM78
I would recommend to add your JQuery 3.5.1 version with var j = jQuery.noConflict(); and calling j('a[href^="#"]').on('click', ...); instead. The Wordpress JQuery version is really old (1.12) and this will definitely cause incompatibilities and issues when mixed.
The issue with the scrolling to the wrong position is caused by not properly clearing floated elements in your <div class="preise-kategorien-abschnitt">...</div> containers. The first element has no floated elements in the DOM in front of it and its position is therefor calculated correctly. All headings following this one will have an incorrect position due to the float:left; on the <div class="preise-kategorien-abschnitt-preise-karte ...">...</div> which are not cleared.
A cleared block would look like this (without showing the inner contains of the three columns:
<div class="preise-kategorien-abschnitt">
<h2 class="preise-kategorien-abschnitt-titel" id="Actors-Target">Actors Shootings</h2>
<div class="preise-kategorien-abschnitt-preise-container">
<div class="preise-kategorien-abschnitt-preise-karte preis-karte-links">...</div>
<div class="preise-kategorien-abschnitt-preise-karte preis-karte-mitte">...</div>
<div class="preise-kategorien-abschnitt-preise-karte preis-karte-rechts">...</div>
</div>
<br style="clear:both;>
</div>
Hi I'm developing a site and I'd like to make people scroll to an href id without showing it in the navigation bar of their browsers. If is it possible I'd like to do it with
Am I able to do it? Thanks
Example: index.html#id
How I want it: index.html
You can use Element.scrollIntoView to achieve this. The javascript needed is
var scrollToElement = function(id){
document.getElementById(id).scrollIntoView();
}
If you pass in {behaviour: 'smooth'} to the function you get smooth scrolling which is really slick.
Check https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView for further documentation on this function
pure JS version
Using window.scrollTo(x,y) you can move the viewport:
var elem = document.getElementById("your element id");
window.scrollTo(0, elem.offsetTop);
jQuery Version
If you are already using jQuery, you can use .animate() for a smooth scroll transition to the element.
Here is an example:
$("#button").click(function() {
$('html, body').animate({
scrollTop: $("#elementtoScrollToID").offset().top
}, 2000);
});
See also here
Got an issue with a navbar I'm creating for a WordPress site. Some of the links are meant to scroll down to different places on the homepage and some are outside links to other places on the site. Something like this:
<div class="main-navigation">
<ul>
<li class="link1">Link 1
<li class="link2">Link 2
</ul>
</div>
Basic stuff.
So if I add the following Javascript in the footer....
jQuery(document).ready(function() {
jQuery('.main-navigation a' ).click(function(){
jQuery.scrollTo( this.hash, 1000, { easing:'swing' });
return false;
});
Link 2 will scroll down but since Link 1 isn't supposed to scroll, if you click on it, nothing happens like it's a null link.
I thought I could change the reference to something like
jQuery('.main-navigation a.link2' ).click(function(){
So only link 2 does the scrolling, but that just makes it jump to the page like an old anchor tag trick in the 1990's.
Tried a few variations of the same idea, and nothing clicked. Anyone know what the right code would be to target just the buttons that need to have the scrolling?
Building from itsgoingdown's answer. The animation is ignored because the default link event still fires. If you pass the event and also prevent the default, you'll be set. See below.
$(document).ready(function() {
$('.main-navigation a[href^="#"]' ).click(function(event) {
// Prevent default link action
event.preventDefault();
// Grab location to send to
var href = $(this).attr('href');
// Scroll the page, animated
$('html, body').animate({
scrollTop: $(href).offset().top
}, 700);
});
});
Here is a live JSFiddle to show as well.
https://jsfiddle.net/y3nutj22/5/
Thanks to the both of you. I finally figured it out and in a sense, you're both right. However, neither of your codes produced the scrollTo effect. While '.main-navigation a[href^="#"]' was partially correct, my issue....and I finally realized it this morning....was I hard coded in the URL's in WordPress' menu feature as a complete URL. So just using '#' wouldn't work. Also, since it's WP, I can't use $'s in the code, Have ot use jQuery, of course.
This is the code that did the trick.
jQuery(document).ready(function() {
jQuery('.main-navigation a[href^="http://path.to.url/#"]' ).click(function(){
jQuery.scrollTo( this.hash, 1000, { easing:'swing' });
return false;
});
with path.to.url representing the actual URL, of course.
Thanks again!
I am not sure how to mimic this (http://ironsummitmedia.github.io/startbootstrap-agency/)
website's easing. What I mean by easing is when I click on the websites navigation tabs, I would slide to the appropriate portion of the section/div. I think it uses jQuery UI easing (http://api.jqueryui.com/easings/). I'm not sure where to start as I just start learning jQuery and front end development.
I think to get started, I would do
$("#nav-pill").onclick(function() {
// easing methods?
})
You have syntax error in your jQuery
$("#nav-pill").on('click', function() { });
And the following code makes you achieve the smooth scrolling effect while
jQuery code:
$("#nav-pill").on('click', function() {
var mode="easeInOutCirc"; // or select the mode from jQuery easings
$('html, body').animate({
scrollTop: $("#myDiv").offset().top
}, 2000, mode);
});
It should work just fine for your case.
For this effect you can use animate
Example:
$("#nav-pill").click(function(){
$('html, body').stop().animate({
scrollTop: $("#container").offset().top
}, 1500,'easeInOutExpo');
});
Or you can use ScrollTo plugin (http://demos.flesler.com/jquery/scrollTo/)
I managed to create scroll to effect on a testing web-page. At first I had
(function($) {
$(document).ready(function() {
$('html, body').animate({
'scrollTop': $('#static').offset().top
}, 1500);
});
})(jQuery);
which smoothly went on every page open to that anchor "static". Because header is big on page. so beside index page every navigation link would scroll past header down to anchor. That works perfect. But then I decided to make some submenu items. and they can't work because I use
<script type="text/javascript">
$(document).ready(function(e){
var str= location.hash;
var n=str.replace("_temp","");
$('html,body').animate({scrollTop:$(n).offset().top}, 500);
});
for that. This script can scroll down to anchor named "#something" on different page even and still smoothly scroll down. I found both scripts searching on Stack Overflow.
Problem is that when I use both of these, only 1st one works. They are similar so that's the problem. Is there any way to make them both work. If there is anchor "static" use first, if not use second?
How about
$(document).ready(function(e){
var str= location.hash;
var n=str.replace("_temp","");
if(n != "static") {
$('html,body').animate({scrollTop:$(n).offset().top}, 500);
} else {
$('html, body').animate({ 'scrollTop': $('#static').offset().top}, 1500);
}
});