localscroll active link url recognition - javascript

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

Related

Clicking a Bootstrap Nav Tab won't scroll to Tab Pane - jQuery / Bootstrap

I have some Bootstrap vertical tabs that I'm struggling with what I felt like would be a simple operation.
Goal:
On the click of Tab, I want to smooth-scroll to the corresponding pane.
What's Actually Happening:
On click of the tab, the browser animates to the tab, not the tab pane. I've tried passing in the paneId instead of the ID, but that doesn't work at all. Any idea where I'm going wrong?
Codepen:
Here's a Codepen: Codepen!
jQuery:
$("#tabs .nav-link").click(function (e) { //on click of nav tav, perform this:
var id = $(e.target).prop("id"); //Grab ID of .nav-link clicked
var paneId = id.replace("tab", "pane"); //Replace "tab" with "pane" and assign new var
function navigateToElement(id) {
$("html, body").animate(
{
scrollTop: $("#" + id).offset().top
},
300
);
}
navigateToElement(id); //Tried with "paneId" instead of "id" to scroll to the pane, but doesn't work
});
Any idea where I'm going wrong?
This line:
var paneId = id.replace("tab", "pane"); //Replace "tab" with "pane" and assign new var
Is creating a variable like: v-pills-profile-pane and there isn't a div on the page with that id. I did see a div with id="v-pills-profile". Change that last line to this and it should work:
var paneId = id.replace("-tab", "");
I just realized that it doesn't matter what pane I scroll to, as bootstrap will display the panes under #panes. As long as I can scroll to that, I'm good. This code worked:
$("#tabs .nav-link").click(function (e) {
var target = $("#panes");
$([document.documentElement, document.body]).animate(
{
scrollTop: $(target).offset().top - 20, // added a bit of offset
},
350
);
});

How to keep class active when scrolling with javascript?

I need help figuring out what is going on with my javascript. I have some code that is supposed to make the nav links have an active class when you are on that part of the page, but it's only sort of working for a couple links and it also flickers as you scroll rather than staying active the whole time you're on that part of the page. See the JSFiddle for an example https://jsfiddle.net/7szpuqsr/ -- if you scroll slowly you can see how "home" becomes active for a moment. I am trying to get each link to have the active class when you click it and also while you are on that entire part of the page.
I also have a javascript sticky nav bar and smooth scrolling working so I don't know if possibly any of that is getting in the way? Thanks in advance for help.
Here's the Javascript I'm trying to use for the active class:
var sections = $('section')
, nav = $('nav')
, nav_height = nav.outerHeight();
$(window).on('scroll', function () {
var cur_pos = $(this).scrollTop();
sections.each(function() {
var top = $(this).offset().top - nav_height,
bottom = top + $(this).outerHeight();
if (cur_pos >= top && cur_pos <= bottom) {
nav.find('a').removeClass('active');
sections.removeClass('active');
$(this).addClass('active');
nav.find('a[href="#'+$(this).attr('id')+'"]').addClass('active');
}
});
});
nav.find('a').on('click', function () {
var $el = $(this)
, id = $el.attr('href');
$('html, body').animate({
scrollTop: $(id).offset().top - nav_height
}, 500);
return false;
});
Something like this? I couldn't reproduce the flickering visually on my machine but I can see the class being removed/added constantly on scroll
https://jsfiddle.net/7szpuqsr/1/
Main changes, I added a class to your sections, you have too many sections but with the way your code is meant to work, it's much easier to add a class to the sections, example below
<section id="home" class="section">
var sections = $('.section') to get the section class
updated this part of the js to check for active class
if (cur_pos >= top && cur_pos <= bottom) {
if(!$(this).hasClass("active")) {
nav.find('a').removeClass('active');
sections.removeClass('active');
$(this).addClass('active');
nav.find('a[href="#'+$(this).attr('id')+'"]').addClass('active');
}
}
You can also cache the $(this) into a variable inside of the section loop like
var $this = $(this);
then just use $this for the rest of the loop
here is the doc for hasClass https://api.jquery.com/hasclass/

