jquery code does not work fine with differents urls - javascript

I have this jquery code:
$(function(){
var $win = $(window);
var $nav = $('.subnav');
var navTop = $('.subnav').length && $('.subnav').offset().top - 38;
var isFixed = 0;
processScroll();
$win.on('scroll', processScroll);
function processScroll() {
console.log('test');
var i, scrollTop = $win.scrollTop();
if (scrollTop >= navTop && !isFixed) {
isFixed = 1;
$nav.addClass('subnav-fixed');
} else if (scrollTop <= navTop && isFixed) {
isFixed = 0;
$nav.removeClass('subnav-fixed');
}
};
})
If I have this url for example:
http://mydomain.com/posts or http://mydomain.com or http://mydomain.com/post?utf8=✓&search=
the code does works fine, but if I have for example:
http://mydomain.com/post?utf8=✓&search=port or http://mydomain.com/post?utf8=✓&search=word
The code does not works fine...
Why if I pass a param for url with my search engine the code does not works fine?
Thank you very much!
Edited
I am using this sunspot solr for my as search engine
http://sunspot.github.com/

I found the fix in this question:
Replicating Bootstraps main nav and subnav
This is the code:
$(document).scroll(function(){
// If has not activated (has no attribute "data-top"
if (!$('.subnav').attr('data-top')) {
// If already fixed, then do nothing
if ($('.subnav').hasClass('subnav-fixed')) return;
// Remember top position
var offset = $('.subnav').offset()
$('.subnav').attr('data-top', offset.top);
}
if ($('.subnav').attr('data-top') - $('.subnav').outerHeight() <= $(this).scrollTop())
$('.subnav').addClass('subnav-fixed');
else
$('.subnav').removeClass('subnav-fixed');
});
Thank you

Related

Caught on a persistent issue with JS, nav bar active class not switching properly

