How to change full content using AJAX - javascript

I want the whole page content to change when I press the button from the Words.html to SelectNumber.html
This is the Words.html
<html>
<head>
<meta charset="UTF-8">
<title>Number Game</title>
<link rel = "stylesheet" href = "stylesheet.css">
</head>
<body>
<div id = "firstScreen">
<h1 id ="Title" class = "title">
The<br>Number Game
</h1>
<input type = "image" src = "button.png" class = "button1" onclick = "loadScreen">
<h3 class = "start">START</h3>
</div>
</body>
<script src = "Main.js"> </script>
</html>
This is the JS
function loadScreen()
{
var load = new XMLHttpRequest();
load.onreadystatechange = function()
{
document.getElementById("firstScreen").innerHTML = this.responseText;
}
};
load.open("GET", "SelectNumber.html", true);
load.send();
}
function myFunction(load)
{
document.getElementById("firstScreen").innerHTML = load.responseText;
}
And this is the SelectNumber.html
<html>
<head>
<meta charset="UTF-8">
<title>Number Game</title>
<link rel = "stylesheet" href = "stylesheet.css">
</head>
<body>
<div id="Screen2">
<p> Hello World</p>
</div>
<script src = "Main.js"></script>
</body>
</html>
I want the whole content to change from Words.html to NumberSelect.html when I press the input button.

function loadScreen() {
var load = new XMLHttpRequest();
load.onreadystatechange = function() {
document.getElementById("firstScreen").innerHTML = this.responseText;
}
load.open("GET", "select.html", true);
load.send();
}
function myFunction(load) {
document.getElementById("firstScreen").innerHTML = this.responseText;
}
loadScreen();

Related

Iframe is srcdoc not updating when using variable

Variables don't work for my iframe's srcdoc or you can't use div.value or something.When I use a variable for an iframe's srcdoc the iframe's html(srcdoc) doesn't update. This code is from me trying to make a code editor. Please Help, I am okay with using jQuery.
It's not done
const html = document.getElementById("html");
const css = document.getElementById("css");
const js = document.getElementById("js");
var edH = document.getElementById("edH");
var edC = document.getElementById("edC");
var edJ = document.getElementById("edJ");
var ifr = document.getElementById("res");
var cssCode;
var htmlCode;
var jsCode;
html.addEventListener("click", changeHTML);
css.addEventListener("click", changeCss);
js.addEventListener("click", changeJs);
html.addEventListener("keydown", update);
function changeHTML() {
htmlCode = edH.value;
jsCode = edJ.value;
cssCode = edC.value;
edH.value = htmlCode;
edH.style.display = "block";
edC.style.display = "none";
edJ.style.display = "none";
}
function changeCss() {
htmlCode = edH.value;
jsCode = edJ.value;
cssCode = edC.value;
edC.value = cssCode;
edC.style.display = "block";
edH.style.display = "none";
edJ.style.display = "none";
}
function changeJs() {
htmlCode = edH.value;
jsCode = edJ.value;
cssCode = edC.value;
edJ.style.display = "block";
edC.style.display = "none";
edH.style.display = "none";
}
function update() {
ifr.srcdoc = edH.value;
}
<!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" />
<title>Static Template</title>
</head>
<body>
<div id="tab" class="tabs">
<p class="langs" id="lang">
<span id="html">HTML</span>
<span id="css">CSS</span>
<span id="js">Javascript</span>
</p>
</div>
<div id="edH" class="edH" contenteditable="true"></div>
<div id="edC" class="edC" contenteditable="true"></div>
<div id="edJ" class="edJ" contenteditable="true"></div>
<iframe id="res" width="500px" height="200px"></iframe>
</body>
<script src="main.js"></script>
</html>
the iframe's srcdoc will not update to edH.value.
demo: https://codesandbox.io/s/lucid-haze-m95ht3
Thanks.
You're adding a keydown event listener to a span; there's no where to type in a span.

