jQuery Scroll Event Not Working With Section - javascript

I'm trying to make a simple scrollspy with jQuery Scroll event but it fails. Here is my JavaScript part:
<script>
$(document).ready(function(){
$("#credit_card").scroll(function(){
console.log('OK');
});
});
</script>
And HTML part:
<section class="method first-of-group" id="credit_card">
...
</section>
As you might have guessed, console.log is just for testing. This section is under a div and this div has "content" id. If I change my JavaScript code for "content" id, it is working. It's really weird.
If you want to see it live, please visit here.
Thanks in advance.

After reading the comments and actually understanding what you mean, this is the solution you are looking for.
$(document).ready(function(){
$("#content").scroll(function(){
// when the user scrolls, we want to detect at what section they currently are.
// This can be calculated, by comparing the current window scrolltop to the position and height of the section elements.
var currentTopOffset = $(document).scrollTop();
$('section').each(function(){
var min = $(this).offset().top;
var max = $(this).offset().top + $(this).height();
if(currentTopOffset > min && currentTopOffset < max){
// current section
// do something here, like getting a value from an input type hidden with the section name
}
});
});
});
I hope this is what you are looking for, or atleast something to get you started with.

Related

Variable doesn't work inside JQuery scroll function

my goal is to create and display variable which will record scroll position. While the scroll function seems to be working (for example i can alert a message inside it) but when I add a scroll_pos variable it just stops working. I have followed this tutorial https://www.youtube.com/watch?v=AwgODLLSgwU but i don't understand what's wrong with my code. I use <div id="'status> to display the variable. Any suggestions?
Here's the code https://jsfiddle.net/avxgeeah/
$(document).ready(function(){
$("#text_area").scroll(function(){
var scroll_pos = $(this).scrollTop();
alert(scroll_pos);
});
});
it works here https://jsfiddle.net/j5vg0fsj/
$("#target").scroll(function(){
var scroll_pos = $(this).scrollTop();
alert(scroll_pos);
});
I know that chrome will offer to disable alerts if they are firing too frequently. Perhaps you okayed that?

Javascript Changing Css Elements

I was following this tutorial, trying to get my sites navigation bar to stick to the top of the page when it reaches the top of the page. I couldn't get it to work with the way they had it set up, so I tried to set it up in a different way and still can't get it to work. I put this code at the end of my body tag to try and make this work (the navigation bar has a css id of "navbar"):
jQuery
if ($document).scrolltop() > 132){
$("#navbar").css("position", "fixed");
$("#navbar").css("top", "132px");
}
else{
$("navbar").css("position","static");
}
Is there something I am missing?
Thanks in advance,
Bradon
Edit:
I want to thank everyone for the quick replies, and apologize as I am both new to javascript and stackoverflow. I have tried to implement some of the solutions suggested and here is what I have now:
<script type="text/javascript">
var navbar = $("#navbar");
navbar.on("scroll", function(e){
if (navbar.scrollTop() <= 0){
navbar.css("position", "fixed");
navbar.css("top", "0px");
}
else{
navbar.css("position","static");
}
});
</script>
I still can't get it to work properly.
Edit 2:
I would like to thank everybody for their help, I couldn't have figured it out without you guys. Here is the code I used if anybody should ever need it:
<script type="text/javascript">
var navbar = jQuery("#navbar");
jQuery(document).on("scroll", function(e){
if (jQuery(document).scrollTop() > 280){
navbar.css("position", "fixed");
navbar.css("top", "0px");
}
else{
navbar.css("position","static");
navbar.css("top", "auto");
}
});
</script>
this script assumes the thing you want stuck to the top has a class of "navbar". My problem was that wordpress wasn't accepting $ in jquery so I replaced it with jQuery. Thank-you once again everybody!
There is a bigger issue in that your scrolltop check is happening only once, while the page is loading. In the original tutorial, the code that checks the scrolltop is set to execute everytime a scroll event occurs:
wrap = $('#wrap');
wrap.on("scroll", function(e) {
if (this.scrollTop > 147) {
wrap.addClass("fix-search");
} else {
wrap.removeClass("fix-search");
}
});
The "wrap.on('scroll')" part is very critical because this will cause the "scrolltop" value check to be triggered whenever the div is scrolled.
I believe the syntax is wrong. Missing parenthesis on document.scrollTop and also missing the # sign on navbar.
<script type="text/javascript">
if ( $(document).scrollTop() > 132){
$("#navbar").css("position", "fixed");
$("#navbar").css("top", "132px");
}
else{
$("#navbar").css("position","static");
}
</script>