I've been using this code snippet to add in a vertical dot nav to a one page site, which smooth scrolls to a section when one of the links are clicked, and keeps a highlight on the active section. I did a lot of tweaking to the css to make it look how I wanted, and then replaced the sections.
So this is my code in a jsfiddle, and the main issue I am having is the active class not changing properly, and making the side nav bar mess up. I've posted the JS below.
$(document).ready(function(){
$('.awesome-tooltip').tooltip({
placement: 'left'
});
$(window).bind('scroll',function(e){
dotnavigation();
});
function dotnavigation(){
var numSections = $('section').length;
$('#side-nav li a').removeClass('active').parent('li').removeClass('active');
$('section').each(function(i,item){
var ele = $(item), nextTop;
console.log(ele.next().html());
if (typeof ele.next().offset() != "undefined") {
nextTop = ele.next().offset().top;
}
else {
nextTop = $(document).height();
}
if (ele.offset() !== null) {
thisTop = ele.offset().top - ((nextTop - ele.offset().top) / numSections);
}
else {
thisTop = 0;
}
var docTop = $(document).scrollTop();
if(docTop >= thisTop && (docTop < nextTop)){
$('#side-nav li').eq(i).addClass('active');
}
});
}
/* get clicks working */
$('#side-nav li').click(function(){
var id = $(this).find('a').attr("href"),
posi,
ele,
padding = 0;
ele = $(id);
posi = ($(ele).offset()||0).top - padding;
$('html, body').animate({scrollTop:posi}, 'slow');
return false;
});
It works fairly well on the jsfiddle, but I am putting this code into squarespace, and on there it ends up like this where all of the buttons highlight when you try to change active classes.
I have tried to isolate the bug by going through the html, css, and the js, but I don't have enough knowledge of JS to be able to edit the script to fix it.
I would really appreciate any help. Thanks in advance.
EDIT: Link to broken squarespace
In the code snippet, the sample page is designed with continuous sections, so the method ele.next() will return next sections. In your squarespace page, the sections is not continuous, so method ele.next() will return empty and the code is not working.
Your could try to modify function dotnavigation like this
function dotnavigation(){
var numSections = $('section').length;
$('#side-nav li a').removeClass('active').parent('li').removeClass('active');
var sections = $('section');
var i = 0;
for (i = 0; i < sections.length; i++) {
var ele = $(sections[i]), nextTop;
//console.log(ele.next().html());
if (i < sections.length - 1) {
nextTop = $(sections[i + 1]).offset().top;
}
else {
nextTop = $(document).height();
}
if (ele.offset() !== null) {
thisTop = ele.offset().top - ((nextTop - ele.offset().top) / numSections);
}
else {
thisTop = 0;
}
var docTop = $(document).scrollTop();
console.log(thisTop);
if(docTop >= thisTop && (docTop < nextTop)){
$('#side-nav li').eq(i).addClass('active');
}
}
}
I've updated your code sample here.

Hide Div on Scroll with JQuery

I'm sure this is a trivial problem but I cannot seem to figure it out. I'm trying to fade a side bar in and out, and because I have a few of them in my website, I need to give them individual IDs for Javascript.
This code works
$(window).on("scroll", function() {
var scrollPos = $(window).scrollTop() - 100 ;
if (scrollPos < 100) {
$("#menu").fadeOut();
} else {
$("#menu").fadeIn();
}
});
This doesn't
$(window).on("scroll", function() {
var menu = document.getElementById("menu");
var scrollPos = $(window).scrollTop() - 100 ;
if (scrollPos < 100) {
menu.fadeOut();
} else {
menu.fadeIn();
}
});
In the latter piece, all I'm trying to do is assign a variable.
Here's the fiddle: https://jsfiddle.net/gavinfriel/nhovvj6q/1/
Your help would be appreciated.
You have to wrap it in a jQuery call to make it a jQuery object. Otherwise it cannot find the fadeOut and fadeIn functions:
var menu = $("#menu");
or
var menu = $(document.getElementById("menu"));
You need to use jquery to convert menu to jQuery object.
So it will have the fade property
$(window).on("scroll", function() {
var menu = document.getElementById("menu");
var scrollPos = $(window).scrollTop() - 100 ;
if (scrollPos < 100) {
$(menu).fadeOut();
} else {
$(menu).fadeIn();
}
});
Because if you use menu.fadeOut() it will generate error because menudoesn't have fade property
Checkout this it will work.
$(window).on("scroll", function() {
var menu = $("#menu");
var scrollPos = $(window).scrollTop() - 100 ;
if (scrollPos < 100) {
menu.fadeOut();
} else {
menu.fadeIn();
}
});
As others have mentioned, you've declared a JavaScript variable but are trying to use it as a jQuery object.
I would personally go with PierreDuc's answer but if you refactor your code slightly you can carry on using the vanilla JS declared vaiable, but pass the variable slightly differently:
var test = document.getElementById("test");
$(test).hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="test">
TEST
</div>
In your 2nd code, this might look as follows:
$(window).on("scroll", function() {
var menu = document.getElementById("menu");
var scrollPos = $(window).scrollTop() - 100 ;
if (scrollPos < 100) {
$(menu).fadeOut();
} else {
$(menu).fadeIn();
}
});

Change URL on scroll not working in chrome and opera

I use the following script to change the url hash when scrolling to a section of a one page website. This is working perfect in ie and firefox, but not in chrome and opera and i cant figure it out.
(jQuery)(function ($) {
// CHANGE URL ON SCROLL
$(function () {
var currentHash = "#intro"
$(document).scroll(function () {
$('section').each(function () {
var top = window.pageYOffset;
var distance = top - $(this).offset().top;
var hash = $(this).attr('id');
if (distance < 30 && distance > -30 && currentHash != hash) {
window.location.hash = (hash);
currentHash = hash;
}
});
});
});
});
Try using $("body").offset().top instead of window.pageYOffset

How to change when Jquery edits my CSS upon reaching an anchor point?

I've found this piece of Jquery to change CSS when it reaches an anchor point.
$(window).on("scroll", function() {
var scrollPosition = scrollY || pageYOffset;
if (scrollPosition > $("#someAnchor").position().top - $(window).height()) {
alert("run code here");
}
});
The problem is it does so when the bottom of the screen reaches the anchor point, but it needs to run the code when the top touches the anchor point. How do I do this?
Hoping this works well for you:
var ranOffsetCode = false
$(window).on("scroll", function() {
var docScrollTop = $(document).scrollTop(); // Figure out how far we scrolled.
var someAnchorTop = $('#someAnchor').offset().top - $('#someAnchor').height(); // Figure out how far down the element is on the page
if (docScrollTop >= someAnchorTop) { // If we scrolled up to or past the element, fire this
if (ranOffsetCode === false) { // This makes sure we only run the function once and not every scroll
ranOffsetCode = true;
console.log('run code here'); // Functional code to execute after we scrolled down this far.
}
}
else {
ranOffsetCode = false;
}
});
Demo
Simply remove - $(window).height()
$(window).on("scroll", function() { var scrollPosition = scrollY || pageYOffset;
if (scrollPosition > $("#someAnchor").position().top) { alert("run code here"); } });
Not really meant to be an answer, but it might help:
var spam = false;
$(window).on("scroll", function() {
var scrollPosition = scrollY || pageYOffset;
$('#pos').html( 'y: '+scrollY+', a: '+$("#someAnchor").position().top + ', p: '+scrollPosition );
if (!spam && (scrollPosition > $("#someAnchor").position().top)) {
alert('hit it!');
spam = true;
}
});
Some html:
<div style="position:fixed; top:0; left:85%; width:15%; height:20px">
<span id="pos" style="font-family:Courier; font-size:0.5em; white-space:pre"></span>
</div>

jQuery Scroll Current Position and Next-Prev Navigator

I need a bit of advice as I can't get my noob head around the following, please see this fiddle: http://jsfiddle.net/NtUpw/
The code works as intended, but when the current div offset goes > 41 and prev is hit, I'd like the page to return to the beginning of the current div, not to one before that. Any idea how can I add this condition?
I realise the current code isn't the cleanest (actually it's a combination of two fiddles), but I hope someone could take a look at it anyway. Thanks.
$('a.buttons').on('click', function (e) {
e.preventDefault();
var t = $(this).text(),
that = $(this);
if (t === 'next' && $('.current').next('div.post').length > 0 ) {
var $next = $('.current').next('.post');
var top = $next.offset().top;
$('body').animate({
scrollTop: $('.current').next('div.post').offset().top - 40
});
} else if (t === 'prev' && $('.current').prev('div.post').length > 0 ) {
var $prev = $('.current').prev('.post');
var top = $prev.offset().top;
$('body').animate({
scrollTop: $('.current').prev('div.post').offset().top - 40
});
}
$(window).bind('scroll', function () {
$('.post').each(function () {
var post = $(this);
var position = post.position().top - $(window).scrollTop();
if (position <= 40) {
post.addClass('current');
post.prev().removeClass("current");
} else {
post.removeClass('current');
}
});
});
The prev action works by moving always the div to the previous; the solution is to check the current position of the navigator respect to the current div:
var $prev;
var top;
var firstElem = true;
if ($('.current').prev('div.post').length > 0) {
$prev = $('.current').prev('.post');
top = $prev.offset().top;
firstElem = false
}
var currTop = $('.current').offset().top;
var navBottom = $('.navigation').offset().top + 40;
if (currTop == navBottom && !firstElem) {
$('body,html').animate({
scrollTop: $('.current').prev('div.post').offset().top - 40
});
with this the navigator jumps to the previous div only if is not at the top of the current; alternatively jumps to the previous.
The firefox issue depends on how Firefox places the overflow, it places it at the html level not at body like other browsers.
To let it work you must define the scrolling action with:
$('body,html').animate({
});
Working fiddle: http://jsfiddle.net/IrvinDominin/2QYgR/3/

Categories