Updating the class name of Div based on top position - javascript

Actually i am trying to achieve smooth scrolling in Jquery, and whatever code i have written seems to be working fine, but i also want to implement a feature where my Nav Class Changes to active when user scroll down/up based on the position. Below link to code will give you more idea on what i am talking about. problem i am facing is even though i click on the next nav sub element active class is set to previous element. i have user window.scroll of query infact this part is actually got it from net. i really dint understand the code that is why its hard fa me debug and fix it, so if anyone is able to fix it, it would be really good if you explain me what this code is actually doing and what is the problem with current implementation.
http://codepen.io/anon/pen/GqJmK
JS
$(document).ready(function(){
var lastId,
header = $("#header"),
topMenu = $("#nav"),
topMenuHeight = topMenu.outerHeight()+header.outerHeight()+25,
menuItems = topMenu.find("a"),
//menuItems = topMenu.find("a:not([href^='http://'],[href^='/'])"),
scrollItems = menuItems.map(function(){
var item = $($(this).attr("href"));
if (item.length) { return item; }
});
menuItems.on('click',function (e) {
e.preventDefault();
_this = this;
var target = _this.hash,
$target = $(target);
//menuItems.parent().removeClass("active");
//$(_this).parent().addClass("active");
$('html, body').stop().animate({
'scrollTop': ($target.offset().top) - topMenuHeight + 1
}, 900, 'swing', function () {
window.location.hash = target;
});
});
$(window).scroll(function(){
var fromTop = $(this).scrollTop()+topMenuHeight;
var cur = scrollItems.map(function(){
if (($(this).offset().top +20)< fromTop){
return this;
}
});
cur = cur[cur.length-1];
var id = cur && cur.length ? cur[0].id : "";
if (lastId !== id) {
lastId = id;
menuItems
.parent().removeClass("active")
.end().filter("[href=#"+id+"]").parent().addClass("active");
}
});
/*$( window ).resize(function() {
alert($( window ).width());
alert($( document ).width());
}); */
});

You might be best off using some sort of a plugin to achieve this effect. Something like http://lirancohen.github.io/stickUp/ or http://www.outyear.co.uk/smint/demo/ would do the trick

Just update your scroll check function & make your position check little more flexible i.e let it consider that you entered a section little before it enters it. Make this change on line 35 in your code -
if (($(this).offset().top - 50)< fromTop)
WORKING DEMO - http://codepen.io/nitishdhar/pen/LEAzI
You can also improve your UI by implementing this - http://css-tricks.com/hash-tag-links-padding/

Related

Show id when div is halfway up

So I know how to actually get ids and classes and do the basics but I'm not sure how to do this:
"When the user scrolls down, the title of the post that takes up half the screen should be shown."
The setup is supposed to look something like this...
Any ideas?
You need to use JS and I used jQuery to do a simple prototype
It's all about listening to the scroll event and dealing with the offset of the elements from top you need to add a simple condition for the heights but now it's just working fine
$(window).scroll(function(){
var scrolledTop = $(this).scrollTop();
console.log(scrolledTop);
$(".blog").each(function(){
if($(this).offset().top < scrolledTop)
{
$('#blogname').html($(this).html());
}
});
});
Check out this http://jsfiddle.net/GkrCU/2/
I hope this can help :)
Here is my answer
$(window).scroll(function () {
var windowheight = $(this).scrollTop();
$(".blog").each(function () {
var sc = $(this).offset().top;
var id = $(this).attr('id');
if (sc < windowheight) {
$("#blogname span").html(id)
}
});
});
http://jsfiddle.net/GkrCU/1/

Scrolling to Div IDs with Jquery

