HTML equivalent of PHP include for JavaScript parts - javascript

I'm looking for a Javascript equivalent of a technique I've been using in PHP. That is, to place even the most basic page setup:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
...in a php file like 'doc_start.php' and then start every page in my site with...
<?php require_once('/path/to/doc_start.php); ?>
Now I need to begin a project that's strictly HTML and JS (no PHP) and want a similar way to avoid duplicating basic, common HTML elements. Obviously, I want to do more than this very basic stuff, like import JQuery in every page, link to a common stylesheet, etc. Again, all easy in PHP, but I'm still kind of a newbie in JS.
I've read about HTML5 includes, but can't seem to find anything that addresses what I want to do

In order to import other pages into your current document, you need to use a link tag.
For example....
<head>
<link rel="import" href="/path/to/imports/stuff.html">
</head>
This will allow you to reference other html, css or javascript documents into your page without copying and pasting the same code within each page.
https://www.w3schools.com/html/html_links.asp

Javascript and PHP are different languages for very different purposes. But assuming you have some element you don't want to repeat some elements one solution is the following:
Save the HTML elements that you don't want to keep repeating as a string. Then use the .innerHTML property to add elements.
The .innerHTML property stores the mark up of an element as a string.
For example, if we have the following <div>:
<div class="example"> <br> Hello there this is a test! </div>
...and we use .innerHTML:
console.log(document.querySelector(".example").innerHTML);
It will output "<br> Hello there this is a test!".
We can add to the .innerHTML using the += operator. So if you want to add something inside the body it's as simple as:
var something = "some HTML";
document.body.innerHTML += something;
Hope this was what you were looking for!

Related

6 javascript tasks assigned to me by my lecturer

I am a complete beginner to javascript. I am also new to this website. I am asking for help to complete an assignment. I have been trying for more than 4 hours by looking at lecture material and online for a solution. It is causing me a lot of unnecessary stress. Before javascript we only used CSS and Html. I was given 6 javascript tasks to manipulate the html file (taskc.html) already given to me.
The tasks are as follows
Make a statement to change contents of h1 from "Welcome" to "Text"
2nd statement should make an new alert window when the page loads that delivers a message explaining what the page is about
3rd statement should change the title to "text"
4th statement should log the contents (innerHTML) of the first paragraph element in the console.
5th statement should hide the contents of the second paragraph when the page loads
6th statement should change the contents of the header to have a new colour of your choice
Here is that html.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Task C - The Document Object Mode</title>
</head>
<body>
<h1 id="header">Welcome</h1>
<p id="first">This site uses JavaScript</p>
<p id="second">Javascript is very useful</p>
</body>
</html>
Because the actual coding im meant to add is meant to be in the .js file I was given. so I figured I had to link the js file in the html file so I added
<script type="text/javascript" src="taskc.js"></script>
With that out of the way I went to the lecture notes and I thought I would simply need to modify some of the code given to me there like
document.getElementById('demo').innerHTML = 'Hello World!';
When I put this code in brackets I got the error (document is not defined)
I modified it to match the requirements for task 1
here it is
document.getElementById('header').innerHTML = 'text';
I was confused because I didn't know what this error meant and of course Errors and how to fix them are never explained so I had to lookup how to resolve the error.
I found that to fix it I have to declare it as a variable so I ended up doing this.
var document = 'taskc.html';
When I did this for document, alert and console all the errors went away, but when I did a live preview only statement 1 was working
If anyone could help me fix this I would really appreciate because I don't understand enough javascript to be able to complete this in a reasonable amount of time.
So first: Please use Javascript functions to keep your code tidy and clean.
Example:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Task C - The Document Object Mode</title>
</head>
<body>
<h1 id="header">Welcome</h1>
<p id="first">This site uses JavaScript</p>
<p id="second">Javascript is very useful</p>
<script type="text/javascript" src="taskc.js">test();</script>
</body>
</html>
function test(){
alert("This is a test!");
}
Always implement scripts that are document referenced at the bottom of your html.
If you use JQuery you can use following code to check document is loaded:
$(document).ready(function(){
//foo bar
});

Create HTML doc like Bootstrap with Prism

I am facing a problem about how to create HTML code examples with Prism, either with pure JS or VueJS.
I need to get something like Bootstrap documentation, with several lines of HTML code displayed, indented, and highlighted.
It works when I put the HTML code directly between the pre/code tags, replacing the < with <.
But I want something more automatic, in which you write a line of code, for example to create a button, and under it, you have the code displayed.
So I am looking for a way to copy this line of code between the pre/code tags.
The problem is that either through the data objects of Vuejs (putting it as a string), or with the appendChild or innerHTML DOM methods, it doesn't works.
With VueJS I get a highlighted line of code but I can't have a multi-line example.
With appendChild and innerHTML, is displayed only the content of the element, for example the text between the button or div tags.
What I need is a way to display all the code, from < of the first tag to > of the last one.
How can I achieve this? Is it possible or is HTML impossible to easily display in the browser?
Here is the easy JS example I am working on.
If you uncomment the line between code tags, you will have the working example, the result I want to get from a more automatic way, just writing once the line of code, and then copying it.
Thanks
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>About</title>
</head>
<body>
<div id="gg" class="div" data-modifiers='["div--small", "div--big"]'>About</div>
<pre>
<code id="hh">
<!-- <div class="div" data-modifiers='["div--small", "div--big"]'>About</div>-->
</code>
</pre>
<script>
const example = document.getElementById('gg');
const toDisplay = document.getElementById('hh');
// toDisplay.appendChild(example);
hh.innerHTML = gg.innerHTML;
</script>
</body>
</html>
I finally found the solution using only pure JS (no framework).
I share the solution if one day someone needs it.
You can add Prism to get a highlighted displayed code.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>About</title>
</head>
<body>
<div id="gg" class="div" data-modifiers='["div--small", "div--big"]'>
<p>fff</p>
About
</div>
<pre>
<code id="hh" class="language-html">
</code>
</pre>
<script>
const example = document.getElementById('gg').outerHTML;
const toDisplay = document.getElementById('hh');
const regex = /</gi;
renamed = example.replace(regex , '<');
hh.innerHTML = renamed;
</script>
</body>
</html>

Can i access html element Id from any from anyfiles?

I am a beginner to Java-script.
i have a concern
on mainPage.html
<div id="showDialog" style="display:none"> </div>
on mainPage.js
$('#ShowDialog').load("../xxxx.html", function (content) {
xxxxxxxxxxx
});
It is easy understand that if you want to use the id element you just call #element
So, my question is here:
if you are in Setup.js (setup.html has no id attribute like #ShowDialog)
can you still call (So, it will do something on mainPage.html ?? )
$('#ShowDialog').load("../xxxx.html", function (content) {
xxxxxxxxxxx
});
If so, is the class also do the same job? i know id is unique and class is common. So, if one file class can be accessed from other file?
like
$('.ShowDialog').load("../xxxx.html", function (content) {
xxxxxxxxxxx
});
By the way, why we call class using $(.'ShowDialog')rather than just call name like $('ShowDialog')
for class="ShowDialog"
If you want to reference an html Element from an external Javascript file it could be as follows:
myHtml.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- First Import Jquery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Then the module you wish to work with-->
<script src="./ReferencebyId.js"></script>
<title>referencing html Element by Id</title>
</head>
<body>
<!-- the Id you will reference on the module -->
<p id="myId">Change this text</p>
<button onclick="changeInnerHtml()">Change paragraph text</button>
</body>
</html>
ReferencebyId.js
function changeInnerHtml(){
//This is how you would reference the Id, with '#' character
$("#myId").text("changed from external js file referencing Id");
}
Remember that if you wish to use the class to reference the Html Element, you have to make sure only that element has that class, or if you wish to affect more than one element you can put them the same class, and reference them as $(".nameOfClass")
Could you please explain what is it that you are trying to do?
As I understand from your code, you are trying to load content from an external HTML to other HTML with the load function in JQuery and place it inside the div with id="showDialog"
$('#ShowDialog').load("../xxxx.html", function (content) {...}
Is this what you are trying to do? or are you trying to run some JavaScript from other file?
What do you mean by:
setup.html has no id attribute like #ShowDialog
does setup.html does not have any div with that id?
and by:
can you still call (So, it will do something on mainPage.html ?? )
call what? the loader.
about:
By the way, why we call class using $(.'ShowDialog')rather than just call name like $('ShowDialog')
The preceding dot (.) is because classes on jQuery selectors are specified with a preceding dot (.), and id's with a hash sign (#), think of it, like Css selectors, but in jQuery.
Please explain exactly what are you trying to do so we can help you better :)

Foreign characters when loading external html code

I have the following javascript, loading my menu on all of my pages
<script type = "text/javascript">
$(document).ready(function () {
$("#menudiv").load("menu.html");
});
</script>
I havent included the menu as it is a completely standard list, formatted to look like it does. One of the menu option contains the character "å", how can I make my page display this character correctly?
This usually happens when the server doesn't set the encoding of menu.html correctly. Make sure the correct encoding is in the headers. (see this document) Especially, make sure that the Content-Type header is correct and that you have a <meta charset="..."> element in menu.html
The encoding of the existing page doesn't matter at all! Whenever you download something, the browser will look for the encoding of the new data, convert that to Unicode and only then, merge the new data with what it already has.
add this HTML Meta tag in your page:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
Or in HTML5 Way :
<meta charset="iso-8859-1">
Add the following meta tag to the head of your HTML document:
<meta charset="iso-8859-1">
Use the HTML entity code for displaying this and other ISO characters:
å or å
More information on HTML entities from w3: http://www.w3schools.com/tags/ref_entities.asp

embed HTML tag in JavaScript

I'd like to embed an html tag in Javascript, between the script> tag
Thanks
Hey maybe you're looking for jQuery.
$("p").text("<b>Some</b> new text.");
See embedded HTML tag.
Write Less, Do More
jQuery
Is E4X what you're looking for? It allows you to embed XML/XHTML within your JavaScript, like this:
var someXml = <div><b>Some Text</b></div>;
I doubt that's what you need, but that's the only way you can do what you're asking. Also, I don't think it works in Internet Explorer. Scratch that, it only works in Firefox.
If that's not what you want, use document.write(), as suggested by others.
Edit: E4X is now deprecated and has been removed from newer versions of Firefox. Don't use it. You should use jQuery, as the answer below me suggests, or simply create the elements via document.createElement and friends and inject them into the document.
You can't. If you want the Javascript to write HTML, you'll have to use document.write().
If you write this inside your body tag then also you can access this using your javascript.
If yo want to check whether the document is ready or not then you can use JQuery
You can't do that. tags can contain just text (usually javascript).
document.write('colour1: ' + colour1 + 'colour2: ' + colour2 + '');
Using document.write(), though it is generally advised against the use of this method.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
document.write(`
<html>
<body>
<p>html in script tag</p>
<\/body>
<\/html>
`)
</script>
</body>
</html>

Categories