Skip to content

ThirteeNov

My personal blog about coding and internet

Menu
  • About me
  • About Zofia Kreasi
  • Cart
  • Checkout
  • Making an airplane game from scratch in Unity
  • My account
  • Privacy Policy
  • Privacy Policy – zkLeaderboard
  • Sample Page
  • Shop
  • Tutorials on Learning JavaScript
  • ZKAccounts – Privacy Policy
Menu

How to include HTML script by using JavaScript

Posted on February 13, 2017August 4, 2020 by Habibie

You know HTML pages is static. We can create dynamic website by mixing HTML and another language, such as PHP.

In PHP, we often create separate header & footer file, and then we dynamically change body content.

But what if we talk about simple offline web pages? For example, I want to make a navigation bar/menu that appears on every single offline HTML pages I have. Instead of creating same navigation bar/menu on each HTML file, I will create that navigation in a JavaScript file and use it on each HTML pages.

You can call this idea as “Embedding HTML in JavaScript” or “include HTML script by JavaScript” or whatever you want.

Lets go into the codes…

First, here is my navigation script in HTML:

<div>My Navigation</div>
<ul>
	<li>Menu 1</li>
	<li>Menu 2</li>
	<li>Menu 3</li>
</ul>

Based on this idea, I am going to embed this code into a JavaScript Variable.

I create a JavaScript file and create a function like this:

function writeNav(){
	var myNav = "<div>My Navigation</div><ul><li>Menu 1</li><li>Menu 2</li><li>Menu 3</li></ul>"
	document.write(myNav);
}

Now, on each HTML files I have to include that script file and then call writeNav() function on any location I want to include the navigation menu. For example:

<!DOCTYPE html>
<html>
	<head>
		<title>Include HTML by using JavaScript</title>
	</head>
	<body>
		<script>writeNav()</script>
		<p>This is my content and my navigation is included above!</p>
	</body>
</html>
Post Views: 298
ciihuy2020

Welcome!

  • My YouTube Channel
  • My GitHub Page
  • About me

Categories

  • 3DVista
  • Android
  • Apache
  • C#
  • Cordova
  • Electron & Node JS
  • HTML5, CSS & JavaScript
  • iOS
  • Let's Make Unity Games
  • Misc
  • Photoshop
  • PHP
  • Python
  • Uncategorized
  • Unity
  • WordPress

Recent Posts

  • Make objects like wires and cables easily in Unity using Ciihuy Curved Mesh
  • [SOLVED] Can’t Add Custom Domain to Blogger After Losing CNAME Verification
  • iOS App Icon Generator by CiihuyCom
  • Advanced Blinking Marker Script to show objects position in your game canvas
  • Ciihuy Images Merger – Fast & Easy Online Image Combiner
© 2025 ThirteeNov | Powered by Superbs Personal Blog theme