Due to css properties my scrolling to div tags has too much margin-top. So I see jquery as the best solution to get this fixed.
I'm not sure why this isn't working, I'm very new to Js and Jquery. Any help us greatly appreciated.
Here is a quick look at Js. I found that when your div ids are in containers to change the ('html, body') to ('container)
Here is my jsfiddle
jQuery(document).ready(function($){
var prevScrollTop = 0;
var $scrollDiv = jQuery('div#container');
var $currentDiv = $scrollDiv.children('div:first-child');
var $sectionid = 1;
var $numsections = 5;
$scrollDiv.scroll(function(eventObj)
{
var curScrollTop = $scrollDiv.scrollTop();
if (prevScrollTop < curScrollTop)
{
// Scrolling down:
if ($sectionid+1 > $numsections) {
console.log("End Panel Reached");
}
else {
$currentDiv = $currentDiv.next().scrollTo();
console.log("down");
console.log($currentDiv);
$sectionid=$sectionid+1;
console.log($currentDiv.attr('id'));
var divid =$currentDiv.attr('id');
jQuery('#container').animate({scrollTop:jQuery('#'+divid).position().top}, 'slow');
}
}
else if (prevScrollTop > curScrollTop)
{
// Scrolling up:
if ($sectionid-1 == 0) {
console.log("Top Panel Reached");
}
else {
$currentDiv = $currentDiv.prev().scrollTo();
console.log("up");
console.log($currentDiv);
$sectionid=$sectionid-1;
var divid =$currentDiv.attr('id');
jQuery('html, body').animate({scrollTop:jQuery('#'+divid).position().top}, 'slow');
}
}
prevScrollTop = curScrollTop;
});
});
I'm not entirely sure what you want but scrolling to a <div> with jQuery is simpler than your code.
For example this code replaces the automatic jumping behaviour of anchors with smoother scrolling:
$(document).ready(function(e){
$('.side-nav').on('click', 'a', function (e) {
var $this = $(this);
var top = $($this.attr('href')).offset().top;
$('html, body').stop().animate({
scrollTop: top
}, 'slow');
e.preventDefault();
});
});
You can of course adjust the top variable by adding or removing from it like:
var top = $($this.attr('href')).offset().top - 10;
I have also made a fiddle from it (on top of your HTML): http://jsfiddle.net/Qn5hG/8/
If this doesn't help you or your question is something different, please clarify it!
EDIT:
Problems with your fiddle:
jQuery is not referenced
You don't need jQuery(document).ready() if the jQuery framework is selected with "onLoad". Remove the first and last line of your JavaScript.
There is no div#container in your HTML so it's no reason to check where it is scrolled. And the scroll event will never fire on it.
Your HTML is invalid. There are a lot of unclosed elements and random tags at the end. Make sure it's valid.
It's very hard to figure out what your fiddle is supposed to do.

localscroll active link url recognition

Via localscroll and scrollto i built a horizontal sliding page (Environment) also adds hashes to the url. example: when clicking a link in the nav from localScroll it adds the hash in the url (index.html#media).
Now via Localscroll there is no active link support and i wanted to add that and found some solutions here: Stackoverflow
i was happy but then i tried to reload the page and when the user is, for example in the media section, there is no support for recognition of the url and it doesnt add the selected class to the nav link that is currently selected in the url.
so i did more research and found that site: Website
great but it didnt work for my horizontal setup.
i barely started my knowledge about javascript and i even don't know how to jquery at all so i modified the script with my logic and went so far:
i adds the class, even when i scroll via the mousewheel it nicely add the class to all nav links. BUT: it doesn't remove them.
<script style="text/javascript">
$(function(){
var sections = {},
_width = $(window).width(),
i = 0;
// Grab positions of our sections
$('.section').each(function(){
sections[this.name] = $(this).offset().left;
});
$(document).scroll(function(){
var $this = $(this),
pos = $this.scrollLeft();
for(i in sections){
if(sections[i] > pos && sections[i] < pos + _width){
$('#nav ul li a').removeClass('selected');
$('#nav_' + i).addClass('selected');
}
}
});
});
$(".scroll").click(function(event){
event.preventDefault();
var full_url = this.href;
var parts = full_url.split("#");
var trgt = parts[1];
var target_offset = $("#"+trgt).offset();
var target_top = target_offset.left;
$('html, body').animate({scrollLeft:target_top}, 800);
});
</script>
How to update the links so it removes the selected class?
Edit: i think i'm close
i think it needs changes in the for header
if(sections[i] > pos && sections[i] < pos + _width)
What are the needed changes to assign the class "selected" to the current viewed slide

How to Set Offsett for Smooth Scroll

I have implemented the CSS Tricks Smooth Page Scroll on my site and it's working pretty nicely. However, because I have a fixed nav at the top of the page, when the page scrolls to the appropriate anchor div, the top of the div disappears behind the nav. How can I offset the scroll (about 70px) so that the whole div is shown? I tried doing this:
var targetOffset = $target.offset().top - 70;
But that doesn't quite work. The page scrolls to the appropriate spot but then it immediately jumps back up so that the top of the div is hidden. What am I missing? Here's the code in full:
$(function() {
function filterPath(string) {
return string
.replace(/^\//,'')
.replace(/(index|default).[a-zA-Z]{3,4}$/,'')
.replace(/\/$/,'');
}
var locationPath = filterPath(location.pathname);
var scrollElem = scrollableElement('html', 'body');
// Any links with hash tags in them (can't do ^= because of fully qualified URL potential)
$('a[href*=#]').each(function() {
// Ensure it's a same-page link
var thisPath = filterPath(this.pathname) || locationPath;
if ( locationPath == thisPath
&& (location.hostname == this.hostname || !this.hostname)
&& this.hash.replace(/#/,'') ) {
// Ensure target exists
var $target = $(this.hash), target = this.hash;
if (target) {
// Find location of target
var targetOffset = $target.offset().top - 70;
$(this).click(function(event) {
// Prevent jump-down
event.preventDefault();
// Animate to target
$(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
// Set hash in URL after animation successful
location.hash = target;
});
});
}
}
});
// Use the first element that is "scrollable" (cross-browser fix?)
function scrollableElement(els) {
for (var i = 0, argLength = arguments.length; i <argLength; i++) {
var el = arguments[i],
$scrollElement = $(el);
if ($scrollElement.scrollTop()> 0) {
return el;
} else {
$scrollElement.scrollTop(1);
var isScrollable = $scrollElement.scrollTop()> 0;
$scrollElement.scrollTop(0);
if (isScrollable) {
return el;
}
}
}
return [];
}
});
Thanks in advance for your help.
This always happens. I search and search for an answer, get frustrated, post a question asking for help, and then immediately find an answer to my problem. Silly. Anyway, here's the solution for anyone who might be having the same problem.
If you want to change the offset by 70px, for example, change the code to this:
var targetOffset = $target.offset().top - 70;
However, unless you remove this line from the code...
location.hash = target;
... the page will scroll to the right spot and then immediately jump back up so that the top of the div is hidden behind the header. You can remove the above line from the code and everything will work great, except for the fact that the URL will no longer change to reflect the user's position on the page.
If you want the URL to change (and I think this is a good idea for usability purposes), then all you have to do is change the CSS for the anchor divs. Add a positive value for padding-top and a negative value for margin-top. For example:
#anchor-name {
padding-top: 70px;
margin-top: -70px;
}
I only have 3 divs, so I just plugged in that CSS to each of them and voila, everything worked. However, if you have a lot of anchor divs, you might consider creating a class of .anchor, putting the CSS there, and applying the class to all the appropriate divs.
I hope this helps!
I have fixed such a kind of issue with below code:
Working demo HERE. You can play with "Post Topics" section in the sidebar and content in the main-content area.
Code
jQuery(function() {
jQuery('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = jQuery(this.hash);
target = target.length ? target : jQuery('[name=' + this.hash.slice(1) +']');
if (target.length) {
jQuery('html,body').animate({
scrollTop: target.offset().top -100
}, 1000);
return false;
}
}
});
});
Refer to https://codepen.io/pikeshmn/pen/mMxEdZ
Approach: We get the height of fixed nav using document.getElementById('header').offsetHeight
And offset the scroll to this value.
var jump=function(e){
e.preventDefault(); //prevent "hard" jump
var target = $(this).attr("href"); //get the target
//perform animated scrolling
$('html,body').animate(
{
scrollTop: $(target).offset().top - document.getElementById('header').offsetHeight - 5 //get top-position of target-element and set it as scroll target
},1000,function() //scrolldelay: 1 seconds
{
location.hash = target; //attach the hash (#jumptarget) to the pageurl
});
}
$(document).ready(function()
{
$('a[href*="#"]').bind("click", jump); //get all hrefs
return false;
});
Actually there's a CSS rule for that : scroll-padding-top :)
Combined with a regular padding-top for the top-most element of course.
cf. https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-padding-top
CSS scroll margin or padding
/* Scroll to 2rem above the target */
:target {
scroll-margin-top: 2rem;
}
/* Bonus for a smooth scrolling experience */
body {
scroll-behavior: smooth;
}
Read more about scroll margin and scroll padding on MDN.

