Embedding multiple pages with same header in multiple <div> - javascript

I want to embed url http://localhost:8081/static/bar.html in the main div at my index.html, so I wrote the below:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Awesome echarts</title>
<script src="https://go-echarts.github.io/go-echarts-assets/assets/echarts.min.js"></script>
<link href="https://go-echarts.github.io/go-echarts-assets/assets/bulma.min.css" rel="stylesheet">
</head>
<body>
<div id="main">
<object id="foo" name="foo" type="text/html" data="http://localhost:8081/static/bar.html"></object>
</div>
</body>
</html>
Where my bar.html is:
<div class="select" style="margin-right:10px; margin-top:10px; position:fixed; right:10px;"></div>
<div class="container">
<div class="item" id="eeUwxscJvXae"
style="width:900px;height:500px;"></div>
</div>
<script type="text/javascript">
"use strict";
var myChart_eeUwxscJvXae = echarts.init(document.getElementById('eeUwxscJvXae'), "white");
var option_eeUwxscJvXae = {
title: {"text":"Bar-示例图",},
tooltip: {},
legend: {},
toolbox: {"show":true,"feature":{"saveAsImage":{},"dataZoom":{},"dataView":{},"restore":{}}},
xAxis: [{"data":["衬衫","牛仔裤","运动裤","袜子","冲锋衣","羊毛衫"],"splitArea":{"show":false,},"splitLine":{"show":false,}}],
yAxis: [{"axisLabel":{"show":true},"splitArea":{"show":false,},"splitLine":{"show":false,}}],
series: [
{"name":"商家A","type":"bar","data":[43,10,4,12,6,38],"label":{"show":false},"emphasis":{"label":{"show":false},},"markLine":{"label":{"show":false}},"markPoint":{"label":{"show":false}},},
{"name":"商家B","type":"bar","data":[21,44,37,19,32,34],"label":{"show":false},"emphasis":{"label":{"show":false},},"markLine":{"label":{"show":false}},"markPoint":{"label":{"show":false}},},
],
color: ["#c23531","#2f4554","#61a0a8","#d48265","#91c7ae","#749f83","#ca8622","#bda29a","#6e7074","#546570","#c4ccd3"],
};
myChart_eeUwxscJvXae.setOption(option_eeUwxscJvXae);
</script>
<style>
.container {margin-top:30px; display: flex;justify-content: center;align-items: center;}
.item {margin: auto;}
</style>
But While loading it at the browser, I got an error:
Uncaught ReferenceError: echarts is not defined
at bar.html:9
Why this is happening, is not it assumed that sub div are calling the header in the caller file?
I got it resolved by re-wriitng the header in the bar.html file, i.e.:
<head>
<script src="https://go-echarts.github.io/go-echarts-assets/assets/echarts.min.js"></script>
<link href="https://go-echarts.github.io/go-echarts-assets/assets/bulma.min.css" rel="stylesheet">
</head>
But is not this meaning double loading of the echarts.min.js and the bulma.min.css and what if I wanted to embed multiple pages like this, in multiple divs in the index.html do I need to call these files for every single div?

This is an example that I just tested. It works fine, and will suffice for your purpose.
index.html
<html>
<head>
</head>
<body>
<div source="header.html"></div>
<script>
window.test = "this is a test";
function includeSource() {
var z, i, elmnt, file, xhttp;
/*loop through a collection of all HTML elements:*/
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain attribute:*/
file = elmnt.getAttribute("source");
if (file) {
/*make an HTTP request using the attribute value as the file name:*/
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {
elmnt.innerHTML = this.responseText;
// now we'll run the js if there is some direct js code in script tags
var html = document.createElement('html');
html.innerHTML = this.responseText;
const scripts = html.getElementsByTagName("script");
for (const script of scripts) {
eval(script.innerText);
}
}
if (this.status == 404) {
elmnt.innerHTML = "Page not found.";
}
/*remove the attribute, and call this function once more:*/
elmnt.removeAttribute("source");
includeSource();
}
}
xhttp.open("GET", file, true);
xhttp.send();
/*exit the function:*/
return;
}
}
};
includeSource();
</script>
</body>
</html>
header.html
<style>
.header {
font-size: 50px;
color: blueviolet;
}
</style>
<div class="header">
<span>Test</span>
<button onclick="console.log(window.test)">click me</button>
</div>
<script>
console.log(window.test);
</script>
Observe the source attribute on the div; it'll be used to define the path of the html file you want to load and you can include your JS and CSS in the same file.

