Bootstrap: scrollspy doesn't work after I've added smooth scrolling - javascript

I'm building a site using Twitter Bootstrap, and I got the scrollspy to work, using the below javascript:
$('body').scrollspy({ target: '.navbar' })
But it stopped working for me, after I add the script to enable smooth scrolling:
<script type="text/javascript">
$(document).ready(function() {
// navigation click actions
$('.scroll-link').on('click', function(event){
event.preventDefault();
var sectionID = $(this).attr("data-id");
scrollToID('#' + sectionID, 750);
});
// scroll to top action
$('.scroll-top').on('click', function(event) {
event.preventDefault();
$('html, body').animate({scrollTop:0}, 'slow');
});
// mobile nav toggle
$('.nav-toggle').on('click', function (event) {
event.preventDefault();
$('#bs-example-navbar-collapse-1').toggleClass("open");
});
});
// scroll function
function scrollToID(id, speed){
var offSet = 70;
var targetOffset = $(id).offset().top - offSet;
var mainNav = $('#bs-example-navbar-collapse-1');
$('html,body').animate({scrollTop:targetOffset}, speed);
if (mainNav.hasClass("open")) {
mainNav.css("height", "1px").removeClass("in").addClass("collapse");
mainNav.removeClass("open");
}
}
if (typeof console === "undefined") {
console = {
log: function() { }
};
}
</script>
I'm thinking I must have added the scrollspy in an incorrect position. I have very little knowledge of javascript. If someone can point me the way to inserting it in the correct order/space/line, that would be great!
Thanks in advance!

You may want to use a third party plugin such as jquery.localScroll (which relies on jquery.scrollTo). It provides great smooth scrolling and is easy to implement. A lot easier than reimplementing the wheel.
https://github.com/flesler/jquery.localScroll

Related

Modal/Popup Changing Start Position if Scrolling Prior to Click

Good morning everyone. I have a novice JS question that I need help clearing up. First off I am an extreme beginner and self taught so forgive any ignorance.
I am building a new website for a business and one of the pages has a grid of products for customers. Each product has a button which creates a modal to give more information about the product. I am using a JS I found online to have DIFFERENT Modals inside some of these other modals. If you click the modal in question (star fish or sea horse) after scrolling the page first, the modals appear further down and cut off by the screen.
example: https://my.duda.co/preview/27d7a4cc?device=desktop&pageId=30782523
I know the author of the JS included a var to reposition the modal if the user had scrolled but it is not working in my favor or there is something more I need to do and don't have the knowledge for it.
I also know the code is sloppy and probably redundant in some places, I am not an expert. My JSFiddle: https://jsfiddle.net/shnt7vwu
<script>
var $html = $(document.documentElement);
var $modal = $('.modal-container');
function showModal() {
$html.css('overflow', 'hidden');
$modal.show().css('overflow', 'auto');
}
function hideModal() {
$html.css('overflow', 'visible');
$modal.show().css('overflow','visible')
}
$('.modal-btn').on('click', showModal);
$('.modal-close').on('click', hideModal);
</script>
<script>
var scrollTop = '';
var newHeight = '100';
$(window).bind('scroll', function() {
scrollTop = $( window ).scrollTop();
newHeight = scrollTop + 100;
});
$('.popup-trigger').click(function(e) {
e.stopPropagation();
if(jQuery(window).width() < 767) {
$(this).after( $(this).nextAll('.popup:first') );
$(this).nextAll('.popup:first').show().addClass
('popup-mobile').css('top', 0);
$('html, body').animate({
scrollTop: $(this).nextAll('.popup:first').offset().top
}, 500);
} else {
$('.popup').hide();
$(this).nextAll('.popup:first').removeClass('popup-mobile').css
('top', newHeight).toggle();
};
});
$('html').click(function() {
$('.popup').hide();
});
$('.popup-btn-close').click(function(e){
$(this).parent().hide();
});
$('.popup').click(function(e){
e.stopPropagation();
});
</script>
You can place your whole 'div body grid' stuff inside a div with overflow-y enabled, then have your modals with vh:100 hidden outside
Just disable all the modals, div property until the correct user action is taken.
This way you can avoid calculations which may break between platforms and in edge cases.

One page scrolling links dont show anker in url

What I have is this:
$(document).ready(function(){$('a[href^="#"]').on('click',function(e){e.preventDefault();var t=$(this.hash).offset().top;$('.wrapper').animate({scrollTop:t,},1000)})});
and actually place divs everywhere as a reference such as:
<div id="about"></div>
It actually scrolls down to those reference points but I dont see the name in the url. When I scroll down and end up in the about section I want it to somehow show up like this www.site.com/#about
Any idea what I am doing wrong? The site used is a HTML document.
give a try to this
$(document).ready(function () {
$('a[href^="#"]').on('click', function (e) {
e.preventDefault();
var target = this.hash;
var t = $(this.hash).offset().top;
$('.wrapper').animate({
scrollTop: t,
}, 1000, function () {
window.location.hash = target;
});
});
});
You can use Html5 History API Good tutorial for using HTML5 History API (Pushstate?)
$(document).ready(function() {
$('a[href^="#"]').on('click',function(e) {
e.preventDefault();
var t = $(this.hash).offset().top;
$('.wrapper').animate({ scrollTop:t }, 1000);
history.pushState(null, null, location.href + $(this).href); // <- not sure whether your links are relative or absolute.. do change appropriately..
})
});