Capture first visible div id while scrolling (viewport)

I have this page:
I want to capture on which div I am while I'm scrolling.
I know If I use:
if( $(document).scrollTop() > $('#div1').position().top) {
console.log('Div1')
}
...it will capture the div1 but instead of using this code for every div I want to set 1 snippet for all divs
Something like:
var a = // The div i am at
if( $(document).scrollTop() > $(a).position().top) {
console.log($(a).attr('id'))
}
I am looking something like the viewport: http://www.appelsiini.net/projects/viewport/3x2.html
Can I achieve that without a plugin, simply 2-3 lines?
Here's a nice way to do it. You may want to optimize the '<=' with a pixel offset to improve user experience and move the div selector ($divs) outside the callback to increase performance. Have a look at my fiddle: http://jsfiddle.net/brentmn/CmpEt/
$(window).scroll(function() {
var winTop = $(this).scrollTop();
var $divs = $('div');
var top = $.grep($divs, function(item) {
return $(item).position().top <= winTop;
});
});
Just throw it into a loop.
var list = [];
$("div").each(function(index) {
if( $(document).scrollTop() > $(this).position().top)
list.push($(this));
});
alert(list);
The list will than have every div that is within your viewport.
I'd suggest using the jQuery Inview plugin:
https://github.com/protonet/jquery.inview
Well maintained Plugin that detects whatever content is in the viewer currently, enabling you to bind functions to an inview event. So as soon as your div is in view you could fire off all the relevant functions you wanted and then again when it has left the users view. Would be great for your needs.
$(window).scroll(function () {
$("#privacyContent div").each(function () {
var bottomOffset = ($(this).offset().top + $(this).height());
console.log("Botom=",bottomOffset ,"Win= ", $(window).scrollTop());
if (bottomOffset > $(window).scrollTop()) {
$("#menu a").removeClass("active");
// console.log("Div is= ",$(this).attr('id'));
$("#menu a[href='#" + $(this).attr('id') + "']").addClass("active");
$(".b").removeClass("fsActive");
var div = $(this);
div.find(".b").addClass("fsActive");
return false;
}
});
});
I do it like this it works fine it detect all div id

Categories