innerHTML works in console, but not in js file - javascript

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;

Related

Embedding multiple pages with same header in multiple <div>

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.

Cannot read property 'innerHTML' of null error. My script is at the end of the body, why am I still getting this error?

My script is at the end of the body, which has been the basic answer I've seen given when searching for a solution. What am I doing wrong? Do I need to use async/await? I've written almost this exact code before, and its worked.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body id="body">
<h1 id="header">Pokemon</h1>
<div id="main-container">
</div>
<button id="button">Click</button>
<script type="text/javascript" src="ajax.js"></script>
</body>
</html>
JS:
let pokemon = document.querySelectorAll('.poke');
let button = document.getElementById('button');
let container = document.getElementById('main-container');
function loadPokemon() {
const urs = 'https://pokeapi.co/api/v2/pokemon';
let xhr = new XMLHttpRequest();
xhr.onload = function() {
if(xhr.status === 200) {
const poke = JSON.parse(xhr.responseText)
container.innerHTML+= `
${poke.results.map(function(pok, index) {
return `
<div class='poke'>
<img src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${(index + 1).toString()}.png">
</img>
${pok.name}
</div>
`
})}
`
}
}
xhr.open('GET', urs, true);
xhr.send();
};
button.addEventListener('click', loadPokemon);
It is working here.. I did not make any changes to your code
let pokemon = document.querySelectorAll('.poke');
let button = document.getElementById('button');
let container = document.getElementById('main-container');
function loadPokemon() {
const urs = 'https://pokeapi.co/api/v2/pokemon';
let xhr = new XMLHttpRequest();
xhr.onload = function() {
if(xhr.status === 200) {
const poke = JSON.parse(xhr.responseText)
container.innerHTML+= `
${poke.results.map(function(pok, index) {
return `
<div class='poke'>
<img src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${(index + 1).toString()}.png">
</img>
${pok.name}
</div>
`
})}
`
}
}
xhr.open('GET', urs, true);
xhr.send();
};
button.addEventListener('click', loadPokemon);
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body id="body">
<h1 id="header">Pokemon</h1>
<div id="main-container">
</div>
<button id="button">Click</button>
<script type="text/javascript" src="ajax.js"></script>
</body>
</html>
Your code is working fine. Are you sure you copy and pasted the exact code?

img tag is not displaying while taking images in javascript array