Trouble with an one page navigation - updating/highlighting active state and scroll to anchor

I'm already busy with a one page navigation. Below you will find more information about the problem and my wish.
How should it work?
Once a navigation item is clicked, scroll to its particular section and update the active class of the menu. And if the page is scrolled to its particular section, it should update the active state too - so change the class to its particular anchor.
Fixed header
For the website I also used a fixed header, so this should NOT be overlay the particular section. So the menu should stop scrolling when the bottom of the header is reaching the top of the section.
Variable sections
All sections on the one page design has a different height.
Problem
I have already tried a lot of code, to get it work. Most of the code is working, but this isn’t in all browsers the same. Also I have some trouble with updating the active state of the particular section - that match to the active anchor.
Code
I used jQuery to create a smooth scroll to anchor. You can see my working code at JSfiddle.
Here are all resources:
JS
Here I controle the click function of the navigation.
So when the user click a list item of #primary-navwrapper, then change the active state class and scroll to the particular section, that match with the clicked anchor.
$('#primary-navwrapper li').find('a[href^="#"]').click(function(event) {
// Prevent from default action to intitiate
event.preventDefault();
$('#primary-navwrapper li a').removeClass("current");
$(this).addClass("current");
// The id of the section we want to go to.
var anchorId = $(this).attr("href");
// Our scroll target : the top position of the
// section that has the id referenced by our href.
var target = $(anchorId).offset().top - offset;
//console.log(target);
$('html, body').animate({ scrollTop: target }, 500, function () {
//window.location.hash = '!' + id;
window.location.hash = anchorId;
});
});
Beside the click function, I also want that when the user scrolls around the one page, it will automatically update the active statement.
function setActiveListElements(event){
// Get the offset of the window from the top of page
var windowPos = $(window).scrollTop();
$('#primary-navwrapper li a[href^="#"]').each(function() {
var anchorId = $(this);
var target = $(anchorId.attr("href"));
if (target.length > 0) {
if (target.position().top <= windowPos && target.position().top + target.height() > windowPos) {
$('#primary-navwrapper li a').removeClass("current");
anchorId.addClass("current");
}
}
});
}
$(window).scroll(function() {
setActiveListElements();
});
In above code, I think that the line of if (target.position().top <= windowPos && target.position().top + target.height() > windowPos) isn’t correct and maybe to long..
If there are any questions or something, I like to hear from you.
Casper
Looking at your code, I've updated the line you said for the below one:
if (target.position().top - $('#header').outerHeight() <= windowPos) {
$('#primary-navwrapper li a').removeClass("current");
anchorId.addClass("current");
}
In this way, it'll get the target's difference to the top minus the header's height (as it will be always visible) and then check with the window's position. If it's inferior, the user has passed this anchor, so the correspondent link in the menu gets highlighted.
And your first link doesn't have its anchor in the fiddle, so:
<li>Home</li>
After these changes, everything seems to work fine.
JSFiddle: http://jsfiddle.net/8n06pvy9/17/
EDIT:
To update the hash, I've tried to use a simple window.location.hash = anchorId;, but it results in some weird scroll issues in FF and IE. I've spent some time on it, but I wasn't able to figure out what happens.
So, I suggest a trick that I've already used, using #! in the hash. In this way, your code would be like that:
window.location.hash = '#!' + anchorId.replace('#', '');
And in the scroll function, like that:
window.location.hash = '#!' + anchorId.attr('href').replace('#', '');
JSFiddle: http://jsfiddle.net/8n06pvy9/18/
And, if you want, you can check for the hash in pageload, remove the exclamation point and scroll the page to the desired anchor. Or, if you want to avoid all of that, you can always use some history plugins, like this one. In your case, I personally wouldn't use a plugin for that, but it's your call if it worth it or not.
Hope it helps!