Replacing Bootstrap Dropdown with Dropup (Different activity on two near identical implementations)

I'm working on a project over at github pages, which I replace a bootstrap .dropdown with .dropup if the div's overflow-y: scroll will cause the dropdown menu to be cutoff / overflow. You can see the function working properly at this jsfiddle. Notice if you click on the ellipsis icon to the right on the top rows, it will drop down, if you click on the icon on the bottom rows, it will drop up.
Now, my actual implementation (github page), the code is exactly the same (below), but it wants to replace all .dropdown classes with .dropup when opened, including the top-most row which gets cut off, seen in the photo below.
I've been struggling with this for a week and can't quite figure it out. I've tried a few different things that I thought fixed it but ended up just being a hack and didn't work on mobile, or replaced some but not all etc.
Here is the Javascript / jQuery I'm using, which can be seen in the jsfiddle and my github source here.
$(document).on("shown.bs.dropdown", ".dropdown", function () {
// calculate the required sizes, spaces
var $ul = $(this).children(".dropdown-menu");
var $button = $(this).children(".song-menu");
var ulOffset = $ul.offset();
// how much space would be left on the top if the dropdown opened that direction
var spaceUp = (ulOffset.top - $button.height() - $ul.height()) - $('#playlist').scrollTop();
// how much space is left at the bottom
var spaceDown = $('#playlist').scrollTop() + $('#playlist').height() - ((ulOffset.top + 10) + $ul.height());
// switch to dropup only if there is no space at the bottom AND there is space at the top, or there isn't either but it would be still better fit
if (spaceDown < 0 && (spaceUp >= 0 || spaceUp > spaceDown))
$(this).addClass("dropup");
}).on("hidden.bs.dropdown", ".dropdown", function() {
// always reset after close
$(this).removeClass("dropup");
});
Edit:
To clear up any confusion, here's an example of the behavior without my added .dropup function. jsfiddle Notice when you click the last menu item, it opens the menu but requires scrolling. I specifically want to remove the .dropdown class and add .dropup in this case, so no scrolling is required.
It took some basic math, but I managed to figure out what you desired to do. This code changes the bootstrap classes between dropup and dropdown depending on the room available for a normal dropdown.
I calculated this by detracting the height of the button, dropdownmenu and how far the button was scrolled down in the scrollContainer from the height of the scrollContainer. I got the value how much the div was scrolled down by using the buttons offset and detracting the offset from the scrollContainer.
Here is my jQuery (I selected the .playlist class because this was attached to your scrollContainer, but you should replace it by an id or select it by other means):
$(".dropdown, .dropup").click(function(){
var dropdownClassCheck = $(this).hasClass('dropdown');
var buttonOffset = $(this).offset().top;
var scrollboxOffset = $('.playlist').offset().top;
var buttonHeight = $(this).height();
var scrollBoxHeight = $('.playlist').height();
var dropDownButtonHeight = $(this).children('ul').height();
dropdownSpaceCheck = scrollBoxHeight>buttonOffset-scrollboxOffset+buttonHeight+dropDownButtonHeight;
if(dropdownClassCheck && !dropdownSpaceCheck){
$(this).removeClass('dropdown').addClass('dropup');
}
else if(!dropdownClassCheck && dropdownSpaceCheck){
$(this).removeClass('dropup').addClass('dropdown');
}
});
A working JSFiddle
Let me know if there are parts of the code that could be improved/done easier or if there are any problems with my solution.
I have not thoroughly checked, but .scrollTop() is probably why the code fails when combined with other elements in the DOM, so here is a solution without it:
function checkHeights(){
// LOOP through each dropdown
$('.dropdown,.dropup').each(function(index,element){
var $dropDown = $(element),
$dropDownMenu = $dropDown.find('.dropdown-menu'),
dropDownTop = $dropDown.offset().top,
visibleHeight = $dropDown.height(),
hiddenHeight = $dropDownMenu.height(),
ddTop = dropDownTop - hiddenHeight,
ddBottom = dropDownTop + visibleHeight + hiddenHeight;
// LOOP through all parents
$dropDown.parents().each(function(ix,el){
var $el = $(el);
// CHECK if any of them have overflow property set
if( $el.css('overflow') !== 'visible' ){
var limitTop = $el.offset().top,
limitBottom = limitTop + $el.height();
// CHECK if parent is better fit when dropped upside
if( limitBottom < ddBottom && ( ddTop - limitTop ) > ( limitBottom - ddBottom ) )
$dropDown.removeClass('dropdown').addClass('dropup');
else
$dropDown.removeClass('dropup').addClass('dropdown');
// BREAK LOOP
return false;
}
});
});
}
$(document).ready(function() {
checkHeights();
$('.playlist').scroll(checkHeights);
});
JS Fiddle here.
This one does not require any class or id given to it except for dropdown,dropdown-menu, and dropup (all of which are Bootstrap defaults) and would work fine even if there are multiple playlists on page.
UPDATE
The code is modified and wrapped in a function in order to allow being called when scroll event fires.
I think that the problem it's that you have a big header, and the jsFiddle don't. So ulOffset.top it's always big, and spaceDown is always negative
Replace parent div.dropdown with div.dropup.

