Scrollspy - Page messing up when linking nav bar page to outside url - javascript

I need help with JQuery, I believe this may be obvious solution but I don't know how to go about it. In regards to the nav bar on my scroller page, I want one of the links on the nav bar to go an external page (not to a section in the page). It will do this, but it messes up the scrolling page, (backgrounds move to the wrong section etc). I believe I have to change the refElement but I'm unsure.. Please help :( thanks
/*=========================================================================
Navbar ScrollSpy
=========================================================================*/
var scrollPos = $(document).scrollTop(),
nav_height = $('#navbar').outerHeight();
$('.navbar li a').each(function () {
var currLink = $(this),
refElement = $(currLink.attr('href'));
if( refElement.size() > 0 ){
if ( ( refElement.position().top - nav_height ) <= scrollPos ) {
$('.navbar li').removeClass('active');
currLink.closest('li').addClass('active');
}else{
currLink.removeClass('active');
}
}
});
});
//Initialize smoothscroll plugin
smoothScroll.init({
updateURL: false
});
-----------------------------HTML--------------------------------
<nav class="navbar navbar-fixed-top">
<div class=container>
<div class=navbar-header>
<button aria-expanded=false class="collapsed navbar-toggle" data-target=#nav-collapse data-toggle=collapse type=button><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=nav-collapse>
<ul class="nav navbar-nav navbar-right">
<li class=active><a href=#intro data-scroll>Home</a>
<li><a href=#features-3 data-scroll>Marine</a>
<li><a href=#features-4 data-scroll>Industrial</a>
<li><a href=#contact data-scroll>Contact</a>
<li><a href="https://www.example.com" data-target>Careers</a></ul>
</div>
</div>

did some more digging around and found this snippet which works. thanks
/**
* Scroll Spy via Bootstrap
*/
$('body').scrollspy({target: "#nav_wrapper", offset:50});
/**
* Scroll Spy meet WordPress menu.
*/
// Only fire when not on the homepage
if (window.location.pathname !== "/") {
// Selector for top nav a elements
$('#top_main_nav a').each( function() {
if (this.hash.indexOf('#') === 0) {
// Alert this to an absolute link (pointing to the correct section on the hompage)
this.href = "/" + this.hash;
}
});
}
/**
* Initiate Awesome Smooth Scrolling based on a.href
*/
$('a.smooth-scroll, #top_main_nav a').click( function() {
target = $(this).attr('href');
offset = $(target).offset();
$('body,html').animate({ scrollTop : offset.top }, 700);
event.preventDefault();
});

Related

Changing menu options is NOT changing the active class even though I followed the solution in the link below

