How to dynamically link menu items to sections - javascript

Using jQuery, how can I dynamically add href and id attributes to link the menu items to the sections in the code below in order?
<body>
<nav>
<ul>
<li><a>nav1</a></li>
<li><a>nav2</a></li>
<li><a>nav3</a></li>
</ul>
</nav>
<section class="main-section"></section>
<section class="main-section"></section>
<section class="main-section"></section>
</body>
It should look like this after.
<body>
<nav>
<ul>
<li>nav1</li>
<li>nav2</li>
<li>nav3</li>
</ul>
</nav>
<section id="id1" class="main-section"></section>
<section id="id2" class="main-section"></section>
<section id="id3" class="main-section"></section>
</body>

You can try this.....
Fiddle
Html :
<ul>
</ul>
</nav>
<div id='addMore'>
</div>
<button id='btn'>add section and link</button>
Jquery :
var count = 0;
$('#btn').click(function(){
$('#addMore').append('<section id="id'+ count+'" class="main-section"></section>');
$('nav ul').append('<li>nav'+count+'</li>');
count++;
});
let me know if it according to you requirements...
Happy coding...

How about this: First build your strings
var sections ="";
var list = "<ul>";
for(var i=0; i < 3; i++)
{
list += '<li>nav'+i+'</li>';
sections += '<section id="id'+i+'" class="main-section"></section>';
}
list += "</ul>"
Then add them somewhere like:
$('nav').html(list );
$('#container').html(sections);

Here is the JSFIDDLE
var totalLists = 4;
var listitems='';
var sectionitems='';
$(document).ready(function(){
for(var i = 1; i<= totalLists; i++){
listitems = listitems+'<li>nav'+i+'</li>';
sectionitems=sectionitems+'<section id="id'+i+'" class="main-section"></section>'
}
$("#navlists").append(listitems);
$("#section").append(sectionitems);
});

You can try this solution :
adding id dynamically to section within body according to nav element
Seems like the nav element exist already then the solution is find the a element length(for creating section), then insert newly created element after existing section or nav. Hope this helped.
Html
<nav>
<ul>
<li><a>nav1</a>
</li>
<li><a>nav2</a>
</li>
<li><a>nav3</a>
</li>
</ul>
</nav>
jQuery
$('nav li a').each(function(i,e){
var section;
$(this).attr('href','#id'+(i+1));
section = $('<section/>',{
class : 'main-section',
id : 'id'+(i+1)
});
if ( $('nav').next().is('section') ) {
$(section).insertAfter($('nav').nextAll().last());
} else {
$(section).insertAfter('nav');
}
});
DEMO

You can loop through the links, then assign common href and id values based on the index of the link.
This checks if the section exists before setting the attributes.
var sections = $('section.main-section');
$('nav a').each(function(index){
if(sections.eq(index).length) {
$(this).attr('href','#section' + index);
sections.eq(index).attr('id','section' + index);
}
})
/* This CSS is for demo purposes only */ html, body { margin: 0; height: 100%; } .main-section { height: 100%; } ul,li { padding: 0; margin: 0; } ul { position: fixed; } li { display: inline-block; } #section0 { background: rgb(150,200,250); } #section1 { background: rgb(250,200,150); } #section2 { background: rgb(150,250,200); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
<ul>
<li><a>nav1</a></li>
<li><a>nav2</a></li>
<li><a>nav3</a></li>
<li><a>nav4</a></li> <!-- This will not change because
there is no fourth section -->
</ul>
</nav>
<section class="main-section"></section>
<section class="main-section"></section>
<section class="main-section"></section>

Related

Is there a shorter more concise way to hide & show div with Javascript?

