Monday, June 16, 2014

Navigation menu content switcher: html/jsp, css, javascript

Goal:
We have a flat navigation bar with menu options: Home, Careers, Contact Us.
When ever user clicks on any of these options, corresponding content has to be shown below.

It is achieved using simple javascript function.

Please find all the files content below:

1. switcher.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css"
    href="resources/css/SwitcherStyles.css" />
<script type="text/javascript" src="resources/js/SwitcherJs.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Switcher Demo</title>
</head>
<body>
    <div>
        <ul>
            <li><a href="#" id="a1" onclick="changeMenu(this.id);">Home</a></li>
            <li><a href="#" id="a2" onclick="changeMenu(this.id);">Careers</a></li>
            <li><a href="#" id="a3" onclick="changeMenu(this.id);">Contact
                    Us</a></li>
        </ul>
    </div>
    <div id="div-home" style="display: block;">
        <p>
            This is the content related to <b>Home</b>
        </p>
    </div>
    <div id="div-careers" style="display: none;">
        <p>
            This is the content related to <b>Careers</b>
        </p>
    </div>
    <div id="div-contactus" style="display: none;">
        <p>
            This is the content related to <b>Contact Us</b>
        </p>
    </div>
</body>
</html>


2. Javascript: SwitcherJs.js

function changeMenu(id) {
    var homeDiv = document.getElementById("div-home");
    var careersDiv = document.getElementById("div-careers");
    var contactUsDiv = document.getElementById("div-contactus");
   
    if("a1" == id) {
        homeDiv.style.display = 'block';
        careersDiv.style.display = 'none';
        contactUsDiv.style.display = 'none';
    } else if("a2" == id) {
        homeDiv.style.display = 'none';
        careersDiv.style.display = 'block';
        contactUsDiv.style.display = 'none';
    } else if("a3" == id) {
        homeDiv.style.display = 'none';
        careersDiv.style.display = 'none';
        contactUsDiv.style.display = 'block';
    }
}


3. CSS: SwitcherStyles.css

li {
    display: inline;
    padding: 20px;
}

a {
    text-decoration: none;
    color: #00F;
    padding: 8px 8px 8px 8px;
}

a:HOVER {
    color: #F90;
    background-color: #FFF;
}

ul {
    border: 1px solid;
    margin: 0px;
    padding: 8px 0px;
}


Demo Screenshots:











No comments:

Post a Comment