2

I'm pretty new to web development. What is the best practice in keeping the same sidebar and other elements across web pages on one's site? Do you store the sidebar html and call that? If so, how would one go about doing something like that?

John
  • 3,037
  • 8
  • 36
  • 68
  • [Yes it can be done in Javascri if you're trying to avoid server-side technology.](http://stackoverflow.com/a/676409/773702) – Josh May 14 '13 at 12:31
  • You are looking for some sort of "frames" See here http://stackoverflow.com/questions/6248564/how-is-better-to-create-frames-in-css-than-html – Fico May 14 '13 at 12:31

3 Answers3

1

There're many options to handle this problem but I've found easy one using jQuery. Use this if it suits your requirements.

  • Add the jQuery CDN in your HTML file.
  • Create a JS file as sidebar.js.
  • Copy all your HTML code of the sidebar and store as a string variable in a function of the JS file. as

    function loadNavbarDiv() { String navbar_code_str = '<nav><div>...</div></nav> $('body').append(navbar_code_str); }

  • Then in the HTML file, you want to add navigation bar, add folowing code in your <head>

    <script src="sidebar.js"></script> <script> $(document).ready(function(){ loadNavDiv(); }); </script>

It's working fine for me. Happy coding!

Shambhu
  • 181
  • 6
  • 16
0

Here's one way to do it: use "include" files. No JavaScript required. The server does the work, instead of requiring the client to add the content.

SSI, or Server Side Includes, were first developed to allow Web developers to "include" HTML documents inside other pages. If your Web server supports SSI, it's easy to create templates for your Web site.

Save the HTML for the common elements of your site as separate files. For example, your navigation section might be saved as navigation.html or navigation.ssi. Use the following SSI tag to include that HTML in each page.

<!--#include virtual="path to file/include-file.html" -->

Use that same code on every page that you want to include the file.

That page also describes some other approaches. But if you know this is called using include files, you can search for it more easily. For example, this article describes includes and how to call them from JavaScript if you must.

DOK
  • 32,337
  • 7
  • 60
  • 92
-2

As long as you're only coding in html, you will need to copy your html into every page. You can store the css for the sidebar in one and the same file and call that on every page though.

Other scripting languages and frameworks might contain templates (php) or master pages (asp.net) for example which make it possible to use the same code in different pages.

Toon Casteele
  • 2,479
  • 15
  • 25