Cant fix a jquery / javascript bug

I have some jquery code that is picking up some issues in firebug chrome.
any help would be great, please update fiddle.
please see the link with fiddle.
http://jsfiddle.net/jwhTd/
image
/* SHOW CATEGORIES
===================================================================*/
$('.normal-btn\.interest').click(function(e){
// Prevent the event from bubbling up the DOM tree
e.stopPropagation();
$('.categories-wrap').fadeIn(); // must be hidden, to fade in
});
$(document, '.normal-btn\.interest').click(function(){
$('.categories-wrap').fadeOut(); // must be visible, to fade out
});
var offset = $(".sticky-header").offset();
var sticky = document.getElementById("sticky-header")
var additionalPixels = 50;
$(window).scroll(function () {
if ($(window).scrollTop() > offset.top - additionalPixels) {
$('#profile-container').addClass('fixed');
} else {
$('#profile-container').removeClass('fixed');
}
});
It's telling you exactly what is wrong. offset is undefined. You probably expect that it has a value, check why it doesn't have one.
You get more errors though. Something about slider and another about an invalid .top access somewhere.
it looks like most of that code is not in the document.ready. the var offset = $(".sticky-header").offset(); needs to be executed once the dom is ready.
Your code:
var offset = $(".sticky-header").offset();
var sticky = document.getElementById("sticky-header")
var additionalPixels = 50;
The first line selects all elements with the class of sticky-header, then gets the offset of the first one. The .offset() function returns undefined in the event that the selector matches zero elements, which appears to be the case here due to the error you're getting later on.
On the next line you're selecting an element with an id of sticky-header, which makes me think that perhaps your first line should be
var offset = $('#sticky-header').offset();
instead, which uses an ID selector rather than a class one.

JS: Applying focus effect on an element when scrolled to

Here is the fiddle: http://jsfiddle.net/fz5Yk/5/
All I want to achieve is to highlight (e.g adding a background color) the heading (in <strong> </strong> tag) of the section-3 when I scroll to section-3.
I'd like to know if there's a way for me to trigger certain events when I'm at a certain section. There must be a thing for this because when you scroll the page manually, you'll notice that, in the navigation menu, link to the section gets selected automatically, as if it was clicked.
Anything helpful will be much appreciated as I've been working on this since yesterday and hav yet to solve it.
There isn't any way to achieve this using CSS, so I edited the jquery.nav.min.js. (added only 4 lines) It works great now. http://jsfiddle.net/fz5Yk/10/
adjustNav=function(a,b,d){
var sec = a.find("."+d+">a").attr("href");
$(sec+">strong").css('background','none'); //Find and remove previous highlight of strong
a.find("."+d).removeClass(d);b.addClass(d); //ORIGINAL
sec = b.find("a").attr("href");
$(sec+">strong").css('background','aqua'); //Find and highlight the strong
};
EDIT: Animation added by request:
http://jsfiddle.net/fz5Yk/11/
add animateSomething function on top:
function animateSomething(sec) {
if(sec == "#section-2")
$("#testBlock").animate({
width:"50%",
opacity:0.5
}, 1500);
}
add animateSomething(sec); at the end of adjustNav function.
Voila!
EDIT FINAL: Animate AFTER scroll ends http://jsfiddle.net/fz5Yk/12/
In your click action have something like this:
$("#container .section strong").css('background-color', 'transparent');
$("#container .section strong:contains('" + $(this).text() + "')").css('background-color', 'yellow');
Not sure if that's what you want exactly, but you could use this to add a class to the every strong which is currently in view:
$(document).scroll(function(){
var t = $(this).scrollTop();
var b = t + $(this).height();
$('.section>strong').removeClass('highlight').filter(function(){
var ot = $(this).position().top;
return ot > t && ot < b;
}).addClass('highlight');
});
http://jsfiddle.net/fz5Yk/7/
But it is a bit pointless in my opinion because when it's not in view why do you want to remove the highlight? It won't be visible anyway!?
If you really only want the functionality for section 3 you could change $('.section>strong') to $('#section-3>strong')

Categories

Resources