jQuery Scrolling Length

I am working with a script to scroll an element on click. It's working properly, however it either scrolls all the way up, or all the way down. I'm new to jquery, and I'm wondering how to make it scroll a little at at time. For example, clicking to scroll down once will take you down a certain length, clicking again scrolls that length again. Also, sometimes it jitters and bugs out when scrolling back up. Any insight on how to fix this is appreciated as well!
Thanks.
Code below:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script>
$(function() {
var ele = $('#scroll');
var speed = 25, scroll = 5, scrolling;
$('#scroll-up').click(function() {
// Scroll the element up
scrolling = window.setInterval(function() {
ele.scrollTop( ele.scrollTop() - scroll );
}, speed);
});
$('#scroll-down').click(function() {
// Scroll the element down
scrolling = window.setInterval(function() {
ele.scrollTop( ele.scrollTop() + scroll );
}, speed);
});
$('#scroll-up, #scroll-down').bind({
click: function(e) {
// Prevent the default click action
e.preventDefault();
},
mouseleave: function() {
if (scrolling) {
window.clearInterval(scrolling);
scrolling = false;
}
}
});
});
</script>
You're saying you want to scroll little at a time but your code is saying scroll UNTIL mouse leaves. If you want to scroll little at a time why would you write a mouseleave which clearly stating if it's been scrolling stop now!
If you want to scroll up/down a bit on click, you should get rid of setInterval and mouseleave.
$(function() {
var ele = $('#scroll');
var speed = 25, scroll = 5;
$('#scroll-up').click(function() {
// Scroll the element up
ele.scrollTop( ele.scrollTop() - scroll );
});
$('#scroll-down').click(function() {
ele.scrollTop( ele.scrollTop() + scroll );
});
$('#scroll-up, #scroll-down').bind({
click: function(e) {
// Prevent the default click action
e.preventDefault();
}
});
});
jsfiddle

Javascript or jQuery slide to element

When a user clicks on the "Contact Me" button, i want the screen to slide to the #contact element, however cannot figure out how to do it. I've tried various different snippets of code and tried to tailor it to my needs, but nothing seems to work.
The site is here; http://dombracher.com/
Simply want the screen to slide to the div mentioned above, rather than quickly snap to it.
Thanks in advance.
$(document).ready(function() {
$("a[href^='#']").anchorAnimate()
});
jQuery.fn.anchorAnimate = function(settings) {
settings = jQuery.extend({
speed : 1100
}, settings);
return this.each(function(){
var caller = this
$(caller).click(function (event) {
event.preventDefault()
var locationHref = window.location.href
var elementClick = $(caller).attr("href")
var destination = $(elementClick).offset().top;
$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, settings.speed, function() {
window.location.hash = elementClick
});
return false;
})
})
}
You can animate window scroll by yourself
$(".menu2").click(function(){
$(document.body).animate({
"scrollTop": $("#contact").offset().top
}, 2000, "swing"); // animation time and easing
return false; // preventing default jump
});
Fiddle: http://jsfiddle.net/M8JE2/
Or use jquery plugin like http://flesler.blogspot.com/2007/10/jquerylocalscroll-10.html to make any/all local links work with animation.
Here it is , scrolls to the bottom of the page since your contact form is there:
jQuery(function () {
jQuery('#nav1 li.menu2').click(function (e) {
jQuery("html, body").stop().animate({
scrollTop: jQuery(document).height()
}, 1000);
e.preventDefault();
return false;
});
});

Scrolling and .addClass(); issues