So, the website I'm working on is: http://wtr2022.webparity.net/. The link for the example is below.
How to change active class while click to another link in bootstrap use jquery?
So, I'll show the code I'm using and wrote and where to find it in the JS file.
HTML:
The below starts on line 77 when you open the DEBUG console or scroll to the tag.
<nav class="navbar navbar-expand-lg navbar-dark ftco_navbar bg-dark ftco-navbar-light sticky-top" id="ftco-navbar">
<div class="container">
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#ftco-nav" aria-controls="ftco-nav" aria-expanded="false" aria-label="Toggle navigation">
<span class="fa fa-bars"></span> Menu
</button>
<div class="collapse navbar-collapse" id="ftco-nav">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">Home</li>
<li class="nav-item">About</li>
<li class="nav-item">Services</li>
<li class="nav-item">Project</li>
<li class="nav-item">Blog</li>
<li class="nav-item">Roofing</li>
<li class="nav-item">Contact</li>
</ul>
<div class="d-flex align-items-center justify-content-center">
<img src="images/logos/weathertight-logo.png" class="logosmaller" alt=""/>
<!-- <span class="flaticon-roof-2"></span> -->
</div>
<div class="col-3 d-flex justify-content-end align-items-center">
<div class="social-media">
<p class="mb-0 d-flex">
<span class="fa fa-facebook"><i class="sr-only">Facebook</i></span>
<span class="fa fa-twitter"><i class="sr-only">Twitter</i></span>
<span class="fa fa-instagram"><i class="sr-only">Instagram</i></span>
<span class="fa fa-dribbble"><i class="sr-only">Dribbble</i></span>
</p>
</div>
</div>
</div>
</div>
</nav>
<!-- END nav -->
JS:
The below starts on line: 194 or scroll until you find this code.
$('.navbar-nav li a').click((e) => {
$('.active').removeClass('active');
console.log("Argument for CLICK FUNCTION: ", e.currentTarget.innerHTML);
console.log("CURRENT TARGET for CLICK FUNCTION: ", e.currentTarget.parentElement);
if (e.currentTarget.innerHTML === "Services") {
funcs.changeAboutImage('sprayfoam');
}
// add the active class to the link we clicked
// console.log("THIS: ", $(this));
$(this).addClass('active');
// e.preventDefault();
});
/* Code for changing active link on clicking */
let btns = $("#ftco-nav .navbar-nav .nav-link");
for (let i = 0; i < btns.length; i++) {
btns[i].addEventListener("click",
() => {
let current = document.getElementsByClassName("active");
console.log("CURRENT: ", current);
// current[0].className = current[0].className.replace(" active", "");
// this.className += " active";
});
}
/* Code for changing active
link on Scrolling */
$(window).scroll(() => {
let distance = $(window).scrollTop();
// console.log($(window).scrollTop());
if ($(window).scrollTop() > 701) {
$('#ftco-navbar').addClass('navbar-fixed');
}
if ($(window).scrollTop() < 700) {
$('#ftco-navbar').removeClass('navbar-fixed');
}
$('.ftco-section').each(function (i) {
if ($(this).position().top <= distance + 250) {
$('.navbar-nav a.active').removeClass('active');
$('.navbar-nav a').eq(i).addClass('active');
}
});
}).scroll();
Here's what happens:
FIRST:
When I click on the FIRST SLIDE, "Learn more..." button, it needs to scroll to the GET A QUOTE section so the YELLOW bar with the words, GET A QUOTE appear. It's not.
SECOND:
If you start from the base URL http://wtr2022.webparity.net/ and SCROLL until the menu appears, you'll see HOME as active. BUT, when you click on About, or any other menu, the active menu fails to become highlighted.
THIRD
When you start at the base URL and SCROLL to "Roofing Services We Offer", below, you'll see SPRAY FOAM ROOFING already active, BUT, whenever you click on a menu, the ACTIVE spray foam menu and content is not active and nothing is there UNLESS you click on it.
This is what happens when you CLICK on a menu and scroll to Roofing Services We offer:
I think that the ACTIVE menu is TIED together, meaning, when the addEventListener() is hit, it REMOVES ALL active classes from everything, hence, the reason.
If anyone can assist me, I'd appreciate it. Thank you.
Your click handler on the <a> tags is adding/removing the .active class to the <a> tag but it should be doing it to the parent <li> tag:
$('#ftco-nav .navbar-nav li a').click((e) => {
$('#ftco-nav .active').removeClass('active');
$(e).parent().addClass('active');
// ...
}
Your scroll handler has a similar problem. It should be adding/removing the .active class from the <li class="nav-item"> tags, not the <a> tags:
if ($(this).position().top <= distance + 250) {
$('#ftco-nav .navbar-nav .nav-item.active').removeClass('active');
$('#ftco-nav .navbar-nav a').eq(i).parent().addClass('active');
}

External links won't open

I am a noob with anything JS, I have a menubar for a onepage website that works to scroll the page but will not open external links, could one of you guys please help? Code Below, site can be viewed at http://protocol-labs.com/new
html
<div class="collapse navbar-collapse navbar-right" id="myNavbar">
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li class="">Services</li>
<li class="">About</li>
<li class="">Testimonial</li>
<li class="">Contact</li>
</ul>
</div>
js that is causing the issue
(function ($) {
// Add smooth scrolling to all links in navbar
$(".navbar a,a.btn-appoint, .quick-info li a, .overlay-detail a").on('click', function(event) {
event.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 900, function(){
window.location.hash = hash;
});
});
//jQuery to collapse the navbar on scroll
$(window).scroll(function() {
if ($(".navbar-default").offset().top > 50) {
$(".navbar-fixed-top").addClass("top-nav-collapse");
} else {
$(".navbar-fixed-top").removeClass("top-nav-collapse");
}
});
})(jQuery);
You have prevent default attached to your anchor event. This prevents the link from working.
$(".navbar a,a.btn-appoint, .quick-info li a, .overlay-detail a").on('click', function(event) {
event.preventDefault(); // prevents link from working. Remove it and you should be good.
Try to add a special class to all links with anchors (the first 4 ones) and call the function just by clicking these links, keeping the standard behavoir by clicking at Contact
I modified both js as well as html codes: (I guess this code is part of Medilab+ Template)
JS / JQuery
(function ($) {
// Add smooth scrolling to all links in navbar
$(".navbar2").on('click', function(event) {
event.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 900, function(){
window.location.hash = hash;
});
});
//jQuery to collapse the navbar on scroll
$(window).scroll(function() {
if ($(".navbar-default").offset().top > 50) {
$(".navbar-fixed-top").addClass("top-nav-collapse");
} else {
$(".navbar-fixed-top").removeClass("top-nav-collapse");
}
});})(jQuery);
HTML Code:
<div class="collapse navbar-collapse navbar-right" id="myNavbar">
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li class="">Services</li>
<li class="">About</li>
<li class="">Contact</li>
</ul>
</div>

I've added an li to my ul, while it works, it's causing an error

I've used a template which has some nice scrolling effects (https://www.freshdesignweb.com/demo/template/ubusina/#carouselHacked), however, I've added an external link to the end of the ul and it seems to work – but it's causing errors!
when I scroll I get this error:
Uncaught Error: Syntax error, unrecognized expression: http://mylink.com/blog/
I believe the first section of JavaScipt code below is where it's breaking, but I'm unsure of how to fix it:
function onScroll(event){
var scrollPos = $(document).scrollTop();
$('.navbar-default .navbar-nav>li>a').each(function () {
var currLink = $(this);
var refElement = $(currLink.attr("href"));
if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
$('.navbar-default .navbar-nav>li>a').removeClass("active");
currLink.addClass("active");
}
else{
currLink.removeClass("active");
}
});
}
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li><a class="menu active" href="#home" title="Home" >Home</a></li>
<li><a class="menu" href="#about">about </a></li>
<li><a class="menu" href="#team" title="Portfolio">Portfolio</a></li>
<li><a class="menu" href="#contact" title="Contact">contact</a></li>
<li><a href="www.google.com" target="_blank" >google</a></li>
</ul>
</div>
I presume whatever template you are using expects your menu to have a certain structure, like the class attribute applied to the anchors within the menu. The anchor you added does not have this attribute.
Try changing this:
<li><a href="www.google.com" target="_blank" >google</a></li>
To this:
<li><a class="menu" href="www.google.com" target="_blank">google</a></li>
The problem is your code is trying to select an element using the href as a selector. #home is a valid jQuery ID selector, but www.google.com is not (incidentally your probably need https://www.google.com). Try filtering so only those that start with # get used.
function onScroll(event){
var scrollPos = $(document).scrollTop();
$('.navbar-default .navbar-nav>li>a').each(function () {
var currLink = $(this);
// Only apply to those tags that start with '#'.
var href = currLink.attr("href");
if (href.indexOf('#') === 0) {
var refElement = $(href);
if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
$('.navbar-default .navbar-nav>li>a').removeClass("active");
currLink.addClass("active");
}
else{
currLink.removeClass("active");
}
}
});
}

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.

