i'm making a website where I need a randomised output. I have a working solution using Javascript but the only way the output is changing at the moment is by reloading the page. Is there anything that I can do to reload the output without reloading the page (preferably using a button)?
My current code:
<DOCTYPE html>
<html>
<head>
<title>Strat Roulette - R6S Edition</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link rel="stylesheet" href="strats.css">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<script>
var request = new XMLHttpRequest();
request.onload = function() {
// get the file contents
var fileContent = this.responseText;
// split into lines
var fileContentLines = fileContent.split( '\n' );
// get a random index (line number)
var randomLineIndex = Math.floor( Math.random() * fileContentLines.length );
// extract the value
var randomLine = fileContentLines[ randomLineIndex ];
// add the random line in a div
document.getElementById( 'strats-output' ).innerHTML = randomLine;
};
request.open( 'GET', 'strats.txt', true );
request.send();
</script>
</head>
<body>
<div id="content">
<div class="textshadow">
<h1>Strat Roulette</h1>
<h2>Rainbow 6 Siege Edition</h2>
</div>
<div id="strat">
<code><div id="strats-output"></div></code>
</div>
<button type="button" class="btn btn-primary" onClick="window.location.reload()">Gimme New Strat</button>
</div>
</body>
<footer style="clear: both;">
<p class="alignleft">© Skiletro <?php echo date("Y"); ?></p> <p class="alignright">strats.txt</p>
</footer>
</html>
function sendRequest(){
var request = new XMLHttpRequest();
request.onload = function() {
// get the file contents
var fileContent = this.responseText;
// split into lines
var fileContentLines = fileContent.split( '\n' );
// get a random index (line number)
var randomLineIndex = Math.floor( Math.random() * fileContentLines.length );
// extract the value
var randomLine = fileContentLines[ randomLineIndex ];
// add the random line in a div
document.getElementById( 'strats-output' ).innerHTML = randomLine;
};
request.open( 'GET', 'strats.txt', true );
request.send();
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link rel="stylesheet" href="strats.css">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<script>
</script>
<div id="content">
<div class="textshadow">
<button onclick="sendRequest()">REFRESH CONTENT</button>
<h1>Strat Roulette</h1>
<h2>Rainbow 6 Siege Edition</h2>
</div>
<div id="strat">
<code><div id="strats-output"></div></code>
</div>
<button type="button" class="btn btn-primary" onClick="window.location.reload()">Gimme New Strat</button>
</div>
</body>
<footer style="clear: both;">
<p class="alignleft">© Skiletro <?php echo date("Y"); ?></p> <p class="alignright">strats.txt</p>
</footer>
Moreover, you may also additionally call it onLoad.
Simply just add the request thing into a function and call it on button click.
Just wrap your AJAX code in a function, and have that function being called when the button is pressed:
function reloadData(){
var request = new XMLHttpRequest();
request.onload = function() {
// get the file contents
var fileContent = this.responseText;
// split into lines
var fileContentLines = fileContent.split( '\n' );
// get a random index (line number)
var randomLineIndex = Math.floor( Math.random() * fileContentLines.length );
// extract the value
var randomLine = fileContentLines[ randomLineIndex ];
// add the random line in a div
document.getElementById( 'strats-output' ).innerHTML = randomLine;
};
request.open( 'GET', 'strats.txt', true );
request.send();
}
Then
<button type="button" class="btn btn-primary" onClick="reloadData()">Gimme New Strat</button>
See codepen:
Related
I am trying to to display JSON data from an external location (3 images with a city name and tagline) onto my HTML page but getting an error:
"Uncaught ReferenceError: showPlaces is not defined
at places.json:1:1" even though I did define the function already in my JS file.
JSON data: https://www.selicaro.com/webd330/week6/places.json
https://codepen.io/stefan927/pen/MWOqxmN?editors=1111
*<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<!-- Bootstrap CSS -->
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"
integrity="sha384-
9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4"
crossorigin="anonymous"
/>
<link rel="stylesheet" href="jsonp.css" />
<title>Week 6 | Assignment | JSONP</title>
</head>
<body>
<div class="container">
<h3 class="card-title">
Assignment: Load JSONP from an External Server
</h3>
<form>
<div class="form-group">
<button
type="button"
class="btn btn-primary mx-auto d-block"
id="btn2"
>
Load JSON
</button>
</div>
</form>
<div id="output"></div>
</div>
<!-- Optional JavaScript -->
<script>
(function() {
var btn = document.getElementById('btn2');
btn.addEventListener('click', getJson);
function getJson() {
var output = document.getElementById('output');
output.setAttribute("class", "card-group");
var xhr = new XMLHttpRequest();
var url = 'https://www.selicaro.com/webd330/week6/places.json'
xhr.open('GET', url, true);
xhr.onload = function(data) {
if (this.readyState === 4) {
if (this.status === 200) {
var data = JSON.parse(this.responseText);
function showPlaces(data) {
var content = '';
for (i = 0; i < data.places.length; i++) {
content += '<div class="card" style="width: 20rem;">'
content += '<img class="card-img-top" src=" data.places[i]["img"]
+ '
" alt="
image of city ">';
content += '<div class="card-body">';
content += '<h5 class="card-title">' + data.places[i].loc '</h5>';
content += '<p class="card-text">tagline: ' + data.places[i]
["tagline"] + '</p>';
content += '</div></div>';
}
document.getElementById('output').innerHTML = content;
}
}
}
xhr.send(null);
}
}
})();
</script>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<!--Your JS files go below this comment-->
<script src="week6.js"></script>
<script src="https://www.selicaro.com/webd330/week6/places.json"></script>
<script
src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-
q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"
></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"
integrity="sha384-
cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ"
crossorigin="anonymous"
></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"
integrity="sha384-
uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm"
crossorigin="anonymous"
></script>
</body>
</html>*
I'm creating a script that can send emails to the selected people in which the checkbox is set to true and I'm creating custom sidebar for it. I have made the script successfully. But the sidebar is not working I have tried everything like creating an eventListner or adding a onClick event but still my function is not invoked I have checked in logs it is not invoking at all. Please could anyone tell what's wrong with my code?
This is my HTML file
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<div>
<div class="form-group">
<label for="enter-subject">Subject</label>
<input type="text" class="form-control" id="enter-subject" aria-describedby="emailHelp" placeholder="Enter Subject">
</div>
<div class="form-group">
<label for="enter-message">Message</label>
<input type="text" class="form-control" id="enter-message" placeholder="Enter Message">
</div>
<button class="btn btn-primary" id="mainButton" onClick="afterButtonIsClicked">Submit</button><!--
onClick="afterButtonIsClicked();" -->
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
<script type="text/javascript">
function afterButtonIsClicked(){
var subject = document.getElementById("enter-subject")
var message = document.getElementById("enter-message")
var rowData = {subject: subject.value, message: message.value}
console.log(rowData)
google.script.run.addNewRow(rowData)
}
// document.getElementById("mainButton").addEventListner("click",afterButtonIsClicked)
</script>
</body>
</html>
This is my script file
function addNewRow(rowData) {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2;
var dataRange = sheet.getRange(startRow, 1, sheet.getLastColumn(),sheet.getLastColumn());
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var checkbox1 =row[1];
var emailAddress = row[0];
// var subject = "test subject";
// var message = "test message";
if(checkbox1) {
console.log(`${rowData.subject} ${rowData.message}`)
MailApp.sendEmail(emailAddress,rowData.subject,rowData.message)
}
}
}
this is my UI for sidebar file
function loadForm() {
const htmlForSidebar = HtmlService.createTemplateFromFile("index")
const htmlOutput = htmlForSidebar.evaluate()
const ui = SpreadsheetApp.getUi();
ui.showSidebar(htmlOutput)
}
function createMenu() {
const ui = SpreadsheetApp.getUi();
const menu = ui.createMenu("My Form")
menu.addItem("Show Form", "loadForm")
menu.addToUi();
}
function onOpen() {
createMenu()
}
Could anyone diagnose and tell me the error?
This should fix the onClick issue:
onClick="afterButtonIsClicked();"
I'm trying to create a simple web app that add countries to a google sheet. And use materialize autocompletes to assist the user (which simply autocomplete the country, with no images attached). I saw a couple of examples of the materialize autocomplete, but always with a predefined autocomplete list. This is the html I used:
<html>
<head>
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!--Import materialize.css-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<div class="row">
<div class="col s12">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">work_outline</i>
<input id="autocomplete-input" type="text" class="autocomplete">
<label for="autocomplete-input">Country</label>
</div>
</div>
</div>
</div>
<div class="input-field col s12">
<button class="btn waves-effect waves-light amber accent-4" id="add_btn">Add country
<i class="material-icons right">send</i>
</button>
</div>
<!-- Compiled and minified JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script>
google.script.run.withSuccessHandler(tags).getCountry();
function tags(data) {
var availableTags = data;
$('input.autocomplete').autocomplete({
data: availableTags
});
};
document.getElementById("add_btn").addEventListener("click", doStuff);
function doStuff() {
var ucountry = document.getElementById("autocomplete-input").value;
google.script.run.userClicked(ucountry);
document.getElementById("autocomplete-input").value = "";
};
</script>
</body>
</html>
And this is my code in google script, the function getCountry works, and returns a list of countries. But I didn't succeed in adding them to the materialize autocomplete function.
function doGet() {
var template = HtmlService.createTemplateFromFile("page");
var html = template.evaluate();
return html;
}
function userClicked(country){
var url = "https://docs.google.com/spreadsheets/d/1_GtmVrdD1Es6zQZna_Mv-Rc3JkIu66-q_knQ8aqcUIc/edit#gid=0";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Data");
ws.appendRow([country]);
}
function getCountry(){
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
var list = ws.getRange(1,1,ws.getRange("A1").getDataRegion().getLastRow(),1).getValues(); // contains countries
list = list.map(function(r){return r[0]; });
Logger.log(list);
var data = "{";
for (var i = 0; i < list.length; i++) {
data = data + "'" + list[i] + "': null,";
}
data = data.slice(0, -1) + "}";
Logger.log(data);
return data;
}
This is the information on https://materializecss.com/autocomplete.html
// Or with jQuery
$(document).ready(function(){
$('input.autocomplete').autocomplete({
data: {
"Apple": null,
"Microsoft": null,
"Google": 'https://placehold.it/250x250'
},
});
});
Answer:
You can use web polling to update your page with a set interval such that it always retrieves updated data from the Sheet.
Code:
Piggybacking off the answer here, edit your script to include:
function polling(){
setInterval(update, 500);
}
function update(){
google.script.run.withSuccessHandler(tags).getCountry();
}
and make sure that you run the polling() function on load:
<body onload="polling()">
<!-- your body goes here -->
</body>
Full page.html:
<html>
<head>
<meta charset="utf-8">
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!--Import materialize.css-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body onload="polling()">
<div class="row">
<div class="col s12">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">work_outline</i>
<input id="autocomplete-input" type="text" class="autocomplete" placeholder="Country">
</div>
</div>
</div>
</div>
<div class="input-field col s12">
<button class="btn waves-effect waves-light amber accent-4" id="add_btn">Add country
<i class="material-icons right">send</i>
</button>
</div>
<script>
function polling(){
setInterval(update, 500);
}
function update(){
google.script.run.withSuccessHandler(tags).getCountry();
}
google.script.run.withSuccessHandler(tags).getCountry();
function tags(list) {
console.log(list);
var availableTags = list;
$("#autocomplete-input").autocomplete({
source: availableTags
});
};
document.getElementById("add_btn").addEventListener("click", doStuff);
function doStuff() {
var ucountry = document.getElementById("autocomplete-input").value;
google.script.run.userClicked(ucountry);
document.getElementById("autocomplete-input").value = "";
};
</script>
</body>
</html>
And leave your code.gs file unchanged.
References:
Stack Overflow - Creating an autocomplete function in Google Script that works with a list of values from the Google Sheet
Stack Overflow - Is it possible to import XML or JSON data from a table within a Word online document into Apps Script website as an HTML table?
Changing the getCountry() function, so it reads the data as an object and not as a string fixed it.
function doGet() {
var template = HtmlService.createTemplateFromFile("page");
var html = template.evaluate();
return html;
}
function userClicked(country){
var url = "https://docs.google.com/spreadsheets/d/1_GtmVrdD1Es6zQZna_Mv-Rc3JkIu66-q_knQ8aqcUIc/edit#gid=0";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Data");
ws.appendRow([country]);
}
function getCountry(){
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
var list = ws.getRange(1,1,ws.getRange("A1").getDataRegion().getLastRow(),1).getValues(); // contains countries
list = list.map(function(r){return r[0]; });
Logger.log(list);
var data = {};
for (var i = 0; i < list.length; i++) {
data[list[i]] = null;}
return data;
}
And the html stayed the same:
<html>
<head>
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!--Import materialize.css-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<div class="row">
<div class="col s12">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">work_outline</i>
<input id="autocomplete-input" type="text" class="autocomplete">
<label for="autocomplete-input">Country</label>
</div>
</div>
</div>
</div>
<div class="input-field col s12">
<button class="btn waves-effect waves-light amber accent-4" id="add_btn">Add country
<i class="material-icons right">send</i>
</button>
</div>
<!-- Compiled and minified JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script>
google.script.run.withSuccessHandler(tags).getCountry();
function tags(data) {
var availableTags = data;
$('input.autocomplete').autocomplete({
data: availableTags
});
};
document.getElementById("add_btn").addEventListener("click", doStuff);
function doStuff() {
var ucountry = document.getElementById("autocomplete-input").value;
google.script.run.userClicked(ucountry);
document.getElementById("autocomplete-input").value = "";
};
</script>
</body>
</html>
Currently, I'm trying to build a Heads or Tails system in HTML, CSS, & JavaScript, but when you flip the coin, there is no animation to show the flipping. I've tried to use timeInterval and timeOut, but they don't work correctly, am I doing something wrong?
function flipCoin() {
var randomSide = Math.floor(Math.random() * 2);
if (randomSide == 1) {
document.getElementById("coinImg").src =
"https://upload.wikimedia.org/wikipedia/commons/a/a0/2006_Quarter_Proof.png";
} else {
document.getElementById("coinImg").src = "https://www.coinhunts.com/wpcontent/uploads/2011/01/2005_CA_Proof.png";
}
}
<!DOCTYPE html>
<html>
<head>
<title>Heads or Tails?</title>
<link rel='stylesheet' href='style.css'>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
crossorigin="anonymous">
<link rel='icon'
href='https://upload.wikimedia.org/wikipedia/commons/a/a0/2006_Quarter_Proof.png'>
<script src='script.js'></script>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-
J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous">
</script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"
integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
crossorigin="anonymous"></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"
integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
crossorigin="anonymous"></script>
</head>
<body>
<div class='container'>
<div class='row'>
<h1 class='mx-auto'>Heads or Tails? JS</h1>
</div>
<div class='row'>
<p class='mx-auto'>Click the Button Below to Flip a Coin!</p>
</div>
<div class='row'>
<button onclick='flipCoin();' class='btn btn-primary btn-lg mx-auto' type='button'>Flip a Coin</button>
</div>
<div class='row'>
<img href='' id='coinImg' class='mx-auto'/>
</div>
</div>
</body>
</html>
Try using setTimeout().
function coinSide() {
var randomSide = Math.floor(Math.random() * 2);
if (randomSide == 1) {
document.getElementById("coinImg").src = "HEADS_URL.png";
} else {
document.getElementById("coinImg").src = "TAILS_URL.png";
}
}
// Waits for 3 secs (3000ms) until executes the code
// Your random function is executed in setTimeout function
function flipCoin() {
document.getElementById("coinImg").src = "COIN_FLIP_GIF_URL_HERE.gif";
setTimeout(coinSide, 3000);
}
I'm looking to overwrite a div using JS but the issue is that I'm using append so the script keep writing data at the end of the div, I have no idea how to fix that, I tried window.location.reload(true) but, obviously, the data is lost.
Can someone point me to the right direction, actually I'm lost. My goal is to refresh / erase or update the div content, preferably, whiteout reloading the page. Here's a runnable code so you can see the problem. Thanks for you help.
$("#getnews").on("click", function() {
setTimeout(function() {
var path = "https://api.iextrading.com/1.0/stock/"
var stock = document.getElementById('userstock').value
var end = "/news"
var url = path + stock + end
$.getJSON(url, function(data) {
data.forEach(function (article) {
$('#data').append(
$('<h4>').text(article.headline),
$('<div>').text(article.summary),
$('<hr>').text(" "),
);
});
});
},200);
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<div class="container">
<p>Search for a stock (E.g: msft, aapl or tsla)</p>
<p><input type="text" id="userstock"></p>
<p><a class="btn btn-dark btn-large text-white" id="getnews">Browse</a></p>
<row id="data"></row>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
$("#getnews").on("click", function() {
setTimeout(function() {
var path = "https://api.iextrading.com/1.0/stock/"
var stock = document.getElementById('userstock').value
var end = "/news"
var url = path + stock + end
$.getJSON(url, function(data) {
var html = $("<div></div>");
data.forEach(function (article) {
html.append($('<h4>').text(article.headline));
html.append($('<div>').text(article.summary));
html.append($('<hr>').text(" "));
});
$('#data').html(html);
});
},200);
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<div class="container">
<p>Search for a stock (E.g: msft, aapl or tsla)</p>
<p><input type="text" id="userstock"></p>
<p><a class="btn btn-dark btn-large text-white" id="getnews">Browse</a></p>
<row id="data"></row>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
Can't you just set the HTML of the container:
var html = $("<div></div>");
html.append($('<h4>').text(article.headline));
html.append($('<div>').text(article.summary));
html.append($('<hr>').text(" "));
$('#data').html(html);