First of all, do not put complex JavaScript code in href attributes. Hard to read or maintain. Use the <script> or completely put the JavaScript code in a separate file.
Secondly, use jQuery. JavaScript is a strange beast: the principles underlying its templates have not been developed with modern web design in mind. jQuery gives you a lot of power without harming JavaScript.
Third, if your goal is to avoid endlessly duplicating the same basic structure for all (or many) of your pages, consider using a template system. Templating systems allow you to connect certain content to forests that contain common elements of your site. If this sounds complicated, it is because I did not explain it well. Google is this and you will find many great resources.
Relying on JavaScript for navigation, your site will not be properly indexed by search engines and will be completely unsuitable for someone with JavaScript turned off. It is increasingly common and acceptable to rely on JavaScript for basic functionality. But your site should, at a minimum, provide discrete pages with reasonable and durable URLs.
Now, all that said, let me get to your question. Here is one way to implement it in jQuery. This is not the worst, most rigorous implementation, but I tried to make something very readable:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>jQuery Example</title> <style type="text/css" media="all"> .content { display: none; } #nav { background: yellow; padding: 10px; } </style> </head> <body> <span id="nav"> <a href="#about_me">about me</a> | <a href="#copyright">copyright notice</a> | <a href="#my_story">a story</a> </span> <div class="content" id="about_me"> <p>I'm a <strong>web developer</strong>!</p> </div> <div class="content" id="copyright"> <p>This site is in the public domain.</p> <p>You can do whatever you want with it!</p> </div> <div class="content" id="my_story"> <p>Once upon a time...</p> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script> <script> </script> </body> </html>
Ok, hope this helps! If jQuery looks attractive, consider starting with this tutorial .
source share