Updating the class name of Div based on top position

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/

Image highlight (hover state) on active section while scrolling?

I have these icons above each section on my page (the largish circular icons, please see example: http://pftest.fhero.net) with colored hover states... what I would really love to do is have them change to the active hover states as the user scrolls to each section (preferably with a simple fade transition) - much like the effect of highlighting the active links/section in the navigation.
There are many tutorials, plugins and questions on this site and so forth for highlighting active sections in a navigation however, but doesn't seem to be much that I can find relating to applying the effect to another div or image on the page...
I'm definitely not any kind of jQuery expert but I'm wondering if one of the myriad of scripts/plugins available which are typically used for highlighting active states in navigation could simply be adapted to this scenario somehow to achieve the same effect? Perhaps even the one I am currently using on my page?
Here is the script I'm using for highlighting the active section in the navigation on my page:
/* Scroll Navigation highlight */
$("#work-section1").parent().addClass('active');
var main = main = $('#mainmenu ul');
$('.scroll').click(function(event) {
event.preventDefault();
var full_url = this.href,
parts = full_url.split('#'),
trgt = parts[1],
target_offset = $('#'+trgt).offset(),
target_top = target_offset.top;
$('html, body').animate({scrollTop:target_top}, 500);
/* Remove active class on any li when an anchor is clicked */
main.children().removeClass();
/* Add active class to clicked anchor's parent li */
$(this).parent().addClass('active');
});
$(window).scroll(function(event) {
if($("#work-section").offset().top < $(window).scrollTop() + $(window).outerHeight()){
$("#work-section1").parent().addClass('active');
$("#about-section1").parent().removeClass('active');
$("#footer-section").parent().removeClass('active');
$("#services-section1").parent().removeClass('active');
$("#process-section1").parent().removeClass('active');
}
if($("#about-section").offset().top < $(window).scrollTop() + $(window).outerHeight()) {
$("#about-section1").parent().addClass('active');
$("#work-section1").parent().removeClass('active');
$("#footer-section1").parent().removeClass('active');
$("#services-section1").parent().removeClass('active');
$("#process-section1").parent().removeClass('active');
}
if($("#services-section").offset().top < $(window).scrollTop() + $(window).outerHeight()){
$("#services-section1").parent().addClass('active');
$("#about-section1").parent().removeClass('active');
$("#work-section1").parent().removeClass('active');
$("#footer-section1").parent().removeClass('active');
$("#process-section1").parent().removeClass('active');
}
if($("#process-section").offset().top < $(window).scrollTop() + $(window).outerHeight()){
$("#process-section1").parent().addClass('active');
$("#about-section1").parent().removeClass('active');
$("#work-section1").parent().removeClass('active');
$("#footer-section1").parent().removeClass('active');
$("#services-section1").parent().removeClass('active');
}
if($("#footer-section").offset().top < $(window).scrollTop() + $(window).outerHeight()){
$("#footer-section1").parent().addClass('active');
$("#about-section1").parent().removeClass('active');
$("#work-section1").parent().removeClass('active');
$("#services-section1").parent().removeClass('active');
$("#process-section1").parent().removeClass('active');
}
});
and the HTML:
<nav id="mainmenu" name="mainmenu">
<ul>
<li><a class="scroll" id="work-section1" href="#work-section">Works</a></li>
<li><a class="scroll" id="about-section1" href="#about-section">About</a></li>
<li><a class="scroll" id="services-section1" href="#services-section">Services</a></li>
<li><a class="scroll" id="process-section1" href="#process-section">Process</a></li>
<li><a class="scroll" id="footer-section1" href="#footer-section">Contact</a></li>
</ul>
</nav>
<section id="about-section" data-anchor-offset="90">
<section id="work-section" data-anchor-offset="90">
...ect...
Could this somehow be adapted to accomplish the effect I am looking for? Or any other/better methods, or plugins I should be looking at?
I should add that the icons use the sprites method which could make the CSS side of things a little trickier, although I would be willing to change them to non-sprite images if necessary...
You could use a small little function for this, that checks if a element is on screen. I set up a little JSFiddle for you: http://jsfiddle.net/LHrkB/1/
Code:
function isElementVisible(elementToBeChecked)
{
var TopView = $(window).scrollTop();
var BotView = TopView + $(window).height();
var TopElement = $(elementToBeChecked).offset().top;
var BotElement = TopElement + $(elementToBeChecked).height();
return ((BotElement <= BotView) && (TopElement >= TopView));
}
$(window).scroll(function () {
isOnView = isElementVisible(".inview");
if(isOnView){
//What to do when element is visible
$(".inview").css({"background":"#ccc"});
}else{ // If not visible
}
});
Ok, so i have changed the JSFiddle a bit, now it uses a fadeIn on a invisible element when it comes into view: http://jsfiddle.net/LHrkB/2/
Ok, i changed the JSFiddle once again. When you scroll in the results pane, and you play around with it a bit you can see the element change class as it comes on screen and also when it goes away again. I commented the JS so you can see what it does and where it does it. http://jsfiddle.net/LHrkB/4/
Thanks to the help of Veritas87 (who is super awesome), managed to get it all working with the following code:
function isElementVisible(elementToBeChecked)
{
var TopView = $(window).scrollTop();
var BotView = TopView + $(window).height();
var TopElement = $(elementToBeChecked).offset().top;
var BotElement = TopElement + $(elementToBeChecked).height();
return ((BotElement <= BotView) && (TopElement >= TopView));
}
$(window).scroll(function () {
isOnView = isElementVisible(".about-icon");
if(isOnView){
//What to do when element is visible
$('.about-icon').addClass('about-icon-active');
}else{ // If not visible
$('.about-icon').removeClass('about-icon-active');
}
isOnView = isElementVisible(".works-icon");
if(isOnView){
//What to do when element is visible
$('.works-icon').addClass('works-icon-active');
}else{ // If not visible
$('.works-icon').removeClass('works-icon-active');
}
isOnView = isElementVisible(".services-icon");
if(isOnView){
//What to do when element is visible
$('.services-icon').addClass('services-icon-active');
}else{ // If not visible
$('.services-icon').removeClass('services-icon-active');
}
isOnView = isElementVisible(".process-icon");
if(isOnView){
//What to do when element is visible
$('.process-icon').addClass('process-icon-active');
}else{ // If not visible
$('.process-icon').removeClass('process-icon-active');
}
});
with the "...icon-active" classes of course containing the style for the icon hover states.

Categories