In ths module i just want to make a flipbook(magazine)so im taking images in a javascript array but the images are not loading up, instead of an image ([object" htmlimageelement]="")is displaying. I don't understand what I am missing in my code.And i'm sure that directory for my images is correct.I think I am missing something in my javascript file.
Html:
<html>
<head>
<title>Flipbook</title>
<link href="jqmodule.css" type="text/css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="jqmodule.js" type="text/javascript"></script>
<script src="jquery.easing.1.3.js" type="text/javascript"></script>
<script src="jquery.booklet.latest.js" type="text/javascript"></script>
</head>
<body class="body_div">
<div class="container">
<div class="main clearfix">
<div class="custom_wrapper">
<h3>Flipbook</h3>
<div id="mybook" class="booklet"></div>
</div>
</div>
</div>
</body>
</html>
JS:
var heading=['background-size','Using transform and the transform functions','Audio','CSS 1, CSS 2.1, CSS3 ...','The benefits of CSS3'];
var para = new Array();
para[0] = new Image();
para[0].src = 'images/1.jpg';
para[1] = new Image();
para[1].src = 'images/2.jpg';
para[2] = new Image();
para[2].src = 'images/3.jpg';
$(function() {
var str="";
for(var i=0;i<para.length;i++)
{
str+="<div class=\"b-page-blank\"><h1>"+heading[i]+"</h1><img src="+para[i]+"/></div>";
}
$('#mybook').html(str);
$('#mybook').booklet({ name: "Booklet" });
$(".b-counter").click(function(){
if($(this).attr('id')==2||$(this).attr('id')==4)
{
$("#mybook").booklet("next");
}
if($(this).attr('id')==3||$(this).attr('id')==5)
{
$("#mybook").booklet("prev");
}
});
});
I may try this way, cleaner and easier to debug,
var data = [
{heading:'background-size',imageSrc:'/images/1.jpg'},
{heading:'Using transform and the transform functions',imageSrc:'/images/2.jpg'},
{heading:'Audio',imageSrc:'/images/3.jpg'}
// ...
];
$(function() {
var str="";
$.each(data,function(index,row){
str+="<div class=\"b-page-blank\"><h1>"+row.heading+"</h1><img src=\""+row.imageSrc+"\" /></div>";
})
$('#mybook').html(str);
//... rest of yoru code
});
Hope it helps

Javascript/html, can't write twice in a input

I'm doing a schoolproject, trying to do an list of things you need to buy.
The problem is, i can't write more than one time and add to the list, and i can't figure out why.
(It's nowhere near done.) (i have to diffrent javascript files)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link href="main.css" type="text/css" rel="stylesheet">
<title>Inköpslista</title>
</head>
<body>
<div id="kol1" class="kol">
<h1>Inköp</h1>
<input type="image" src="img/button.png" alt="Submit" id="storknapp" onclick="klickaKnapp('skriva')"/>
<input type"text" id="skriva" placeholder="Skriv din vara här!"/>
<input type="image" id="knapp" src="pluss.png" alt="Submit"/>
</div>
<div id="kol2">
<ul id="listaavvara"></ul>
</div>
<script src="menudropdown.js" type="text/javascript"></script>
<script type="text/javascript" src="java.js"></script>
</body>
</html>
function laggtill(cool, namnVara) {
var vara = document.createElement("li");
vara.innerText = namnVara;
cool.appendChild(vara);
}
var button = document.getElementById("knapp");
button.onclick = function() {
var skriva = document.getElementById("skriva")
var namnVara = skriva.value;
if(!namnVara|| namnVara =="" || namnVara == " " ){
return false;
}
laggtill(document.getElementById("listaavvara"), namnVara);
};
javascrpit 2:
function klickaKnapp(x){
var skrivrutan = document.getElementById(x), maxH="100px";
if(skrivrutan.style.height == maxH){
skrivrutan.style.height = "0px";
} else {
skrivrutan.style.height = maxH;
}
}
HOPEFULLY YOU KNOW WHAT I MEAN! (my pictures are not here)
Because
var button = document.getElementById("knapp");
button.onclick = function() { ... }
overrides the inline event handler. You need to attach events with addEventListener
button.addEventListener("click", function(){...}, false);
Your example works for me on fiddle: http://jsfiddle.net/7zjb86ab/
So this looks like there is something wrong with your imported scripts
<script src="menudropdown.js" type="text/javascript"></script>
<script type="text/javascript" src="java.js"></script>
Are those the two files with your javascript snippets inside?
You could also try to replace
var button = document.getElementById("knapp");
button.onclick = function() {
with
function addItem() {
and then add the function as onclick attribute like you do with the klickaKnapp function
<input type="image" id="knapp" src="pluss.png" alt="Submit" onclick="addItem()" />

jQuery Carousel Stop at End

I am making a jQuery carousel that is populated using JSON. I need it to stop at the end. I calculate the width of the list by multiplying the number of list items by the width of the list item, so new items can be added without changing the width in the CSS. Here is my code
slider.js
$(document).ready(function() {
var w = $("#carouselList").css("width");
var slider = $("#carouselList");
var leftProperty, newLeftProperty;
$("#rightButton").click(function(){
leftProperty = parseInt(slider.css("left"));
if (leftProperty - 991 <= -w) {
newLeftProperty = 0;
}
else {
newLeftProperty = leftProperty - 304;
}
slider.animate({left: newLeftProperty}, 500);
});
$("#leftButton").click(function(){
leftProperty = parseInt(slider.css("left"));
if (leftProperty < 0){
newLeftProperty = leftProperty + 304;
}
else {
newLeftProperty = 0;
}
slider.animate({left: newLeftProperty}, 500);
});
});
the HTML
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="slider.js"></script>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div id="carousel">
<h2>Recommended for You</h2>
<div id="leftButton" class="buttonPanel"></div>
<div id="display">
<ul id="carouselList">
</ul>
</div><!--display-->
<div id="rightButton" class="buttonPanel"></div>
<div class="clear"></div>
</div><!--carousel-->
<script>
$.getJSON('jsonData.json', function(data){
var items=[];
$.each(data, function(key, val){
items.push(val);
$("#carouselList").append(items[2]);
var c =$("#carouselList li").size();
$("#carouselList").css("width", c*250);
});
});
</script>
</body>
</html>

Categories