Scroll when linked to id on same page

Note: I'm new to webdev and i'm building this site with bootstrap
I'm building a one page site and the navbar at the top directs the user to the relevant id. the problem i'm having is that i want it to scroll to the id when clicked (see http://www.blastprocessor.co.uk/). I also want to set the class as active when the user scrolls past a specific id.
I have no idea where to start but i'll post my html code here.
<nav class="navbar navbar-default" data-spy="affix" data-offset-top="34">
<div class="container">
<div class="navbar-collapse collapse navbar-responsive-collapse" id="main-menu">
<ul class="nav navbar-nav">
<li class="active">What We Are</li>
<li class="">Why Us</li>
<li class="">What We Offer</li>
<li class="">Contact Us</li>
</ul>
<ul class="nav navbar-nav pull-right">
<li>Right Link</li>
</ul>
</div>
</div>
</nav>
You can use the following function to make your scroll animation. Regarding adding a class 'active' to the past id actually you can follow the answer of #ahb. For your need i just added a var reduce in the function which will help you reduce 50px from the actuall offset.
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
var reduce = 50;
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 - reduce
}, 1000);
return false;
}
}
});
});
ORIGINAL SOURCE
DEMO
Using JQuery:
See here to scroll and animate to your ID.
To add your class after scrolling past your ID use:
//assign the window and all the contents into variables
//instead of going and grabbing it from the DOM on every scroll
var $window = $(window),
$content = $('.content');
$window.scroll(function () {
$content.each(function () {
//for each element that has a class of content
//check its position and add SomeClass
if ($window.scrollTop() >= $(this).position().top) {
$(this).addClass('SomeClass');
} else if ($window.scrollTop() <= $(this).position().top) {
//if window position is less then remove it
$(this).removeClass('SomeClass');
}
});
});

Categories