So I am trying to use the smooth scrolling animation used in this template:
https://blackrockdigital.github.io/startbootstrap-scrolling-nav/
After adding the js files to my directory, including the basic JQuery files, I've seen the custom .js file that adds the scrolling uses the .class parameter in an anchor tag to detect if clicking it should trigger the smoothscrolling. So I added those to my anchor tags.
Below is the relevant code.
I will include a live preview too.
index.html file
<!-- Navigation section -->
<section class="nav" id="nav">
<div class="container">
<div class="row" style="width: 100%; text-align: center;">
<div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
<a class="js-scroll-trigger btn btn-lg btn-nav" href="#about">About me</a>
</div>
<div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
<a class="js-scroll-trigger btn btn-lg btn-nav" href="#work">My work</a>
</div>
<div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
<a class="js-scroll-trigger btn btn-lg btn-nav" href="#contact">Contact</a>
</div>
</div>
</div>
</section>
Script imports in index.html
<!-- Import js -->
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/jquery-easing/jquery.easing.min.js"></script>
<script src="js/scrolling-nav.js"></script>
Scrolling-nav.js
(function($) {
"use strict"; // Start of use strict
// Smooth scrolling using jQuery easing
$('a.js-scroll-trigger[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$('html, body').animate({
scrollTop: target.offset().top
}, 1000, "easeInOutExpo");
return false;
}
}
});
})(jQuery); // End of use strict
I have nearly no experience with JQuery / JS, so it's hard for me to understand where it might be going wrong.
Here is a live preview of the website with above code in it:
Live preview
Full code:
Github link
If there's any information missing, let me know.
jQuery is missing, and you're using jQuery in your click event...
Add this code in you jquery
$(document).ready(function(){
// Add smooth scrolling to all links
$("a").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
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
Related
I have a page of list of products with a return button to redirect to the homepage.
I want after the redirection to the homepage, a scroll down to a specific div ( in my case, a carousel of products)
I did the scroll, but it works every time the homepage is loaded, but I want the scroll only after clicking to the return button, how can I do that please ?
there is some code :
list of product page :
<a href="{{ path('home_index') }}" class="return-ad">
<img src="{{ app.request.getBaseURL()/arrow-white-left.png">
</a>
homepage :
<div class="row align-items-stretch">
Some code here
</div>
<script>
$(".return-ad").ready(function() {
$('html,body').animate({
scrollTop: $(".align-items-stretch").offset().top},
1000);
});
</script>
Someone can help me please ? I'm new on Jquery and JS
Thanks in advance
To achieve this you could add a fragment to the URL which can be detected when the home page next loads:
In the product page add a # fragment to the URL:
<a href="{{ path('home_index') }}#foo" class="return-ad">
<img src="{{ app.request.getBaseURL()/arrow-white-left.png">
</a>
Then in the home page, detect that fragment and perform the animation:
jQuery($ => {
if (window.location.hash && window.location.hash.substring(1) === 'foo') {
$('html,body').animate({
scrollTop: $(".align-items-stretch").offset().top
}, 1000);
}
});
Also note that the ready() method should be called on the document, not an element in the DOM. I amended the example above to use the short-form of a document.ready event handler
I'm creating a website using Django, and I want the link in the navbar (when clicked) to smoothscroll to the element that I want. This is what I have:
base.html
<li>
<a class="nav-item nav-link" href = '' class='scroll-about'>About</a>
</li>
//unrelated elements
<script>
// scroll into view
document.querySelector('.scroll-about').addEventListener('click', function(e) {
e.preventDefault();
document.querySelector('.about').scrollIntoView({ behavior: 'smooth' });
});
home.html
<div class="about col-12 col-md-6">
<div class="d-flex flex-column align-items-center py-5 text-uppercase">
<h3 class="h3-responsive bg-primary text-center text-white rounded font-weight-bold w-50 px-4 py-2 shadow">About</h3>
<h1 data-easy-reveal = "" class = " h1-reponsive font-weight-bold my-5 ml-3">Our vision is for every business to leave its mark on the digital world</h1>
<h1 data-easy-reveal = "" class = "down h1-reponsive font-weight-bold ml-3">Our vision is to bring them to the next level </h1>
</div>
</div>
The rest of the code works fine, the Django templating is all fine. I just can't seem to get this scroll function to work. I've tried moving the script around the bottom of the html file, and as well as putting it in the head element of the html file. I've also tried using jQuery smooth scroll and it doesn't work either.
the jQuery code I tried (in this case I put scroll-about and about as the respective IDs):
<script>
$("#scroll-about").click(function() {
$([document.documentElement, document.body]).animate({
scrollTop: $("#about").offset().top
}, 2000);
});
</script>
i think that this is what you are trying to do. note that it works just with a tags with href="#something"
$(document).ready(function(){
// Add smooth scrolling to all links
$("a").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
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="height: 100vh; background: #00ced1">
<a id="1" href="#2">Go to Section 2</a>
</div>
<div style="height: 100vh; background: red;">
<a id="2" href="#1">Go to Section 1</a>
</div>
I've found the solution to the issue, adding this allows it to work:
html {
scroll-behavior: smooth;
}
I have a button that when clicked smooth scrolls to an anchor point on the same page. The problem is the script has disabled all hyperlinks on the page. How can I fix this so my extenal hyperlinks work again and the demo button smooth scrolls down the page?
This is the stripped down code where my button resides and the associated javascript:
<body data-spy="scroll" data-offset="80">
<div class="other">
<div class="container">
<div class="col-md-12">
<div class="center-header"><button type="submit" class="btn btn-theme-bg btn-lg">Demo</button></div>
</div>
</div>
</div>
<div id="demo" div class="center-header"></div>
<script>
$(document).on('click', 'a', function(event){
event.preventDefault();
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
});
</script>
</body>
HTML:
<a href="#demo" class="someClassName">
JS:
$(document).on('click', '.someClassName', function(event){
After observing your code I have seen that you are using jQuery to bind click event to the anchor tag. Which will bind click event of all anchor tags. It's causing your anchor tags from click. I suggest to use below code.
$(document).on('click', 'a', function(event){
if ($.attr(this, 'href').indexOf("#") === 0) {
event.preventDefault();
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
}
});
I have jQuery function which toggles a ckeditor text field on click.
My .js file:
$(function() {
$(".add-greeting").on("click", function(event){
$(".panel-body").find('#add-greeting').slideToggle(400,
function(){
$('html, body').animate({
scrollTop: $('#add-greeting').offset().top + $('window').height()
}, 1000);
});
return false;
});
});
My html.erb file:
<div class="form-group", style="padding-bottom:0px;">
<%= link_to "Add greeting", "#", class: "add-greeting btn btn-sm btn-success" %>
</div>
<div id="add-greeting" style="float:left; display:none;">
<%= f.input :offer_greeting, value: offer_settings(#offer, :offer_greeting), as: :ckeditor %>
</div>
The problem is, I have 2 ckeditor fields, so 2 buttons, which now translates into 2 identical jQuery functions, the only difference being the classes and ids I am passing in.
$(function() {
$(".add-observations").on("click", function(event){
$(".panel-body").find('#add-observations').slideToggle(400,
function(){
$('html, body').animate({
scrollTop: $('#add-observations').offset().top + $('window').height()
}, 1000);
});
return false;
});
});
Rendered html:
<div class="form-group", style="padding-bottom:0px;">
<a class="add-greeting btn btn-sm btn-success" href="#">Add greeting</a>
</div>
<div id="add-greeting" style="float: left; display: none;">
<div class="control-group ckeditor optional offer_offer_greeting"><label class="ckeditor optional" for="offer_offer_greeting">Greeting</label>...
How can I avoid repetition?
I would do something like this then you only need to give each link the class of .animate-scroll
Change link to have href to id you want to scroll to and shared class:
<a class="animate-scroll btn btn-sm btn-success" href="#add-greeting">Add greeting</a>
Update jQuery to:
var scrollable = $('html, body');
$(".animate-scroll").on("click", function (event) {
event.preventDefault();
var elem = $($(this).attr('href'));
elem.slideToggle(400,
function () {
scrollable.animate({
scrollTop: elem.offset().top + $(window).height() // no need for quotes around window
}, 1000);
});
});
The problem is, I have 2 ckeditor fields, so 2 buttons, which now translates into 2 identical jQuery functions, the only difference being the classes and ids I am passing in.
In that case, a plugin might help. Try building your repetitive code as a jQuery plugin and reuse it with different ids or classes.
Few references to get you started
How to create a basic plugin
Learning JavaScript Design Patterns
Update: the script and scrollTo animation now work fine. I've uploaded the correct solution.
I'm working on a Bootstrap 3 based website and I'm having some scrollTo issues, this is the code for a navbar (links from the nav lead to three different sections within the page):
HTML:
<header id="page-header" class="container">
<h1> NMS website </h1>
<img src="assets/images/group-logo.png" alt="group logo">
<nav class='navbar navbar-default navbar-fixed-top' role='navigation'>
<h2> Page navigation </h2>
<div class='navbar-header'>
<button type='button' class='navbar-toggle' data-toggle='collapse' data-target='#collapse'>
<span class='sr-only'>Toggle navigation</span>
<span class='icon-bar'></span>
<span class='icon-bar'></span>
<span class='icon-bar'></span>
</button>
</div>
<div class='collapse navbar-collapse' id='collapse'>
<div class="container">
<ul class="nav navbar-nav">
<li>Brands</li>
<li>About Us</li>
<li>Contact</li>
</ul>
</div>
</div>
</nav>
</header> <!-- end of page header -->
JavaScript (Modernizr library included for media query support, also I've used offset because the navbar is fixed and is overlapping the content area after scrollTo animation by default):
$(function () {
// making our anchors "scrollable"
var x;
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top-x
}, 700);
return false;
}
}
});
function responsive () {
if(Modernizr.mq('(min-width: 768px)')) {
x = 85;
}
if(Modernizr.mq('(max-width: 767px)')) {
x = 180;
}
}
responsive();
$(window).resize(function () {
responsive();
});
});
and as you can see, I'm using this piece of code - https://css-tricks.com/snippets/jquery/smooth-scrolling/ for making scrollTo effects. Scrolling doesn't work that great, the problem occurs when I resize the browser window. When I go from desktop to mobile (without refreshing the page) the scrolling animation won't work that well (it doesn't recognize the "mobile" script first, so when I click on a link in the menu it will first run the offset from non-mobile script, and then it will run the offset for mobile script, which makes a non-pretty animation). But if I resize the window to mobile and then refresh the page (just like opening the page from a mobile device for the first time), my scrolling works great. Same thing goes for non-mobile window sizes as well. I hope I made this question clear? Thanks.