Generate a New HTML Document with Javascript

Ok, so all I want to do is : whenever I write something in the Input and press the Button, a new HTML page gets created. But I also want to set the page's name and location. Tried searching it, couldn't find any results...
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Books test</title>
<link rel="stylesheet" href="https://cdn.rawgit.com/Chalarangelo/mini.css/v3.0.1/dist/mini-default.min.css">
</head>
<body>
<input type="text" id="book-input">
<button id="book-button">Create a book</button>
<h1>All the books</h1>
<ul id="books-list"></ul>
<script src="/app.js" defer></script>
</body>
</html>
Javascript
const bookNameInput = document.getElementById("book-input");
const bookCreateButton = document.getElementById("book-button");
var bookName;
var bookId;
bookCreateButton.addEventListener('click', createBook);
function generateRandomNumber() {
var randomNumber = Math.floor(1000000000 + Math.random() * 900000000);
var rn = randomNumber.toString();
return rn;
}
function createBook() {
bookName = bookNameInput.value;
bookId = generateRandomNumber();
fbn = bookName + '_' + bookId
var bookLi = document.createElement("li");
bookLi.classList.add("book-li")
var bookLiA = document.createElement("a");
bookLiA.innerText = bookName;
bookLiA.href = fbn + ".html";
document.getElementById("books-list").appendChild(bookLi);
bookLi.appendChild(bookLiA);
bookNameInput.value = "";
}
Tried using :
const newDoc = document.implementation.createHTMLDocument(title)
But doesn't creates any page...
I already answered your question in comments, so I'm writing this down as a answer so it might be helpful for others too.
So as i was saying it is totally possible to save the file directly from the client side without any need of server or special file system permission on client side -
In Short You can do something like this, Follow this step-by-step -
Get the value of the text input using input.value
Create a Blob out of It
Create a DOM element of anchor element with download attribute
Convert the Blob to an URL Using URL.createObjectURL and Chane the href of previously created anchor element to the returning url
Click on the anchor element without appending it to the DOM
Here is the Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Generate HTML Page</title>
<style>
* {
padding: 0;
box-sizing: border-box;
margin: 0;
}
</style>
</head>
<body style="padding: 20px">
<textarea
placeholder="Enter Your Content Here"
style="width: 100%; height: 500px; font-size: 18px; padding: 18px"
></textarea>
<br /><br />
<button>Download Text as HTML page</button>
<script>
let btn = document.querySelector("button");
let text = document.querySelector("textarea");
btn.addEventListener("click", () => {
if (!/^\s*$/.test(text.value)) {
let a = document.createElement("a");
a.setAttribute("download", "download.html");
let blob = new Blob(text.value.split(""));
let url = URL.createObjectURL(blob);
a.href = url;
a.click();
text.value = "";
} else {
alert("Blank text");
text.value = "";
}
});
</script>
</body>
</html>

Keep body scrolled at the bottom unless user scrolls up in javascript

I have a program where the user types in something and then something outputs in the "console." The most recent entered thing stays at the bottom unless the user scrolls up
The body of my document seems to be where I can dd effects like hidden scroll to it. I read another post and used scrollTop and scrollHeight and it is not working.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href = "style.css">
</head>
<body id = "scroll">
<div id="game">
<div id="console">
</div>
</div>
<div id = "command-box">
<div id = "cmd">
<input id = "command" onkeypress = "doAThing(event);">
</div>
</div>
</div>
<script src = "variables.js"></script>
<script src = "code.js"></script>
</body>
</html>
var input = document.querySelector("#command");
var theConsole = document.querySelector("#console");
theConsole.scollTop = theConsole.scrollHeight;
var myScroll = document.getElementById("scroll");
function doAThing(event) {
var theKeyCode = event.keyCode;
if(theKeyCode === 13) acceptCommand();
setInterval(scrollUpdate, 1000);
}
function scrollUpdate() {
myScroll.scrollTop = myScroll.scrollHeight;
}
function acceptCommand() {
var p = document.createElement("p");
if(input.value === "hi") theConsole.append("Hi!", p);
if(input.value === "ping") theConsole.append("Pong!", p);
}

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?

