PDA

View Full Version : Adding a class to a navigation menu



FrickenTrevor
08-03-2016, 08:07 AM
May not be exactly what the title of this thread is, but it is the best I can sum it up. Anyways, I have a few lines of jQuery that takes a navbar and as the user scrolls down the page, the navbar changes to reflect where on the page the user is (example here (http://jsfiddle.net/gUWdJ/3/)). The code that is highlighted is what I am having trouble with. My goal is to get the navbar to stick to the page after the user scrolls down for a set amount of pixels.

Also on a side note, if you see anything that needs to be improved go ahead and provide feedback.



var sections = $('section')
, nav = $('nav')
, nav_height = nav.outerHeight();
$(window).scroll(function() {
var cur_pos = $(this).scrollTop();
if (cur_pos >= 300) {
$('nav').addClass('stickme');
}
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;
});

FrickenTrevor
08-05-2016, 12:08 AM
The problem is I cant get the nav bar to stick after the user scrolls about 300 pixels down the page. Basically it should start as an un-static element then dynamically gets changed to a fixed element, if that makes sense.

Here's an example (http://jsfiddle.net/gUWdJ/3/), of what I am trying to achieve. Just not having to rely on the data-scroll html tag and more efficient.

FrickenTrevor
08-07-2016, 02:40 AM
Anyone out there? This is still an issue I have.

jscheuer1
08-07-2016, 04:33 PM
Alright, I didn't get it before, because the 'demo' you linked to seems to work fine. I realize now, that's not your demo, or at least not the current one. I still don't completely get it. Is your problem that the menu doesn't become fixed? Is it that when you click on a menu item the page doesn't scroll to the desired section? Or is it both? In any case, I don't see any crucial errors in the code, just minor issues with efficiency that shouldn't affect its working or not. That said, there are things in the code that depend upon certain css styles being set as implied they'd need to be in a stylesheet somewhere on or available to the page. Conflicting styles might be at work as well. The code also depends upon markup and attributes within that markup being as expected and being valid. There are also incidental things that might be missing - like jQuery, etc. I can't see any of that right now, care to show us the full demo page? If not, I would suggest first check the error console. Next doing console dumps (logging) at strategic points in the code to determine if the expected values (strings and numbers) have been obtained. Next validate the markup, and then systematically remove anything non-essential one thing at a time to see if there are any conflicts. Really - just all the usual things.

The easiest thing though would be for us to have a link to the actual page.

FrickenTrevor
08-07-2016, 07:24 PM
Is your problem that the menu doesn't become fixed?
Exactly. The class .stickme does not get added to the nav after the user scrolls down 300 pixels. The only property of said class is position: fixed; Other than the class issues the code is perfectly fine with no errors.
I will PM you a link to the page if needed.

jscheuer1
08-07-2016, 08:43 PM
I think I would need to see that (link to the page, please PM it to me), because I agree - from what you're saying it seems mysterious.

jscheuer1
08-11-2016, 03:28 AM
Got tired of waiting, try this:


<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
body {
padding: 0;
margin: 0
}

header {
background: green url('http://adventure.nationalgeographic.com/2008/11/ecotourism/lodge-jungle.jpg') 0 0;
height: 300px;
}

h4 {
font-weight: bold;

}

p {
margin: 20px 0;
}

section {
padding: 20px 0;
}

.wrapper {
width: 400px;
margin: 0 auto;
position: relative;
padding: 28px 0 0 0;
}

nav {
position: absolute;
left: 0;
right; 0;
top: 300px;
background: green;
display: block;
width: 100%;
padding: 4px 0;
height: 30px;
z-index: 100;
}

nav a {
font-family: helvetica;
color: #ffffff;
padding: 2px; 4px;
display: block;
float: left;
text-decoration: none;
margin-right: 4px;
}

nav a:hover,
nav a.active {
background: white;
color: green
}

.stickme {
position: fixed;
top: 0
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function($){
var sections = $('section'), nav = $('nav'), nava = nav.find('a'), nav_height = nav.outerHeight(),
top_height = $('#top').outerHeight(), running = false, stick_limit = 300, active_idx = 0;
function updateActive(num){
nava.removeClass('active');
nava.eq(num).addClass('active');
}
$(window).scroll(function() {
var cur_pos = $(this).scrollTop(), stuck = nav.hasClass('stickme');
if (!stuck && cur_pos >= stick_limit) {
nav.addClass('stickme');
} else if (stuck && cur_pos < stick_limit) {
nav.removeClass('stickme');
}
if(!running){
sections.each(function(i, s) {
var top = $(s).offset().top - nav_height, bottom = top + $(s).outerHeight(),
idx = cur_pos <= top_height + nav_height? 1 :
cur_pos >= top && cur_pos <= top + 2 * nav_height? i + 1 :
cur_pos > top && cur_pos <= bottom && idx !== sections.length? i + 2 :
0;
idx && active_idx !== idx && updateActive(idx - 1);
active_idx = idx;
});
}
});
nava.on('click', function(e) {
running = true;
var el = $(this), id = el.attr('href');
updateActive(el.index());
$('html, body').animate({
scrollTop: $(id).offset().top - nav_height
}, 500, function(){running = false;});
e.preventDefault();
});
});
</script>
</head>
<body>
<header id="top"></header>

<nav>

<a href="#top" class="active">TOP</a>

<a href="#news">NEWS</a>

<a href="#products">PRODUCTS</a>

<a href="#contact">CONTACT</a>

</nav>

<div class="wrapper">

<section>

<h4>TOP</h4>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque feugiat eleifend orci, eget aliquam dolor elementum vel. Aliquam eu nulla eros, et tincidunt felis. Pellentesque congue sodales eleifend. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nulla suscipit nulla vel nisi fermentum ultricies. Integer ligula elit, gravida ac pretium nec, eleifend ultrices purus. Duis cursus orci et urna accumsan tempor. Nunc mattis tincidunt nulla, id porta velit sollicitudin blandit.</p>

<p>Duis vel augue quis elit ultrices fermentum ut eu risus. Mauris dictum nisl eget lorem pulvinar sit amet bibendum nunc scelerisque. Suspendisse ac libero magna, at imperdiet leo. Pellentesque vulputate venenatis vestibulum. Aenean varius turpis quis sem adipiscing volutpat. Fusce scelerisque iaculis augue, eget fringilla velit mattis nec. Maecenas sagittis dolor eget felis cursus imperdiet. Morbi ut dui libero. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sit amet mi ac diam semper hendrerit a id tellus. Morbi accumsan magna sit amet velit ultricies ut dapibus justo rutrum. Ut et ante dui, vel pellentesque velit.</p>

</section>

<section id="news">

<h4>NEWS</h4>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque feugiat eleifend orci, eget aliquam dolor elementum vel. Aliquam eu nulla eros, et tincidunt felis. Pellentesque congue sodales eleifend. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nulla suscipit nulla vel nisi fermentum ultricies. Integer ligula elit, gravida ac pretium nec, eleifend ultrices purus. Duis cursus orci et urna accumsan tempor. Nunc mattis tincidunt nulla, id porta velit sollicitudin blandit.</p>

<p>Duis vel augue quis elit ultrices fermentum ut eu risus. Mauris dictum nisl eget lorem pulvinar sit amet bibendum nunc scelerisque. Suspendisse ac libero magna, at imperdiet leo. Pellentesque vulputate venenatis vestibulum. Aenean varius turpis quis sem adipiscing volutpat. Fusce scelerisque iaculis augue, eget fringilla velit mattis nec. Maecenas sagittis dolor eget felis cursus imperdiet. Morbi ut dui libero. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sit amet mi ac diam semper hendrerit a id tellus. Morbi accumsan magna sit amet velit ultricies ut dapibus justo rutrum. Ut et ante dui, vel pellentesque velit.</p>

</section>

<section id="products">

<h4>PRODUCTS</h4>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque feugiat eleifend orci, eget aliquam dolor elementum vel. Aliquam eu nulla eros, et tincidunt felis. Pellentesque congue sodales eleifend. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nulla suscipit nulla vel nisi fermentum ultricies. Integer ligula elit, gravida ac pretium nec, eleifend ultrices purus. Duis cursus orci et urna accumsan tempor. Nunc mattis tincidunt nulla, id porta velit sollicitudin blandit.</p>

<p>Duis vel augue quis elit ultrices fermentum ut eu risus. Mauris dictum nisl eget lorem pulvinar sit amet bibendum nunc scelerisque. Suspendisse ac libero magna, at imperdiet leo. Pellentesque vulputate venenatis vestibulum. Aenean varius turpis quis sem adipiscing volutpat. Fusce scelerisque iaculis augue, eget fringilla velit mattis nec. Maecenas sagittis dolor eget felis cursus imperdiet. Morbi ut dui libero. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sit amet mi ac diam semper hendrerit a id tellus. Morbi accumsan magna sit amet velit ultricies ut dapibus justo rutrum. Ut et ante dui, vel pellentesque velit.</p>

</section>

<section id="contact">

<h4>CONTACT</h4>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque feugiat eleifend orci, eget aliquam dolor elementum vel. Aliquam eu nulla eros, et tincidunt felis. Pellentesque congue sodales eleifend. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nulla suscipit nulla vel nisi fermentum ultricies. Integer ligula elit, gravida ac pretium nec, eleifend ultrices purus. Duis cursus orci et urna accumsan tempor. Nunc mattis tincidunt nulla, id porta velit sollicitudin blandit.</p>

<p>Duis vel augue quis elit ultrices fermentum ut eu risus. Mauris dictum nisl eget lorem pulvinar sit amet bibendum nunc scelerisque. Suspendisse ac libero magna, at imperdiet leo. Pellentesque vulputate venenatis vestibulum. Aenean varius turpis quis sem adipiscing volutpat. Fusce scelerisque iaculis augue, eget fringilla velit mattis nec. Maecenas sagittis dolor eget felis cursus imperdiet. Morbi ut dui libero. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sit amet mi ac diam semper hendrerit a id tellus. Morbi accumsan magna sit amet velit ultricies ut dapibus justo rutrum. Ut et ante dui, vel pellentesque velit.</p>

</section>

</div>

</body>
</html>

Bottom line, I think perhaps the problem was that you were NOT removing the 'stickme' class from the nav element when it no longer should be stuck. But there also could be other problems, and/or it might be something else. As I say, can't really tell without seeing your complete code, css and markup (the link to your page preferably).