Using HTML5 localstorage to update some text without document.write - javascript

I have a div with a class of 'card', which is also draggable() with jQuery. I'm using localstorage to store an array containing information about the card.
var cardID = 1;
var cardValues = new Array();
var name = "Shifting Sliver";
var cost = "3U";
var text = "Sliver cannot be blocked except by slivers.";
var power = "2";
var toughness = "2";
cardValues.push(name);
cardValues.push(cost);
cardValues.push(text);
cardValues.push(power);
cardValues.push(toughness);
localStorage.setItem(cardID, cardValues.join(";"));
var cardKey = localStorage.key(0);
var getCardValues = localStorage.getItem(cardKey);
values = getCardValues.split(";");
var name = values[0];
var cost = values[1];
var text = values[2];
var power = values[3];
var toughness = values[4];
function writeCard()
{
document.write('Card Name: ' + name + '<br />');
document.write('Card Cost: ' + cost + '<br />');
document.write('Card Text: ' + text + '<br />');
document.write('Card Power: ' + power + '<br />');
document.write('Card Toughness: ' + toughness);
}
In the html:
<div class="card">
<div class="info"><script type='text/javascript'> writeCard(); </script></div>
</div>
After dragging the card, when releasing the mouse, document.write causes the whole page to refresh and only the data in document.write is shown. How can I insert the data onto the card without using document.write?
I think I need to use DOM manipulation, but I'm a bit stuck on exactly how.

You can not use document.write when document is completed loading use innerHTML instead
ypu can also use jQuery .append

Related

Getting Data out of a container