I am creating a dashboard with approximately 20 divs starting with "display: none;".
When the .onClick() in the sidebar will be used, it will show a specific div and keep hidden all the others.
I have used the classic solution of creating a function for each div, however, is extremely lengthy and the code looks like a mess.
Is there a better cleaner way to achieve this with Javascript?
Here is my code:
function presale() {
var x = document.getElementById("presale");
var y = document.getElementById("claim");
var z = document.getElementById("stake");
if (x.style.display === "grid") {
x.style.display = "none";
} else {
x.style.display = "grid";
y.style.display = "none";
z.style.display = "none";
}
}
function claim() {
var x = document.getElementById("presale");
var y = document.getElementById("claim");
var z = document.getElementById("stake");
if (y.style.display === "grid") {
y.style.display = "none";
} else {
x.style.display = "none";
y.style.display = "grid";
z.style.display = "none";
}
}
function stake() {
var x = document.getElementById("presale");
var y = document.getElementById("claim");
var z = document.getElementById("stake");
if (z.style.display === "grid") {
z.style.display = "none";
} else {
x.style.display = "none";
y.style.display = "none";
z.style.display = "grid";
}
}
*,
html {
color: #fff;
background-color: black;
}
#presale,
#claim,
#stake
/* Here I have many other divs like below */
{
display: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<link rel="stylesheet" href="MOD.CSS">
<script src="main2.js"></script>
<title>Base Template</title>
</head>
<body>
<div>
<ul>
<!-- Here I have other 20 options like the above -->
<li onclick="presale()">Presale</li>
<li onclick="claim()">Claim</li>
<li onclick="stake()">Stake</li>
<!-- Here I have other 20 options like the above -->
</ul>
<div id="presale">
<h1>Presale</h1>
</div>
<div id="claim">
<h1>Claim</h1>
</div>
<div id="stake">
<h1>Stake</h1>
</div>
</div>
</body>
</html>
Is there a better way to do this without the need to create a function and repeat the same thing over and over for each div?
There is no need for JS at all. You can simply use an anchor and use #id as hyper reference. Then you can display the element through CSS by using the :target-selector:
*,
html {
color: #fff;
background-color: black;
}
.d-none
/* Here I have many other divs like below */
{
display: none;
}
div:target {
display: grid;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<link rel="stylesheet" href="MOD.CSS">
<script src="main2.js"></script>
<title>Base Template</title>
</head>
<body>
<div>
<ul>
<!-- Here I have other 20 options like the above -->
<li>Presale</li>
<li>Claim</li>
<li>Stake</li>
<!-- Here I have other 20 options like the above -->
</ul>
<div id="presale" class="d-none">
<h1>Presale</h1>
</div>
<div id="claim" class="d-none">
<h1>Claim</h1>
</div>
<div id="stake" class="d-none">
<h1>Stake</h1>
</div>
</div>
</body>
</html>
Here you see a vanilla Javascript solution.
content divs are by default hidden.
If you click an element, the corresponding data-id get the class show.
window.onload = function () {
document.querySelectorAll('#nav li').forEach((elements) => {
elements.addEventListener('click', (el) => {
document.querySelectorAll('.content').forEach((item) => {
// hide all
item.classList.remove('show');
});
// show one
document.getElementById(el.target.getAttribute('data-id')).classList.add('show');
});
});
};
.content {
display: none;
}
.show {
display: block;
}
<ul id="nav">
<li data-id="presale">Presale</li>
<li data-id="claim">Claim</li>
<li data-id="stake">Stake</li>
</ul>
<div id="presale" class="content">
<h1>Presale</h1>
</div>
<div id="claim" class="content">
<h1>Claim</h1>
</div>
<div id="stake" class="content">
<h1>Stake</h1>
</div>
Something like this using data attributes and classlist toggles should also work.
I would consider minimizing your code (and CSS) by using generic CSS selectors to hide/show the individual sections. This also makes scalability and maintainability easier for the next guy.
This has the added benefit of your styling being controlled 100% using CSS and not arbitrary inline styles set by the javascript.
Adding another section is also easy as can be:
Add a new section with some id (eg. awesome-section)
Add a nav entry with the attribute data-toggle-section with the id as the value <li data-toggle-section="awesome-section">Awesome Section</li>
Profit
You're also not restricted to using just the nav elements themselves as the event listener is bound using the [data-toggle-section] selector which means that basically anything can show or hide a section as long as it has that attribute with the correct value.
const buttons = Array.from(document.querySelectorAll("[data-toggle-section]"));
const sections = buttons.map(element => {
return document.getElementById(element.dataset.toggleSection)
});
buttons.forEach(element => {
element.addEventListener('click', event => {
const selected = element.dataset.toggleSection;
sections.forEach(section => {
if(section.id === selected) {
section.classList.toggle('shown');
} else {
section.classList.remove('shown');
}
})
});
});
*,
html {
color: #fff;
background-color: black;
}
.option-section {
display: none;
}
.option-section.shown {
display: grid;
}
<div>
<ul>
<!-- Here I have other 20 options like the above -->
<li data-toggle-section="presale">Presale</li>
<li data-toggle-section="claim">Claim</li>
<li data-toggle-section="stake">Stake</li>
<!-- Here I have other 20 options like the above -->
</ul>
<div id="presale" class="option-section">
<h1>Presale</h1>
</div>
<div id="claim" class="option-section">
<h1>Claim</h1>
</div>
<div id="stake" class="option-section">
<h1>Stake</h1>
</div>
</div>
You could simply assign the same class (e.g. my_div) to every showable div, then pass the id to your function (that will show that and hide all the others).
function show_hide(id) {
document.querySelectorAll('.my_div').forEach(my_div => {
my_div.style.display = my_div.getAttribute('id') == id ? 'block' : 'none';
});
}
.my_div {
display: none;
}
<div>
<ul>
<li onclick="show_hide('presale')">Presale</li>
<li onclick="show_hide('claim')">Claim</li>
<li onclick="show_hide('stake')">Stake</li>
</ul>
<div class="my_div" id="presale">
<h1>Presale</h1>
</div>
<div class="my_div" id="claim">
<h1>Claim</h1>
</div>
<div class="my_div" id="stake">
<h1>Stake</h1>
</div>
</div>
Here's my attempt. It's sensibly the same as #ztom's answer but I tryed avoiding a foreach.
document.querySelectorAll("li").forEach(e => e.addEventListener("click", () => {
let shown = document.querySelector(".action:not(.d-none)")
if(shown){
shown.classList.add("d-none")
if(e.dataset.id != shown.id){
document.getElementById(e.dataset.id).classList.remove("d-none")
}
}else{
document.getElementById(e.dataset.id).classList.remove("d-none")
}
}))
.action{
display:grid;
}
.d-none{
display:none;
}
<ul>
<li data-id="presale">Presale</li>
<li data-id="claim">Claim</li>
<li data-id="stake">Stake</li>
</ul>
<div class="action d-none" id="presale">Presale</div>
<div class="action d-none" id="claim">Claim</div>
<div class="action d-none" id="stake">Stake</div>
When it comes to use the same logic on multiple elements, use classes instead of id's and your solution is shortened by default.
With jQuery, it's basically a 2-liner:
in CSS, create a class .hidden with display:none;
Your div and li elements should be grouped, using a class too.
Then you can simply refer to this classes and add the show/hide logic by:
$('h1:contains('+$(this).text()+')').parent().toggleClass("hidden");
$('h1:not(:contains('+$(this).text()+'))').parent().addClass("hidden");
$('document').ready(function(){
$('.toggle').on('click',function(){
$('h1:contains('+$(this).text()+')').parent().toggleClass("hidden");
$('h1:not(:contains('+$(this).text()+'))').parent().addClass("hidden");
});
});
*,
html {
color: #fff;
background-color: black;
}
.hidden
{
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" href="MOD.CSS">
<script src="main2.js"></script>
<title>Base Template</title>
</head>
<body>
<div>
<ul>
<!-- Here I have other 20 options like the above -->
<li class="toggle">Presale</li>
<li class="toggle">Claim</li>
<li class="toggle">Stake</li>
<!-- Here I have other 20 options like the above -->
</ul>
<div class="hidden">
<h1>Presale</h1>
</div>
<div class="hidden">
<h1>Claim</h1>
</div>
<div class="hidden">
<h1>Stake</h1>
</div>
</div>
</body>
</html>
This is a question for Code Review section https://codereview.stackexchange.com/
However, you can try smth like this:
const elems = ["presale", "claim", "stake"];
function toggle(elem) {
elems.map(i => {
let el = document.getElementById(i);
el.style.display = "none";
});
let active_el = document.getElementById(elem);
active_el.style.display = "grid";
}
and in html add the elem name as a param, so, replace this
<li onclick="presale()">Presale</li>
<li onclick="claim()">Claim</li>
<li onclick="stake()">Stake</li>
with this
<li onclick="toggle('presale')">Presale</li>
<li onclick="toggle('claim')">Claim</li>
<li onclick="toggle('stake')">Stake</li>
If you attach data attributes to both the list items and the "panels" you can use one function to match them up, and use a CSS class to determine whether it should be active or not.
// Cache the elements, the panels container, and the list element
// separately adding one event listener to the list. We're using
// event delegation for this - one listener captures all
// the events from its child elements
const allElements = document.querySelectorAll('.list li, .panels .panel');
const panels = document.querySelector('.panels');
const list = document.querySelector('ul');
list.addEventListener('click', handlePanel);
// When the listener is triggered
function handlePanel(e) {
// Check if it's a list item
if (e.target.matches('li')) {
// Destructure its id from the dataset
const { id } = e.target.dataset;
// Remove all the active classes from the elements
allElements.forEach(el => el.classList.remove('active'));
// And then add an active class to the list item,
// and the panel where their ids match
const selector = `[data-id="${id}"]`;
const item = list.querySelector(`li${selector}`);
const panel = panels.querySelector(`.panel${selector}`);
item.classList.add('active');
panel.classList.add('active');
}
}
.panel { display: none; }
.panel h1 { font-size: 1.2em; color: darkblue; }
ul { list-style-type: none; margin-left: 0; padding: 0; }
li { padding: 0.3em; border: 1px solid white; }
li:hover { background-color: thistle; cursor: pointer; }
li.active { border: 1px solid #454545; background-color: lightyellow; }
.panel.active { display: block; }
<ul class="list">
<li data-id="presale">Presale</li>
<li data-id="claim">Claim</li>
<li data-id="stake">Stake</li>
</ul>
<div class="panels">
<div data-id="presale" class="panel">
<h1>Presale</h1>
</div>
<div data-id="claim" class="panel">
<h1>Claim</h1>
</div>
<div data-id="stake" class="panel">
<h1>Stake</h1>
</div>
</div>
Additional documentation
classList
Destructuring assignment
Event delegation
matches
querySelector / querySelectorAll
Template/string literals

How to dynamically set the colour of a 'div' element to match that of the colour picked on a colour widget using for loop?

I have this html code that includes a colour widget picker, the background of the entire page will change according to which pre-defined choice the user clicks on. I have got that working but I would like to highlight the box around the colour choice once it has been clicked to differentiate from the other unselected choices.
<html>
<head>
<meta charset="utf8" />
<title></title>
<script>
function changeColor(e) {
document.getElementById("page").className = e;
var i;
var x = document.getElementById("page");
for (i = 0; i < 5; i++)
if (document.getElementById("page").className = e ){
x.getElementsByTagName("li")[i].style.borderColor = "red";
}
}
</script>
</head>
<body>
<div id="page" class=""><!-- start page wrapper -->
<hr />
<div id="theme-picker">
<h2>Theme Picker</h2>
<p>Select a theme from the options below:</p>
<div id="palette">
<ul>
<li class="midnight" onClick="changeColor('midnight')">Midnight</li>
<li class="matrix" onclick="changeColor('matrix')">Matrix</li>
<li class="peardrop" onclick="changeColor('peardrop')">Peardrop</li>
<li class="skylight" onclick="changeColor('skylight')">Skylight</li>
<li class="sunset" onclick="changeColor('sunset')">Sunset</li>
</ul>
<div class="clearfix"></div>
<hr />
</div><!-- /page -->
</body>
</html>
Here's how I would do this (of course change the classes as needed):
$('.changeColor').click(function(){
var $this=$(this);
var color=$this.data('color');
$('#page').removeClass('midnight matrix peardrop skylight sunset').addClass(color);
$('.changeColor').removeClass('highlight'); // jquery actually implements a loop here it's just internal...
$this.addClass('highlight');
});
/*
// Methods with a explicit loop per your comment
$('.changeColor').click(function(){
var $this=$(this);
var $page=$('#page');
var color=$this.data('color');
$page.removeClass('midnight matrix peardrop skylight sunset').addClass(color);
$page.find('li').each(function(){ // jQuery loop....not really neccisary though...
$(this).removeClass('highlight');
});
$this.addClass('highlight');
});
$('.changeColor').click(function(){
var $this=$(this);
var $page=$('#page');
var color=$this.data('color');
$page.removeClass('midnight matrix peardrop skylight sunset').addClass(color);
var lis = $page.find('li');
for(var i =0; i< lis.length; i++){ // js loop....again not really neccisary though...
$(lis[i]).removeClass('highlight');
}
$this.addClass('highlight');
});
*/
body {
margin: 10px;
}
.midnight{
background-color:black;
color:white;
}
.matrix{
background-color:purple;
}
.peardrop{
background-color:grey;
}
.skylight{
background-color:blue;
}
.sunset{
background-color:pink;
}
.highlight{
background-color:yellow;
outline: 1px solid #red;
color:black;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="page" class=""><!-- start page wrapper -->
<hr />
<div id="theme-picker">
<h2>Theme Picker</h2>
<p>Select a theme from the options below:</p>
<div id="palette">
<ul>
<li class="changeColor" data-color="midnight">Midnight</li>
<li class="changeColor" data-color="matrix">Matrix</li>
<li class="changeColor" data-color="peardrop">Peardrop</li>
<li class="changeColor" data-color="skylight">Skylight</li>
<li class="changeColor" data-color="sunset">Sunset</li>
</ul>
<div class="clearfix"></div>
<hr />
</div>
You could pass the object everytime you call the function, and then change that object color. Something like this:
...
<script>
function changeColor(className,object) {
document.getElementById("page").className = className;
var siblings = object.parentElement.getElementsByTagName('li');
for(var sibling in siblings){
if(siblings[sibling].className){
siblings[sibling].className = siblings[sibling].className.split(' ')[0];
}
}
object.className = object.className+' selected';
}
</script>
...
<li class="midnight" onClick="changeColor('midnight',this)">Midnight</li>
<li class="matrix" onclick="changeColor('matrix',this)">Matrix</li>
<li class="peardrop" onclick="changeColor('peardrop',this)">Peardrop</li>
<li class="skylight" onclick="changeColor('skylight',this)">Skylight</li>
<li class="sunset" onclick="changeColor('sunset',this)">Sunset</li>
...
Edited, since I was missing the point of resetting the selection. You could just create a selected class with whatever you need and your done

How to use the jQuery Selector in this web application?

I am trying to work out to select a delete icon in my own web application. delectIcon
HTML
<main>
<div class="container">
<div class="tabs">
<p><span class="active">Newest</span></p><a href=""><p>
<span>Oldest</span></p></a><p><span>Add</span></p>
</div>
<div class="content">
<ul>
<li>
<span class="itemLeft">Answer emails</span>
<span class="itemMiddle">12-31-2016</span>
<span class="itemRight">1</span>
<b class="deleteIcon"> X </b>
</li>
<li>
<span class="itemLeft">Prep for Monday's class</span>
<span class="itemMiddle">12-31-2016</span>
<span class="itemRight">5</span>
<b class="deleteIcon"> X </b>
</li>
</ul>
</div>
</div>
</main>
JavaScript
$(".deleteIcon").on("click", function () {
alert("Oh, clicked!");
return false;
});
I failed to do so by writing it myself. So I used Chrome Web Developer Tool to find the CSS path. I tried to use the XPath($"[/html/body/main/div/div[2]/ul/li[ 1 ]/b]") and CSS Path ($"(pathbody > main > div > div.content > ul > li:nth-child(1) > b)"). Neither of them worked.
I tried to mark it with an ID and made only one "li" exists. The CSS selector worked all right. But when I clicked the deleteIcon$"(#deleteIcon)", nothing happened.
#deleteIcon{
float:right;
font-weight: bold;
padding: 0 3px 0 3px;
border-radius: 5px;
background: #ccc;
cursor: pointer;
margin-left: 5px;
font-size: 1.3em;
text-align: center;
}
I also tried to select my title. I found the following worked out.
$(".container h1").on("click", function () {
alert("Oh, no!");
return false;
});
I do not what to do now. Can anyone help me out here?
Thank you! I would be really appreciate if you can answer my question.
Adding more details:
I did actually add the deleteIcon into the HTML by JavaScript. I do not know whether this can have an effect on my selector.
Actual HTML
<main>
<div class="container">
<div class="tabs">
<p><span class="active">Newest</span></p><a href=""><p>
<span>Oldest</span></p></a><p><span>Add</span></p>
</div>
<div class="content">
</div>
</div>
</main>
JavaScript (The important part listed below)
function Item(name,dueDate,type){
this.name=name;//1
this.dueDate=dueDate;//input2
this.type=type;//3
};
$(".tabs a span").toArray().forEach(function (element) {
var $element = $(element);
// create a click handler for this element
$element.on("click", function () {
var $content,
$input,
$button,
i;
if ($element.parent().parent().is(":nth-child(1)")) {
// newest first, so we have to go through
// the array backwards
$content = $("<ul>");
for (i = Task.length-1; i >= 1; i--) {
// $buttondelete = $("<buttonDelete>").text("X");
var txt1 = Task[i].toStringName();
var txt2 = Task[i].toStringDate();
var txt3 = Task[i].toStringType();
//alert(txt3);
$content.append('<li> <span class="itemLeft">'+txt1+'</span> <span class="itemMiddle">'+txt2+'</span> <span class="itemRight">'+txt3+'</span><b class="deleteIcon"> X </b>');
}
}
$("main .content").append($content);
return false;
});
});
If you are creating the items inside ul dynamically you should bind the click event like this :
$(".content").on("click", ".deleteIcon", function()
{
alert("clicked") ;
return false;
}
) ;
The class selector starts with a . (just like the example you say you have that works).
Try
$(".deleteIcon").on("click", function () {
alert("Oh, clicked!");
return false;
});

add class to li onclick

how will i go on to added a class to li class='active' on click and also on page load have the first li ( overview ) active by default ?
<ul>
<li>Overview</li>
<li>Reviews</li>
<li>News</li>
<li>Gallery</li>
</lu>
<div id='overview' style='display: none;'>
<!-- overview content -->
</div>
<div id='articles' style='display: none;'>
<!-- arcticles content -->
</div>
<div id='news' style='display: none;'>
<!-- news content -->
</div>
<div id='gallery' style='display: none;'>
<!-- gallery content -->
</div>
<script type="text/javascript">
function showdiv(id){
document.getElementById(id).style.display = "block";
}
</script>
Here is a Quick JSFiddle Demo that demonstrates swapping classNames and display of divs in pure JavaScript.
var toggleDiv = function(self, id) {
var li = self.parentNode,
contents = document.getElementsByClassName('content'),
menu = document.getElementById('menu'),
children = menu.children,
child = undefined,
i = 0;
// Loop over all content divs and show the active and hide all others.
for (i = 0; i < contents.length; i++)
contents[i].style.display = contents[i].id == id ? 'block' : 'none';
// Loop over all menu items and add active class to the selected
// and remove from others if applicable.
for (i = 0; i < children.length; i++) {
child = children[i];
if (child === li) {
child.className = (child.className + ' active').trim();
} else {
if (child.className.indexOf('active') > -1) {
child.className = child.className.replace('active', '').trim();
}
}
}
}
<ul id="menu">
<li>Overview</li>
<li>Reviews</li>
<li>News</li>
<li>Gallery</li>
</ul>
<div id="overview" class="content">Overview...</div>
<div id="reviews" class="content">Reviews...</div>
<div id="news" class="content">News...</div>
<div id="gallery" class="content">Gallery...</div>
ul {
margin: 0;
padding: 0;
list-style-type: none;
}
li {
position: relative;
display: inline-block;
width: 80px;
background: #4679BD;
color: #FFFFFF;
text-align: center;
}
li>a {
color: #FFFFFF;
text-decoration: none;
font-weight: bold;
}
.content {
display: none;
}
.active {
background: #064CA8;
}
You should consider using jQuery if you have not already. It really makes these a bit easier.
Strictly speaking, here is one way: (untested)
<ul>
<li>Overview</li>
<li>Reviews</li>
<li>News</li>
<li>Gallery</li>
</ul>
<div id='overview' style='display: none;'>
<!-- overview content -->
</div>
<div id='articles' style='display: none;'>
<!-- arcticles content -->
</div>
<div id='news' style='display: none;'>
<!-- news content -->
</div>
<div id='gallery' style='display: none;'>
<!-- gallery content -->
</div>
<script type="text/javascript">
function showdiv(id, a){
if (window.activeA != undefined) {
window.activeA.className = ''; // delcare window.activeA, if not already exists
}
document.getElementById(id).style.display = "block";
a.className = 'active';
window.activeA = a;
}
</script>

Nav items on header change based on section

On my website I've got a sticky header with several different nav items on it that when clicked will scroll down to find that section on the page. I was wondering how one would go about setting it up so the nav items change colour when the view is on the section it corresponds to. In other words, if the viewer is on section 'x', 'x' on the nav bar will change color.
Update: heres the code for the nav bar im using
<div class = 'nav-container'>
<nav>
<div id = 'nav-items-container'>
<ul class='nav-items'>
<li class='nav-item'><a href='#what'>what</a></li>
<li class='nav-item'><a href='#how'>how</a></li>
<li class='nav-item'><a href='#why'>why</a></li>
<li class='nav-item'><a href='#who'>who</a></li>
<li class='nav-item'><a href='#where'>where</a></li>
</ul>
</div>
</nav>
</div>
some css
.nav-container{
background-color:black;
height:50px;
width:410px;
font-size: 120%;
position:absolute;
}
a:link{
color:white;
}
a:visited{
color:#58ACFA;
}
#nav-items-container ul li{
display:inline;
}
#nav-items-container ul li a{
padding: 20px;
text-decoration:none;
}
#nav-items-container ul{
margin:0;
padding:0;
list-style-type: none;
text-align: center;
padding-top:15px;
}
If you can use jquery you can do something like:
<script type="text/javascript">
$(function() {
var sections = [],
anchors = $('#nav-items-container a[href^="#"]'), // anchor links with hash tags
docHeight = $(document).height(),
currentOffset,
setNavActive;
// handler to update the class
setNavActive = function(hash){
anchors.removeClass('current-section');
anchors.filter('a[href="' + hash + '"]').addClass('current-section');
};
// building our hash/start/end position map
$.each(anchors, function(i, item) {
currentOffset = $(item.hash).offset().top;
if (i > 0) {
sections[i-1].end = currentOffset;
}
sections[i] = {
hash: item.hash,
start: (i == 0 ? 0 : currentOffset),
end: docHeight
};
});
// on scroll event, check which map fits,
// find the hash and set the class
$(document).scroll(function() {
currentOffset = $(document).scrollTop();
for (var i = 0; i < sections.length; i++) {
if (sections[i].start <= currentOffset && sections[i].end > currentOffset) {
setNavActive(sections[i].hash);
}
}
});
});
</script>
I added a new style but you can make it nested or whatever:
.current-section {background:pink; }
jsFiddle
http://jsfiddle.net/fstreamz/krb6Q/3/
There is not enough information here to give the best answer. I can give one that works though.
Chang your headers to look like this:
<li class='nav-item' id = "nav_what"><a href='#what'>what</a></li>
<li class='nav-item' id = "nav_how"><a href='#how'>how</a></li>
<li class='nav-item' id = "nav_why"><a href='#why'>why</a></li>
<li class='nav-item' id = "nav_who"><a href='#who'>who</a></li>
<li class='nav-item' id = "nav_where"><a href='#where'>where</a></li>
then in the body of each page put
<script>
document.getElementById('nav_what').style.backgroundColor = "gray";
</script>
You would have to switch it out on each page with the correct id. Its more traditionally done manually with inline styles if the header is not loaded externally.
Add another CSS declaration as below and apply active style to the current page.
#nav-items-container ul li.active a {
color:red;
}
Apply the above style like this...
<li class='nav-item active'><a href='#what'>what</a></li>
jsFiddle Demo

Categories

Resources