Related

TypeError : button is null but working fine in console

So I wanted to make a webpage in which on button click, the background color changes.
Its showing TypeError on loading in browser but its working fine after pasting same JavaScript on console.
Code snippet
var colors = ["#0af5fa", "#0ab1fa", "#0a3efa", "#560afa", "#b70afa", "#fa0ad9", "#fa0a65", "#fa0a1e", "#fa5e0a", "#facc0a", "#cbfa0a", "#69fa0a", "#0afa1b", "#0afa77", "#0afae5", "#0a8efa"];
var flag = 0,
blinkCount = 0;
function blink() {
if (blinkCount == 15) {
blinkCount = 0;
blink();
} else {
var h1 = document.querySelector("h1");
var body = document.querySelector("body");
h1.style.color = colors[blinkCount];
body.style.background = colors[blinkCount];
blinkCount++;
}
}
var button = document.querySelector("button");
button.addEventListener("click", blink);
button {
width: 50%;
height: 100px;
background: black;
margin-top: 300px;
margin-left: 300px;
}
h1 {
color: #0af5fa;
}
body {
background: #0af5fa;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<script src="../JavaScript/ex153.js"></script>
<link href="../css/ex153.css" rel="stylesheet">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div class="">
<button><h1>Click Me</h1></button>
</div>
</body>
</html>
In Browser [Error]
TypeError: button is null[Learn More] ex153.js:25:1
You're running the script before the document has been fully parsed - see how the <script> is above the <body> and its <button>?
Either give the script tag the defer attribute:
<script defer src="..
Or move it to the bottom of the body:
</div>
<script src="../JavaScript/ex153.js"></script>
</body>
</html>
Or wrap the whole script in a DOMContentLoaded listener:
document.addEventListener('DOMContentLoaded', function() {
var colors;
// other code
});

innerHTML works in console, but not in js file

I have this code:
window.addEventListener("load", function() {
console.log("s");
var pres = document.querySelectorAll("pre[lang]");
console.log(pres);
for (var i = 0; i < pres.length; i++) {
console.log("x")
var lang = pres[i].getAttribute("lang");
console.log(lang);
console.log(pres[i].innerHTML);
pres[i].innerHTML = highlight_c(pres[i].innerHTML);
console.log(pres[i].innerHTML);
}
});
All the console.logs work, except for the console.log(pres[i].innerHTML);. pres[i].innerHTML = highlight_c(pres[i].innerHTML); is also not working. It does work in console, though. When I run this code in the JavaScript-console everything works! But when it is runned from the js-file, it doesn't work.
BTW: Those messy console.logs are just to check that my code was running.
EDIT: The highlight_c function is defined in another file and it works completely fine.
Here is my HTML:
<html>
<head>
<title>Index - C: Local documentation</title>
<link rel="stylesheet" type="text/css" href="styles/global.css">
<link rel="stylesheet" type="text/css" href="syntax-highlighting/styles/c.css">
<meta charset="utf-8">
</head>
<body>
<div id="container">
<div id="header">
<h1>C: Local documentation</h1>
</div>
<div id="content">
<div id="nav">
<h3>Navigation</h3>
<ul>
<li>Reading files</li>
<li>Page 02</li>
<li>Page 03</li>
</ul>
</div>
<div id="main">
<h2>Reading files</h2>
<p>How to read files:</p>
<pre lang="c" src="reading-files.c"></pre>
<p>That's it.</p>
</div>
</div>
<div id="footer">
Copyright © 2018 Quintus Rijpstra.
</div>
</div>
<script type="text/javascript" src="scripts/pre-load.js"></script>
<script type="text/javascript" src="syntax-highlighting/load.js"></script>
<script type="text/javascript" src="syntax-highlighting/scripts/c.js"></script>
</body>
The pre tag has no contents but an src tag, wich is used by another function to load text into it:
window.addEventListener("load", function() {
var pres = document.querySelectorAll("pre[src]");
for (var i = 0; i < pres.length; i++) {
var src = pres[i].getAttribute("src");
loadfile(src, load);
}
});
function load(filecontent, filename) {
var pre = document.querySelectorAll("pre[src=\"" + filename + "\"]");
for (var i = 0; i < pre.length; i++) {
pre[i].innerHTML = filecontent;
}
}
function loadfile(filename, handler) {
var xmlrequest = new XMLHttpRequest();
xmlrequest.open("GET", filename);
xmlrequest.onreadystatechange = function() {
if (xmlrequest.readyState == 4) {
if (xmlrequest.status == 200) {
var content = xmlrequest.responseText;
handler.call(null, content, filename);
}
}
};
xmlrequest.send(null);
}
Can anyone help me?
Thanks in advance!
Instead of
var pres = document.querySelectorAll("pre[lang]");
Try to get your 'pre' tag in JS by tag name:
var pres = document.getElementsByTagName('pre')[lang].innerHTML;

blocky - property of undefined

I am trying to create a custom block in blockly but can't seems to get it to work. I generated code from block factory and this is what I got:
//say_input.js
Blockly.Blocks['say_input'] = {
init: function() {
this.appendDummyInput()
.appendField("say")
.appendField(new Blockly.FieldTextInput("something"), "say_input");
this.setColour(230);
this.setTooltip("");
this.setHelpUrl("");
}
};
Blockly.JavaScript['say_input'] = function(block) {
var text_say_input = block.getFieldValue('say_input');
// TODO: Assemble JavaScript into code variable.
// var code = 'alert("Hello! I am an alert box and'+text_say_input+'!");';
var code = '...;\n';
return code;
};
then I import it into my html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Blockly Demo: Fixed Blockly</title>
<script src="js/blockly_compressed.js"></script>
<script src="js/blocks_compressed.js"></script>
<script src="js/msg/js/en.js"></script>
<script src="js/blocks/say_input.js"></script>
<style>
body {
background-color: #fff;
font-family: sans-serif;
}
h1 {
font-weight: normal;
font-size: 140%;
}
</style>
</head>
<body>
<button onclick="runCode()">Click me</button>
<div id="blocklyDiv" style="height: 480px; width: 600px;"></div>
<xml id="toolbox" style="display: none;">
<block type="say_input">
<field name="say_input">something</field>
</block>
</xml>
<script>
var demoWorkspace = Blockly.inject('blocklyDiv', {
media: 'js/media/',
toolbox: document.getElementById('toolbox')
});
function runCode(){
window.LoopTrap = 1000;
Blockly.JavaScript.INFINITE_LOOP_TRAP =
'if(--window.LoopTrap == 0) throw "Infinite loop."\n';
var code = Blockly.JavaScript.workspaceToCode(workspace);
Blockly.JavaScript.INFINITE_LOOP_TRAP = null;
try {
eval(code);
} catch (e) {
alert(e);
}
}
</script>
</body>
</html>
and load it to browser. immediately I got this error:
Cannot set property 'say_input' of undefined
The error is at the line:
Blockly.JavaScript['say_input'] = function(block) {
My custom block appear in the workplace so I am sure the linking is working.
I checked this video and seems like I am doing nothing wrong.
How can I resolve this?
I found the solution. I have to link javascript_compressed.js then everything just work.
<script src="js/javascript_compressed.js"></script>
make sure to link it before the custom block.js.

jQuery load breaks function

My PHP webpage page1.php is like this:
<html>
<head>
<script src="//code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
function ciao(){
$('#files').load('page2.php?SQL_type=files');
}
$(function(){
$(".icon_files").bind("contextmenu",function(e){
var left;
var top;
if($(document).width() < 630){
left = 0;
top = 0;
}else{
left = e.pageX;
top = e.pageY;
}
$("#context").css({left: left, top: top});
contextmenu($(this).attr('id'));
e.preventDefault();
});
});
</script>
</head>
<body>
<button onclick="ciao()">ciao</button>
<div id="files">
<?php
$_GET['SQL_type'] = 'files';
include "page2.php";
?>
</div>
</body>
</html>
I've build a custom contextmenu that appears with the code above.
When the page loads and include page2.php through PHP it works, but when I change #files content via jQuery, the contextmenu (and all other function I haven't copied there) no longer works.
I've tried other codes like
jQuery.get('page2.php?SQL_type=files', null, function(data) {
$('#files').append(data);
}, 'html');
And I've tried also with simple Javascript
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("files").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "page2.php?SQL_type=files", true);
xmlhttp.send();
Inside page2.php there are simply some DIVs everyone of them with icon_files as class and it doesn't include jQuery again. It is simply like
<div class="icon_files">something</div><div class="icon_files">other</div>
I don't have any other ideas, what could be the problem here?
Thank you
The jquery code is running, however, the elements the jquery code is targeting are being replaced after clicking the button, thus causing them to lose events/data. Try using event delegation instead. This causes the event to be bound to the id="files" element rather than the elements that are being replaced.
function ciao() {
$('#files').html('<div class="icon_files">another icon...</div>');
}
$(function() {
$("#files").on("contextmenu", ".icon_files", function(e) {
var left;
var top;
if ($(document).width() < 630) {
left = 0;
top = 0;
} else {
left = e.pageX;
top = e.pageY;
}
$("#context").css({
left: left,
top: top
});
console.log('context menu');
e.preventDefault();
});
});
<html>
<head>
<script src="//code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
</script>
</head>
<body>
<button onclick="ciao()">ciao</button>
<div id="files">
<div class="icon_files">icon...</div>
</div>
</body>
</html>

How Block UI until page load with wait image using javascript/CSS only

I want to block html page until it loads completely with wait image by javascript or CSS but WITHOUT JQUERY
I want to achieve like these demos http://malsup.com/jquery/block/#demos
Please don't suggest with jquery solutions.
HTML code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script>
var ld = (document.all);
var ns4 = document.layers;
var ns6 = document.getElementById && !document.all;
var ie4 = document.all;
if (ns4)
ld = document.loading;
else if (ns6)
ld = document.getElementById("loading").style;
else if (ie4)
ld = document.all.loading.style;
function init() {
if (ns4) { ld.visibility = "hidden"; }
else if (ns6 || ie4) ld.display = "none";
}
</script>
</head>
<body onload="init()">
//image which has size of 40 mb.
<img src="show.jpg" />
<div id="loading" style="position:absolute; width:100%; text-align:center; top:300px;">
//loading image to see while loading background image
<img src="loading.gif" />
</div>
</body>
</html>
Here a solution that will show the wait image when js is active, and keep the wait image hidden if js is not active:
Create a default rule that hides the #loading and a .is-loading #loading that shows the wait image
Use JS to add the class wait image to the html element
When the content (or image) is loaded remove the is-loading class.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
(function() {
var html = document.getElementsByTagName('html')[0];
html.className += ' is-loading';
window.onload = function() {
html.className = String(html.className).replace('is-loading','');
}
}());
</script>
<style>
#loading {
display : none;
position : absolute;
width : 100%;
text-align : center;
top : 300px;
}
.is-loading #loading {
display: block;
}
</style>
</head>
<body>
<!--image which has size of 40 mb. -->
<img src="show.jpg" >
<div id="loading">
<!-- loading image to see while loading background image -->
<img src="loading.gif" >
</div>
</body>
</html>

Categories