I am working on a "one page" website with a fixed navigation and about 5 different pages inside the one document.
UPDATED WORKING LINK
http://www.coco-works.com/Archive/ LIVE VERSION
I'm having trouble with the active class addition. When you click Keep in Touch or Home, the class is not applied. As you can see from the live version, it's not function properly.
The page works something like this;
And here is the JavaScript;
$(document).ready(function() {
$('body').click(function(event) {
if (event.target.nodeName.toLowerCase() == 'a') {
var op = $(event.target);
var id = op.attr('href');
if (id.indexOf('#') == 0) {
$.scrollTo(id, 1000, {
offset: {
top: 75
},
axis: 'y',
onAfter: function() {
window.location.hash = id.split('#')[1];
}
});
}
return false;
}
});
$.fn.waypoint.defaults.offset = 75;
$('.section h1.page_name').waypoint(function() {
var id = this.id;
var op = $('#navigation a[href = "#' + id + '"]');
if (op.length) {
$("#navigation a").removeClass("active");
op.addClass('active');
}
});
});
I'm not a strong programmer. I've tried to edit it as best as I can and I'm just stuck. Any insight to fixing this would highly be appreciated.
Still looking for an answer, below couldn't fix the problem.
I'm not sure what the waypoints plugin was doing, but I've refactored your code and it is working for me. Note that I took out the call to .waypoints, and changed your $('body').click() handler to be a more specific handler on the navigation link elements. This handler will scroll to each element and then will perform the removal and addition of the class correctly when the scrolling is done:
$(document).ready(function()
{
function highlightNav(navElement){
$("#navigation a").removeClass('active');
navElement.addClass('active');
}
$('#navigation a').click(function(event){
var nav = $(this);
var id = nav.attr('href');
$.scrollTo(id, 1000, {
offset: { top: -75 },
axis: 'y',
onAfter: function(){
highlightNav(nav);
}
});
return false;
});
$(window).scroll(function(){
if($(this).scrollTop() == 0){
highlightNav($("#navigation a[href*='home']"));
}
});
$.fn.waypoint.defaults.offset = 75;
$('.section h1.page_name').waypoint(function() {
var id = this.id;
var op = $('#navigation a[href = "#' + id + '"]');
if (op.length) {
highlightNav(op);
}
});
// Fancybox
$("a.zoom").fancybox({
'overlayShow' : false,
'transitionIn' : 'elastic',
'transitionOut' : 'elastic'
});
$("a.outside_shade").fancybox({
'titlePosition' : 'outside',
'overlayColor' : '#000',
'overlayOpacity' : 0.9
});
$("a.inside_white").fancybox({
'titlePosition' : 'inside'
});
$("a.inside_shade").fancybox({
'titlePosition' : 'over'
});
// validation
$("form").validate();
// nivo slider
$('#slider').nivoSlider();
});
In the html I added a default active class to the first link:
<div id="navigation">
<ul>
<li>Home</li>
<li>Portfolio</li>
<li>Who Are We?</li>
<li>Our Services</li>
<li>Features</li>
<li>Keep in Touch</li>
</ul>
</div>
Also I noticed on the page you have your css defined before the reset.css is called in. That's usually bad practice you might want to make sure reset.css is always the very first css file pulled in. It doesn't appear to have affected the page much but sometimes you'll get weird results doing that.
I made a jsfiddle of the results here: http://jsfiddle.net/RNsFw/2/
the waypoints plugin isn't needed anymore I think. I didn't change the fancybox or validation stuff because i'm not sure what those are doing and it wasn't really part of your issue.
I tested it in firefox and Chrome. Let me know if you have questions :)
http://jsfiddle.net/vCgy8/9/
This removes the dependency on scrollTo, and the waypoints plugin.
$('body').click(function(event)
{
if(event.target.nodeName.toLowerCase() == 'a')
{
var op = $(event.target);
var id = op.attr('href');
if(id.indexOf('#') == 0)
{
destination = $(id).offset().top;
$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, 1000, function() {
var hash = id.split('#')[1];
window.location.hash = hash;
});
}
return false;
}
});
$(window).scroll(function (event){
makeActive();
});
function makeActive(){
var y = $(this).scrollTop();
if(y!==0){
$('.page_name').each(function(){
var curPos = parseInt($(this).offset().top - y);
if(curPos <= 0){
var op = $('#navigation a[href = "#'+$(this).attr('id')+'"]');
$("#navigation a").removeClass("active");
op.addClass('active');
}
});
}else{
$("#navigation a").removeClass("active");
$("#navigation a:first").addClass('active');
}
}
makeActive();
This may be completely unrelated, but I had a similar problem yesterday - where, in the callback of an event handler, jQuery operations weren't being performed in that scope but if you threw the code into something like:
setTimeout(function() {
$(selector).addClass('foo');
}, 0);
it would work - similar to how $.animate() functions (ish) if you call $(selector).stop().animate() without the queue param being false, eg:
$(selector).stop();
$(selector).animate({ foo }, { no queue:false here });
// ^ fail
$(selector).stop();
setTimeout(function() {
$(selector).animate({ foo }, { no queue:false here either });
}, 0);
// ^ success
The problem, completely unrelated to the above example though similar in behavior/functional hack, turned out to be the method of binding - in my case I had been using $.bind() - but then I refactored this to use $.delegate() ($.live() would work also) and it functioned as expected.
Again, not sure if this related, but figured I'd pass that along just in case. Unsure if it's a bug or just me not properly understanding some of the subtler parts of jQuery.
The problem is not in your js code, but in your css/page layout.
Or maybe the problem is that you are using the waypoint plugin and you might not want to for this particular page. (As you will see you also have trouble hitting the "Home" waypoint again once you have left it, because of the offset you use.)
The thing is, the waypoint plugin won't trigger until the target element you are scrolling to is in the very top of the browser window, with respect to the offset that is. "Keep in touch" will never get to the top unless your browser window is small enough that the "keep in touch" section takes up the entire browser window (minus the offset).
You can see it visualized here:

Categories