I wrote a function that creates new Input fields based on the number of input fields needed. That code is below.
for (i=0;i<number;i++){
container.appendChild(document.createTextNode("Guest " + (i+1)));
var input = document.createElement("input");
input.id = "Guest" + i;
container.appendChild(input);
container.appendChild(document.createElement("br"));
console.log(i.value);
It creates a new Id for each input field. In the function below,depending on the number you set for i, the function creates a generated message.
function sendInput ()
{
var guestNames = document.getElementById("Guest").value
var personName = document.getElementById("people").value;
var eventType = document.getElementById("event").value;
var date = document.getElementById("date").value;
var output = "Dear " + guestNames + " You have been invited to " + personName + "'s " + eventType + " on " + date + " Thank you for coming!!";
document.getElementById('output').innerHTML = output.repeat(i);
}
The problem is it is not collecting the data for guestNames. I am pretty new to JS but have searched and cannot find a solution to my problem. Any feedback wouls be helpful.
IDs are difficult to work with in a dynamic environment, classes are generally the simplest solution. This code will convert your inputs to have classes, then loop through them and collect the names.
So change:
input.id = "Guest" + i;
to
input.setAttribute("class","guest");
And change
var guestNames = document.getElementById("Guest").value
to:
var guests = document.querySelectorAll(".guest");
var guestNames = [];
guests.forEach(function(el){
guestNames.push(el.value);
});
guestNames = guestNames.join(",");
If you are wanting a message for EACH guest, then you would use the below function:
function sendInput ()
{
var personName = document.getElementById("people").value;
var eventType = document.getElementById("event").value;
var date = document.getElementById("date").value;
var guests = document.querySelectorAll(".guest");
var guestNames = [];
document.getElementById('output').innerHTML = "";
guests.forEach(function(el){
document.getElementById('output').innerHTML += "Dear " + el.value + " You have been invited to " + personName + "'s " + eventType + " on " + date + " Thank you for coming!!";
});
}
You try to get node by id var guestNames = document.getElementById("Guest").value
But all nodes have a different id, like a Guest0,Guest1 etc. I am trying to write my own code, but your snippet isn't full. I hope I helped you.
As far as I can see, when you try to fetch the guest name
var guestNames = document.getElementById("Guest").value
you won't get any element for two reasons because there's no element with id "Guest". In fact you generate them in the form "GuestN"
`input.id = "Guest" + i;`
You probably want to add a parameter i to sendInput () function, so that internally you can concatenate it to Guest as you did above and get the correct element with getElementById().
Your code is incomplete (as far as I can tell).
You do not specify the following elements anywhere:
'container', 'guest', 'people', 'event', 'data' or 'output'
I assume they should be defined somewhere in the HTML section (not provided)
To be able to create the variable displays, you need to define the 'container' you wish to initialize it before it is used in the for() loop that follows.
Example: var container = document.getElementById('container');
Within the loop, console.log(i.value) is invalid as i is not an element that has been assigne a value to display. It is a counter of the for() loop.
The function of sendInput(), I assume, is to collect the information from the user for each "Guest#" created by the first loop of your code. However you try to collect from "Guest" which has not been defined. For a number of 5, the collections should be for "Guest1", "Guest2", "Guest3", "Guest4", "Guest5". "Guest" only can not be found anywhere in your loop creation. Same goes for 'people, 'event' and 'date' which are referenced for value collection, but there are no elements named as such.
Not exactly sure why you are mixing DOM creation techniques (???).
You create the number of element for the guest, but then output the results with .innerHTML. You should use the DOM creation method, but I have used your code as you indicated you are a beginner.
Here is some (partially) corrected code that you can continue on with.
<!DOCTYPE html><html lang="en"><head><title> Test Page </title>
<meta charset="UTF-8">
<meta name="viewport" content="width-device-width,initial-scale=1.0, user-scalable=yes"/>
<!-- link rel="stylesheet" href="common.css" media="screen" -->
<style>
</style>
</head><body>
<input type="text" value="5/28/2020" id="date">
<pre id='container'></pre>
<button id="report">Report</button>
<pre id='output'></pre>
<script>
console.clear();
function init() {
var number = 5;
var container = document.getElementById('container');
for (i=0;i<number;i++) {
var value = "Guest " + (i+1)+' ';
container.appendChild(document.createTextNode(value));
var input = document.createElement("input");
input.id = "Guest" + i;
input.value = value;
container.appendChild(input);
container.appendChild(document.createElement("br"));
console.log(i); // .value);
}
document.getElementById('report').addEventListener('click',sendInput);
} init();
function sendInput () {
var date = document.getElementById("date").value,
output = document.getElementById('output'),
info = '';
var guestNames = [...document.querySelectorAll('#container input')]; // alert(guestNames.length);
for (let i=0; i<guestNames.length; i++) {
info = `Dear ${guestNames[i].value}:\nYou have been invited to XXX's EVENT on ${date}\nThank you for coming!!\n\n`;
output.innerHTML += info;
}
// var guestNames = document.getElementById("Guest").value
// var personName = document.getElementById("people").value;
// var eventType = document.getElementById("event").value;
// var output = "Dear " + guestNames + " You have been invited to " + personName + "'s " + eventType + " on " + date + " Thank you for coming!!";
// output = `Dear ${guestNames}:\nYou have been invided to XXX's EVENT on ${date}\nThank you for coming!!`;
// document.getElementById('output').innerHTML = output.repeat(i);
}
</script>
</body></html>

How can I make sure each dynamically created image is taking on its own information/data pulled from the API?

Is there a way for me to make sure each img tag created also contains or can be linked with its individual data from the api? If only one image is returned in the search, it will give me the data for that image. However, if multiple images are returned, once clicked, it will return a only one possible image and data. I am new to coding and javascript in general, so please forgive any rookie mistakes. Thanks!
var scryfallURL = "https://api.scryfall.com/cards/search?q=";
var cardName = "";
var container = $("#list");
$("#searchBtn").on("click", function(event) {
event.preventDefault();
container.empty();
cardName = $("#search").val().trim();
queryURL = scryfallURL + cardName;
$.ajax({
url: queryURL,
method: "GET"
}).then(function(response) {
debugger;
var result = response.data;
console.log(result);
$('#search').val('');
//loops through creating an image tag for each search result
for (let index = 0; index < result.length; index++) {
var showCard = $("#list").append("<image src=' " + result[index].image_uris["normal"] + "' ></image>", "</br>");
var name = result[index].name + "<br>";
var creature = result[index].type_line + "<br>";
var flavorText = result[index].flavor_text + "<br>";
var legality = result[index].legalities + "<br>";
var cardFront = "<image src=' " + result[index].image_uris["large"] + "' ></image>" + "<br>";
};
// click function to clear the div and replace with only one card image and info
showCard.click(function() {
$("#searchForm").empty();
container.empty();
$("#info").append(name, creature, flavorText, legality);
$("#oneCard").append(cardFront);
})
});
});

Dynamically add accordion elements to the DOM

I am trying to dynamically add accordion elements to my DOM and I cannot seem to add it correctly so that the new element will have it's ID in place, class in place etc...
Here is my code:
function addAccordion(esr){
var elementID = document.getElementById("ThreatMainDiv_" + esr.marking);
var emittersDiv = document.getElementById("Emitters");
if(elementID != null){
return;
}
var marking = esr.marking;
var tmp;
tmp = "\"" + "ThreatMainDiv_" + marking + "\"";
var topDiv = '<div id='+ tmp + ' class="accordionTitle"><h1 style="font-size: 16px"></h1></div>';
var tDiv = document.createElement('div');
tDiv.innerHTML = topDiv;
$('#Emitters').append(tDiv);
};
How can I add it correctly?
Change
$('.accordionTitle').click(function(){});
with
$(document).on('click','.accordionTitle',function(){});

Creating and deleting divs using javascript

I have a few JavaScript functions designed to add and remove HTML divs to a larger div. The function init is the body's onload. New lines are added when an outside button calls NewLine(). Divs are removed when buttons inside said divs call DeleteLine(). There are a few problems with the code though: when I add a new line, the color values of all the other lines are cleared, and when deleting lines, the ids of the buttons, titles, and line boxes go out of sync. I've gone through it with the Chrome debugger a few times, but each time I fix something it seems to cause a new problem. I would greatly appreciate some input on what I'm doing wrong.
function init()
{
numOfLines = 0; //Keeps track of the number of lines the Artulator is displaying
}
function NewLine()
{
var LineBoxHolder = document.getElementById("LineBoxHolder");
numOfLines += 1;
LineBoxCode += "<div class = 'Line Box' id = 'LineBox" + numOfLines + "'>" //The code is only split onto multiple lines to look better
+ " <h6 id = 'Title " + numOfLines + "' class = 'Line Box Title'>Line " + numOfLines + "</h6>";
+ " <p>Color: <input type = 'color' value = '#000000'></p>"
+ " <input type = 'button' value = 'Delete Line' id = 'DeleteLine" + numOfLines + "' onclick = 'DeleteLine(" + numOfLines + ")'/>"
+ "</div>";
LineBoxHolder.innerHTML += LineBoxCode;
}
function DeleteLine(num)
{
deletedLineName = "LineBox" + num;
deletedLine = document.getElementById(deletedLineName);
deletedLine.parentNode.removeChild(deletedLine);
num++;
for ( ; num < numOfLines + 1 ; )
{
num++;
var newNum = num - 1;
var changedLineName = "LineBox" + num;
var changedHeaderName = "Title" + num;
var changedButtonName = "DeleteLine" + num;
var changedButtonOC = "DeleteLine(" + newNum + ")";
var changedLine = document.getElementById(changedLineName);
var changedHeader = document.getElementById(changedHeaderName);
var changedButton = document.getElementById(changedButtonName);
var changedLine.id = "LineBox" + newNum;
var changedHeader.innerHTML = "Line" + newNum;
var changedHeader.id = "Title" + newNum;
var changedButton.setAttribute("onclick",changedButtonOC);
var changedButton.id = "DeleteLine" + newNum;
}
num--;
numOfLines = num;
}
You are having a hard time debugging your code because of your approach. You are "marking" various elements with the IDs you construct, and using the IDs to find and address elements. That means that when things change, such as line being deleted, you have to go back and fix up the markings. Almost by definition, the complicated code you wrote to do something like that is going to have bugs. Even if you had great debugging skills, you'd spend some time working through those bugs.
Do not over-use IDs as a poor-man's way to identify DOM elements. Doing it that way requires constructing the ID when you create the element and constructing more IDs for the sub-elements. Then to find the element again, you have to construct another ID string and do getElementById. Instead, use JavaScript to manage the DOM. Instead of passing around IDs and parts of IDs like numbers, pass around the DOM elements themselves. In your case, you don't need IDs at all.
Let's start off with DeleteLine. Instead of passing it a number, pass it the element itself, which you can do my fixing the code inside your big DOM string to be as follows:
<input type='button' value='Delete Line' onclick="DeleteLine(this.parentNode)"/>
So we have no ID for the line element, no ID for the element, and no ID within the onclick handler. DeleteLine itself can now simply be
function DeleteLine(line) {
{
line.parentNode.removeChild(line);
renumberLines();
}
We'll show renumberLines later. There is no need to adjust IDs, rewrite existing elements, or anything else.
Since we no longer need the ID on each line or its sub-elements, the code to create each element becomes much simpler:
function NewLine()
{
var LineBoxHolder = document.getElementById("LineBoxHolder");
numOfLines += 1;
var LineBoxCode = "<div class='LineBox'>" +
+ " <h6 class='LineBoxTitle'>Line " + "numOfLines + "</h6>"
+ " <p>Color: <input type='color' value='#000000'></p>"
+ " <input type='button' value='Delete Line' onclick= 'DeleteLine(this.parentNode)'/>"
+ "</div>";
LineBoxHolder.innerHTML += LineBoxCode;
}
The only remaining work is to fix up the titles to show the correct numbers. You can do this by just looping through the lines, as in
function renumberLines() {
var LineBoxHolder = document.getElementById("LineBoxHolder");
var lines = LineBoxHolder.childElements;
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
var h6 = line.querySelector('h6');
h6.textContent= "Line " + (i+1);
}
}
I voted to close because the question is too broad, but will answer anyway on a few points to... well, point in the right direction.
var changedButton.setAttribute("onclick",changedButtonOC); This is not a variable declaration. Omit the var.
for ( ; num < numOfLines + 1 ; ) { num++; ... The correct form here would be simply for (; num < numOfLines + 1; num++) { ....
Instead of incrementing (num++) then decrementing (num--) around the loop, why not just use the right math?
See:
for (; num < numOfLines; num++) {
...
}

Javascript for i not printing array

I've searched around and found no pure js solution to my issue that I can apply to my code.
It's a script that prints an array of images, but for now it only prints 1 array.
Pertinent code in html:
<div id="imgViewer"></div>
<script>
var imgViewerImages = ['img/imgViewer/1.png','img/imgViewer/2.png','img/imgViewer/3.png','img/imgViewer/4.png','img/imgViewer/5.png','img/imgViewer/6.png'];
</script>
<script src="services/imgViewer.js"></script>
And in JS:
function imgViewerPrinter(){
var imgViewerTarget = document.getElementById('imgViewer');
imgViewerImages.toString();
for (var i=0;i<imgViewerImages.length;i++){
imgViewerTarget.innerHTML = '<img src="' + imgViewerImages[i] + '">';
}
}
window.onload = imgViewerPrinter();
I'm still a noob is JS so I ask for your pacience.
Thanks in advance
try :
imgViewerTarget.innerHTML += "<img src="' + imgViewerImages[i] + '">";
If you want to print out an array of images shouldnt you have your HTML code in the loop making i the image number for example;
for (var i=0;i<imgViewerImages.length;i++){
var imgViewerImages = ['img/imgViewer/' + [i] + '.png'];
}
Try this optimized soln.
var imgViewerImages =['img/imgViewer/1.png','img/imgViewer/2.png','img/imgViewer/3.png','img/imgViewer/4.png','img/imgViewer/5.png','img/imgViewer/6.png'];
function imgViewerPrinter(){
var imgList=[];
for (var i=0;i<imgViewerImages.length;i++){
imgList.push('<img src="' + imgViewerImages[i] + '" />');
}
var imgViewerTarget = document.getElementById('imgViewer');
imgViewerTarget.innerHTML = imgList.join('');
}
window.onload = imgViewerPrinter();
try something like this,Because your code rewrite innerHTML again and again, so you get last iterated value.
Instead of manipulating DOM in every loop,Below code will manipulate your DOM one time only.
function imgViewerPrinter(){
var imgViewerTarget = document.getElementById('imgViewer');
var imgViewerImages_length = imgViewerImages.length;
var image = '';
for (var i=0;i<imgViewerImages_length;i++){
image += '<img src="' + imgViewerImages[i] + '">';
}
imgViewerTarget.innerHTML = image;
}

Categories