'Li' element showing as `undefined`

Started to do a todo list on my own to practice JS
When I add the text/task to the todo, HTML text showing-
Undefined
Made sure getElementbyId etc was right but unsure if missing something. Design is rubbish, just want to try JS out.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link type="text/css" rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<title>To doist</title>
</head>
<body>
<div class= "main-title-bar">
<h1>To doist</h1>
</div>
<div id = "button">
<button>+</button>
</div>
<div class = "input" id = "input">
<input type="text" class="add_tast" placeholder="Task">
<span onclick="newElement()" onkeypress="newElement()" class="addBtn">Add</span>
</div>
<div class = "todo-list">
<ul id="myUL">
</ul>
</div>
<script src="js/app.js"></script>
</body>
</html>
JAVASCRIPT
//Click button to get input field
let button = document.getElementById('button')
button.addEventListener("click",showInput)
function showInput(event){
if(event.type === "click"){
input.classList.toggle("show")
}
}
const input = document.querySelector(".input")
// Create new element for the classList
function newElement(){
let li = document.createElement("li");
let inputValue = document.getElementById("input").value;
let t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue === ''){
alert("You must write something!");
} else {
document.getElementById("myUL").appendChild(li);
}
document.getElementById("input").value = "";
console.log('Is it working?');
}
Expecting to see the name of my task on HTML as for example "Going to the gym"
You have given the id="input" to the div instead of the input element. Give the id to the input an it will work
let button = document.getElementById('button')
button.addEventListener("click",showInput)
function showInput(event){
if(event.type === "click"){
input.classList.toggle("show")
}
}
const input = document.querySelector(".input")
function newElement(){
let li = document.createElement("li");
let inputValue = document.getElementById("input").value;
let t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue === ''){
alert("You must write something!");
} else {
document.getElementById("myUL").appendChild(li);
}
document.getElementById("input").value = "";
console.log('Is it working?');
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link type="text/css" rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<title>To doist</title>
</head>
<body>
<div class= "main-title-bar">
<h1>To doist</h1>
</div>
<div id = "button">
<button>+</button>
</div>
<div class = "input" >
<input type="text" id = "input" class="add_tast" placeholder="Task">
<span onclick="newElement()" onkeypress="newElement()" class="addBtn">Add</span>
</div>
<div class = "todo-list">
<ul id="myUL">
</ul>
</div>
<script src="js/app.js"></script>
</body>
</html>
I have fixed your code. document.getElementById("input").value;
input tag is not id it's tag.
if you want get value from input tag must using through id use to this code.
document.getElementById("id").value;
let button = document.getElementById('button')
button.addEventListener("click",showInput)
function showInput(event){
if(event.type === "click"){
input.classList.toggle("show")
}
}
const input = document.querySelector(".input")
// Create new element for the ClassList
function newElement(){
debugger;
let li = document.createElement("li");
let inputValue = $("#tasks").val();
let t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue === ""){
alert("You must write something!");
} else {
document.getElementById("myUL").appendChild(li);
}
document.getElementById("input").value = "";
console.log('Is it working?');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link type="text/css" rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<title>To doist</title>
</head>
<body>
<div class= "main-title-bar">
<h1>To doist</h1>
</div>
<div id = "button">
<button>+</button>
</div>
<div class = "input" id = "input">
<input type="text" id="tasks" class="add_tast" placeholder="Task">
<span onclick="newElement()" onkeypress="newElement()" class="addBtn">Add</span>
</div>
<div class = "todo-list">
<ul id="myUL">
</ul>
</div>
<script src="js/app.js"></script>
</body>
</html>

Categories