Scrolltop animation not working - javascript

I am using this js to scroll to the id of the page. I took it from w3 schools and it works on my other site, so I don't understand why it doesn't work on my new site. It goes to the correct part of the page, but it doesn't do the scroll animation.
js:
<script>
$(document).ready(function () {
$(".navbar a, footer a[href='#myPage']").on('click', function (event) {
if (this.hash !== "") {
event.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 900, function () {
window.location.hash = hash;
});
}
});
})
</script>
html navbar code:
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav navbar-right">
<li>ABOUT</li>
<li>CLIENTS</li>
<li>SESSIONS</li>
<li>CONTACT</li>
</ul>
</div>
</div>
</nav>
Please let me know if you need to see any other code. Thanks!

That should work.
Are you positive that the new site is using jQuery and that the IDs of the element that you are scrolling to are correct?
Is your console displaying an error?

Related

How do I access these id's with javaScript

I have website with a javaScript function that should scroll to section on page when user clicks a navigation item. This script worked before I made changes to my nav menu. I can not figure out how to reference the ID's in the javaScript correctly.
Here is HTML nav menu:
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle Navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Data Detective</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li><a id="home" href="#homeSect">HOME</a></li>
<li><a id="about" href="#aboutSect">ABOUT</a></li>
<li><a id="portfolio" href="#portfolioSect">PORTFOLIO</a></li>
<li><a id="contact" href="#contactSect">CONTACT</a></li>
</ul>
</div>
</div>
</div>
Here is the javaScript:
$(document).ready(function() {
setBindings();
});
//Allow screen to Scroll to selected section
function setBindings() {
$("nav ul li a").click(function (tip) {
tip.preventDefault();
var sectionID = "#" + tip.currentTarget.id + "Sect";
alert('button id ' + sectionID);
$("html body").animate({
scrollTop: $(sectionID).offset().top
}, 1000);
});
}
You should use .navbar class.
Please change:
$("nav ul li a").click(function (tip) {
TO
$(".navbar ul li a").click(function (tip) {
Further more, I recommend you to use var sectionID = $(this).attr('href'); instead var sectionID = "#" + tip.currentTarget.id + "Sect"; because it's more simply.
Your jQuery selector:
$("nav ul li a")
will search for the element <nav> (which doesn't exist).
Instead, you can use the selector:
$(".nav a")
I would do a more useful global function I guess. I would check for any href with an anchor reference, check if there is a div with that id, and then scroll to that one.
That way you're not limited to the menu but can use the same code everywhere. Also I made the event caputurer the top level document, so you can insert and remove elements at hearts content and it will always work without having to be rebound.
$(document).on('click','a[href^="#"]',function(e) {
var target = $(e.currentTarget).attr('href');
var $target = $(target);
if($target.length > 0) {
$("html body").animate({
scrollTop: $target.offset().top
}, 1000);
}
});
div.sect {
margin:50px;
height:400px;
width:100%;
background-color:gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li><a id="blah" href="www.google.nl">Excluded</a></li>
<li><a id="home" href="#homeSect">HOME</a></li>
<li><a id="about" href="#aboutSect">ABOUT</a></li>
<li><a id="portfolio" href="#portfolioSect">PORTFOLIO</a></li>
<li><a id="contact" href="#contactSect">CONTACT</a></li>
<li><a id="blah" href="www.google.nl">Excluded</a></li>
<div class="sect" id="portfolioSect">
portfolioSect
</div>
<div class="sect" id="homeSect">
homeSect
</div>
<div class="sect" id="aboutSect">
aboutSect
</div>
<div class="sect" id="contactSect">
contactSect
</div>

How to Ensure Elements have Loaded Before Adding Class on PageLoad

I have the following bit of code, which first loads a navbar to the website on page load (this is so that I don't have to create a new navbar for each page):
<div id="nav"></div>
<script>$( "#nav" ).load( "nav.html" );</script>
And to show the "active" tab for that page, I have the following script:
<script>
window.onload = function() {
document.getElementById('lindex').className = 'active';
};
</script>
However, when the page loads, I am seeing this error in the console (for the document.getElementById line):
index.html:70 Uncaught TypeError: Cannot set property 'className' of null
And the "active" tab does not update when I navigate to the page. Strangely, it does seem to add the class when I reload the page, but intermittently. Does anyone know why this might be happening?
Here is the code for the navbar (nav.html):
<nav class="navbar navbar-inverse ">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<img src="/img/logo.png">
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li id="lindex" class="listitem">Home</li>
<li id="lpandp" class="listitem">Products & Purchasing</li>
<li>Freight & Distribution</li>
<li>Blog</li>
<li>Contact Us</li>
<li class="dropdown">
</li>
</ul>
</div>
</div>
</nav>
I have also tried:
$(function() {
$('#about').addClass('expand');
});
But this doesn't seem to work either, unless I refresh the page after navigating to it.
Try the following
<script>$( "#nav" ).load( "nav.html",function(){
$('#lindex').addClass('active');// add the class after the nav is loaded
});</script>
$( document ).ready(function() {
console.log( "ready!" );
$( "#nav" ).load( "nav.html");
console.log( "after load nav.html!" );
//add the class here
$('#lindex').addClass('active');
});
$("#lindex").addClass("Your Class Name");

Getting navigation to display the selected page

I'm struggling with getting my navigation menu to show the selected page. I'm using the Bootstrap framework to build my site. This is my navigation menu:
<nav class="navbar">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/index.html">Digital Transformation</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav pull-right">
<li class="active">Transformation deck</li>
<li>Background information</li>
</ul>
</div><!--/.nav-collapse -->
</div>
</nav>
As far as I can tell, Bootstrap uses the following JS to make the selected menu item active, which I have in my header:
<script>
$('label').click(function() {
$(this).parent('li').toggleClass('active');
});
</script>
However with this code my primary nav item is active on page load, but when I select the second item it keeps 'Tranformation deck' as active instead of 'Background information'.
Am I missing a trick here? Any help would be greatly appreciated.
If you want to hook up click listeners to your nav items, your script should be something like this:
<script>
$('#navbar nav li a').click(function() {
$(this).parent('li').toggleClass('active');
});
</script>
You don't have any 'label' tags in your code, so there isn't anything to attach click event handlers to.
$(function() {
// this will get the full URL at the address bar
var url = window.location.href;
// passes on every "a" tag
$("#navbar a").each(function() {
// checks if its the same on the address bar
if (url == (this.href)) {
$(this).closest("li").addClass("active");
}
});
});

Error: Uncaught TypeError: Cannot read property 'top' of undefined

I have this code
jQuery(function($) {
'use strict';
$(window).scroll(function(event) {
Scroll();
});
$('.navbar-collapse ul li a').on('click', function() {
$('html, body').animate({
scrollTop: $(this.hash).offset().top - 5
}, 1000);
return false;
});
function Scroll() {
var contentTop = [];
var contentBottom = [];
var winTop = $(window).scrollTop();
var rangeTop = 200;
var rangeBottom = 500;
$('.navbar-collapse').find('.scroll a').each(function() {
contentTop.push($($(this).attr('href')).offset().top);
contentBottom.push($($(this).attr('href')).offset().top + $($(this).attr('href')).height());
})
$.each(contentTop, function(i) {
if (winTop > contentTop[i] - rangeTop) {
$('.navbar-collapse li.scroll')
.removeClass('active')
.eq(i).addClass('active');
}
})
};
I tried keep getting this error when loading the code:
Uncaught TypeError: Cannot read property 'top' of undefined.
The effected lines are 9 and 21
Just in case this helps, the site this code is loading on works fine as it's html file, but doesn't when its set up as a WHMCS theme
The HTML this should be working with is
<nav id="main-nav" class="navbar navbar-default navbar-fixed-top" role="banner">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.php"><img src="templates/six/images/logo.png" alt="logo"></a>
</div>
<div class="collapse navbar-collapse navbar-right">
<ul class="nav navbar-nav">
<li class="scroll active">Home</li>
<li class="scroll">Features</li>
<li class="scroll">Services</li>
<li class="scroll">Domains</li>
<li class="scroll">Pricing</li>
<li class="scroll">Client Area</li>
<li class="scroll">Support</li>
</ul>
</div>
</div><!--/.container-->
</nav>
The problem is this:
$($(this).attr('href')).offset().top
You are sending the result of getting the href into the Jquery $function which will return an object with an undefined offset() as it's not part of the page.
$('my-a-tag').offset().top where my-a-tag finds your a tag uniquely will work, as long as my-a-tag exists on the page.
This jsfiddle here demonstrates. Open the console to see the difference between the object returned by your code and the object returned by the correct code. Also, see the offset() function working correctly.
Here's also an example line that should work in your code:
contentTop.push($(this).offset().top);
In this this case we just use this rather than a class like in the jsfiddle as we're in a loop which is going through all the anchors.

JQuery NavBar code causing scrolling to div issue

Question Background:
I have a standard bootstrap NavBar that collpases to a button on mobile devices.
The Issue:
When the user clicks on an item in the NavBar dropdown list the page will scroll down to the corrosponding div. I have a piece of JQuery that collpases the dropdown menu when the item has been clicks.
Without the JQuery to close the dropdown Nav menu the page scrolls down to the div with no issues. With the JQuery the page is scrolling down but stops well after the set 10px offset.
Without the JQuery menu closing code - working:
Note the small 10px above the panel item, this is what is wanted.
With the JQuery closing code - Broken:
Note that the page now scrolls down past the top of the div.
The Code:
The NavBar:
<div class="navbar">
<nav class="navbar navbar-default navbarColour" role="navigation" id="nav">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<img src="~/Images/DC.png" class="dc">
</div>
<div class="middleNavPadding">
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav pull-right">
<li>Services</li>
<li>Our Mission</li>
<li>Projects Gallery</li>
<li>Contact Us</li>
</ul>
</div>
</div>
</div>
</nav>
</div>
The JQuery Menu closing code:
$(document).ready(function () {
$(".navbar-nav .scroll-link").click(function (event) {
$(".navbar-collapse").collapse('hide');
});
});
The JQuery used to scroll to the Div as set in the NavBar menu:
$(document).ready(function () {
$('.scroll-link').on('click', function (event) {
event.preventDefault();
var sectionID = $(this).attr("data-id");
scrollToID('#' + sectionID, 750);
});
function scrollToID(id, speed) {
var offSet = 10;
var targetOffset = $(id).offset().top - offSet;
$('html,body').animate({ scrollTop: targetOffset }, speed);
}
});
The HTML Markup of the Panel:
<div id="Info">
//panel HTML
</div>
I believe the issue is that the JQuery is setting the 'top' of the page as the bottom of the dropdown menu which is then causing a false offset. Any help with solving a a solution to this would be much appreciated.
You are on the right track, just add the height of the #bs-example-navbar-collapse-1 to your offset.
function scrollToID(id, speed) {
var offSet = 10 + $('#bs-example-navbar-collapse-1').height(); // NAVBAR HEIGHT !!!
var targetOffset = $(id).offset().top - offSet;
$('html,body').animate({ scrollTop: targetOffset }, speed);
}
This should work.

Categories