this is my code:
const clcBtn = document.getElementById("calcButton");
let clcInput = document.getElementById("calcInput");
const result = document.getElementById('paragraph');
const loader = document.getElementById('spinner');
clcBtn.addEventListener("click", calcFunc);
function calcFunc() {
loader.classList.add("display")
fetch(`http://localhost:5050/fibonacci/`).then(function (response) {
return response.json().then(function (data) {
result.innerHTML = data.clcInput.value; // i want to get the input value from the input field and the server to calculate it and present it to the user.
});
});
}
basically what i want to do, is to add the value the user types in to the innerHTML paragraph id name.
and then i want to make the button react to the click and re-display the "loader" (which i gave it display:none in the CSS file)
and then, i need to make the button to display an error message if the input is higher than 50.
what i have tried to do:
inside the
clcBtn.addEventListener("click", calcFunc);
function calcFunc() {
i have tried to add:
loader.classlist.add("display")
and inside
return response.json().then(function (data) {
result.innerHTML = data.clcInput.value;
i have tried to add and change it to:
clcInput.value = innerHTML.result;
what am i doing wrong?
what is wrong with my syntax and what is the order i need to write everything?
thank you!!!
If i understand correctly what is you need, you should look at the small snippets I did below. It show a loader during the API Call and hide it when you get the result as well as updating the info paragraph depending on the value you typed.
The main thing I recommend you changing in order for your code to work properly is not adding or removing a class to your spinner element to hide it and show it, but simply changing directly it's style by using loader.style.display = "value"
Hope it helps.
const clcBtn = document.getElementById("calcButton");
let clcInput = document.getElementById("calcInput");
const result = document.getElementById('paragraph');
const loader = document.getElementById('spinner');
clcBtn.addEventListener("click", calcFunc);
function calcFunc() {
paragraph.innerText= "";
loader.style.display = "block";
// TimeOut to simulate API Call
setTimeout(function() {
loader.style.display = "none";
if (clcInput.value > 50) {
paragraph.innerText = clcInput.value + " - Error, value too high";
} else {
paragraph.innerText = clcInput.value + " - Value correct";
}
}, 2000);
}
#spinner {
width: 50px;
height: 50px;
border-radius: 50%;
background-color: white;
border: 5px solid black;
display: none;
}
<input type="number" id="calcInput" />
<button id="calcButton">calcButton</button>
<div id="spinner"></div>
<p id="paragraph"></p>
Related
I have already seen a couple of the same questions but I can't seem to get it right. I want to generate a new GIF with a button click. I got as far as generating a GIF by a button click. The problem is that when I click the button again it adds another GIF instead of replaced the previous one.
This is the code I have now:
HTML Button
<form>
<button
class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg"
type="button"
id="btnGIF"
style="display: inline;
transition: all 0.15s ease 0s;
text-align: center;
width: 50%;
z-index:1;
position: relative;
padding: 3%;">Generate GIF
</button>
</form>
And this is the JavaScript code I have:
document.addEventListener("DOMContentLoaded", init);
function init() {
document.getElementById("btnGIF").addEventListener("click", ev => {
let APIKEY = "Dsuxat5V1ccrtvIIBdrxk731WPrSs22l";
let RandomNumber = Math.floor(Math.random() * (100 - 1) + 1);
ev.preventDefault();
let url = `https://api.giphy.com/v1/gifs/search?api_key=${APIKEY}&limit=100&q=thankyou&offset=${RandomNumber}`;
console.log(APIKEY)
console.log(url);
//var image_x = document.getElementsByClassName('out').classList.length;
//console.log(image_x);
//if (image_x > 0){
// PrevImage = document.getElementsByClassName('out')
// PrevImage[0].parentNode.removeChild(PrevImage[0]);
// }
fetch(url)
.then(response => response.json())
.then(content => {
console.log(content.data);
console.log('META', content.meta);
let fig = document.createElement("figure");
let img = document.createElement("img");
img.src = content.data[0].images.downsized.url;
img.alt = content.data[0].title;
fig.appendChild(img);
let out = document.querySelector(".out");
out.insertAdjacentElement("afterbegin", fig);
})
.catch(err => {
console.error(err);
})
});
}
I do see that I'm appending the new gif instead of replacing it. I just can't find a way to replace it (I just started learning JavaScript).
Could someone help me?
You have to remove the previous gif from the html element that it is being appended, which in this case is the element with class 'out'. An easy way to do this is to clear all the children from that class before appending the new element. The snippet below will be setting the HTML of the children of the 'out' class to blank.
document.querySelector(".out").innerHTML = ""
You can put this line right above where you set the api key, the first line within the click listener. Also, it is good practice not to post your api key on stack overflow. Best to leave that blank here.
I have a popup modal in Shopify, I'm using text node instead of innerHtml for security concerns. However, everytime I open the popup modal, the text node keeps getting appended to my h1 tag. Is there any way to check if the node already has been appended? (I don't want to use a boolean value to check if text node has been appended)
html:
<h1 id="ProductHeading" class="product__title product__title--template"></h1>
<h2 id="ProductHeadingModal" class="product__title product__title--template product__title--modal"></h2>
javascript:
var title = document.createTextNode(product.title);
// Product heading is an element with h1 tag
var productHeading = document.getElementById("ProductHeading");
if(// how to check if element has no node?) {
productHeading.appendChild(title);
}
the entire javascript block:
window.onload = () => {
if (window.__shgProductInits.length) {
window.__shgProductInits.forEach((ele) => {
let proId = document.getElementById(ele.uuid);
proId.setAttribute('url', ele.productHandle);
proId.style.cursor='pointer';
proId.addEventListener('click', (e) => {
let productHandle = e.target.parentElement.parentElement.parentElement.getAttribute('url');
fetch('/products/'+productHandle+'.js')
.then((res) =>{return res.json()})
.then((product) => {
console.log(product)
var product = product;
document.getElementsByClassName("product-modal")[0].style.display = "block";
var title = document.createTextNode(product.title);
var productHeading = document.getElementById("ProductHeading");
var productHeadingModal = document.getElementById("ProductHeadingModal");
if(!(productHeading.hasChildNodes())) {
productHeading.appendChild(title);
productHeadingModal.appendChild(title);
var price = document.createTextNode("$" + parseInt(product.price).toFixed(2));
document.getElementById("product-price").appendChild(price);
}
document.getElementById("product-image").src = product.images[0];
});
});
});
}
ProductHeading itself is not a node (I think). And checking innerHtml for length doesn't work as it is always 0
Update:
I've added the conditional check, it still returns false everytime I open the modal.
My code:
My browser console:
My website displays:
Inspect element in browser:
A couple of ways:
if (element.firstChild) {
// It has at least one
}
or the hasChildNodes() function:
if (element.hasChildNodes()) {
// It has at least one
}
or the length property of childNodes:
if (element.childNodes.length > 0) { // Or just `if (element.childNodes.length)`
// It has at least one
}
So you can just write this
var title = document.createTextNode(product.title);
// Product heading is an element with h1 tag
var productHeading = document.getElementById("ProductHeading");
if(!(productHeading.hasChildNodes())) {
productHeading.appendChild(title);
}
Referring this answer
if (productHeading.hasChildNodes()) {
}
Button works, but after refreshing the page, the rule is gone.
My code:
// Create the <style> tag
var style = document.createElement("style");
// WebKit hack :(
style.appendChild(document.createTextNode(""));
// Add the <style> element to the page
document.head.appendChild(style);
return style.sheet;
})();
// Button
let spaces = document.getElementById("spaces");
spaces.onclick = () => {
sheet.insertRule(".navbar {letter-spacing: 3px !important;}", 0);
};
You can do it like this:
localStorage.setItem("your item name or id goes here", "value goes here");
So for what you want it could be like this:
localStorage.setItem("size", "15px");
Then you have to get it when the window loads:
window.onload = function(){
var nav = document.getElementById(navbar);
var finalSize = localStorage.getItem('size');
nav.style.letterSpacing = finalSize;
}
Also, give your navbar or element and ID of "navbar".
Also, there is no need to create a style tag. You can do that with style
in javascript.
Shouldn't that be the normal behavior, refreshing the page should reset it to the initial state?
If you want to use LocalStorage for saving the style rules, you can
// Button
let spaces = document.getElementById("spaces");
spaces.onclick = () => {
sheet.insertRule(".navbar {letter-spacing: 3px !important;}", 0);
localStorage.setItem("addNavbarRule", true)
};
// on page load
window.onload = function(){
if (localStorage.getItem("addNavbarRule")){
sheet.insertRule(".navbar {letter-spacing: 3px !important;}", 0);
}
}
So I'm making a web page where users can press buttons to add elements using appendChild but when they refresh the page it all goes away. Is there something I can do to save what the users add to the page so that when they refresh it it stays the same?
HTML:
<input type="text" id="input" placeholder="write anything here...">
<button id="submit" onclick="createEl()">Submit</button>
<div class="text-div" id="text-div"></div>
CSS:
#input {
width: 500px;
height: 50px;
padding-left: 5px;
}
#submit {
height: 55px;
}
JAVASCRIPT:
var txtDiv = document.getElementById("text-div")
var inputField = document.getElementById("input")
function createEl() {
if (inputField.value !== "") {
var p = document.createElement("p")
var pNode = document.createTextNode(inputField.value)
p.appendChild(pNode)
txtDiv.appendChild(p)
}
}
In the absence of a database, you could try storing their progress within window.localStorage. On page load, you would need to run a function that checks for this item; if present, the function would then repopulate all of their information. After each submission, you would also need to update local storage so that their progress stays current.
Well, as people said earlier the if you want to load your data in all browsers regardless of where did those data came from, you should set up a database, based on your need and specification. Otherwise, you can get used to existing stuff in browsers such as localStorage. So you need to create a property in it, then on each page reload check whether there are data saved there or not with onload event.
So your final code should be something like this:
var txtDiv = document.getElementById("text-div")
var inputField = document.getElementById("input")
var items = [];
function createItem(item) {
var p = document.createElement("p")
var pNode = document.createTextNode(item)
p.appendChild(pNode)
txtDiv.appendChild(p)
}
window.onload = function() {
if (window.localStorage.getItem("items") !== null) {
items = JSON.parse(window.localStorage.getItem("items"))
var itemsLength = items.length
for (var i = 0; i < itemsLength; i++) {
createItem(items[i])
}
}
}
function createEl() {
if (inputField.value !== "") {
createItem(inputField.value)
items.push(inputField.value)
window.localStorage.setItem("items", JSON.stringify(items))
}
}
You will need to use some method of persistent storage. If you don't care about saving the changes forever, then you can save user changes in localStorage. If you need to make sure the changes will always be available, then you'll need to create a database and handle saving and loading data from an API that connects to it.
Here's an example of how to do this using localStorage:
var txtDiv = document.getElementById("text-div")
var inputField = document.getElementById("input")
const getSaved = () => JSON.parse(localStorage.getItem("saved"));
function saveEl(val) {
const saved = getSaved();
let newInputArr = saved ? [...saved, val] : [val];
localStorage.setItem("saved", JSON.stringify(newInputArr));
}
function createEl(val) {
var p = document.createElement("p")
var pNode = document.createTextNode(val)
p.appendChild(pNode)
txtDiv.appendChild(p)
}
function saveAndCreate() {
if((inputField.value !== "")) {
saveEl(inputField.value);
createEl(inputField.value);
}
}
const saved = getSaved();
if(saved && saved.length) {
saved.forEach((val) => {
createEl(val)
})
}
I am using this plugin:
http://code.google.com/p/jquery-watermark/downloads/detail?name=jquery.watermark-3.1.4.zip
and problem is it submits the watermark value as textbox's value in IE9. How can I avoid this issue?
The issue is somewhat related to this post: http://code.google.com/p/jquery-watermark/issues/detail?id=91
but the author denies and marks the bug as invalid.
You could probably just use some simple JS and CSS and roll your own. Using massive all encompassing plug-ins are great when they work.
http://jsfiddle.net/VF8Dr/
https://stackoverflow.com/a/14246071/884862
CSS
.placeholder {
color: gray;
position: absolute;
padding-left: 10px;
}
JS
function addPlaceholder(id, text) {
var elm = document.getElementById(id);
var ph = document.createElement("SPAN");
ph.className = "placeholder";
ph.innerHTML = text;
elm.parentNode.insertBefore(ph, elm.nextSibling);
ph.style.left = elm.offsetLeft + 'px';
ph.style.top = elm.offsetTop + 'px';
ph.onclick = function() {
ph.style.display = 'none';
elm.focus();
};
elm.onfocus = function() {
if(ph.style.display != 'none')
ph.style.display = 'none';
};
elm.onblur = function() {
if(elm.value == '')
ph.style.display = '';
};
}
addPlaceholder("demo", "my text");
Depending on your needs, simple may be best.
I know this is very old post but today i faced the same issue.
Issue: Watermark value was passing as textbox value.
Basically i was using Watermark in all of search functionality and the entire search functionality controls are wrapped in update-panel including watermark text box. In my case because of updatepanel, textbox value being passed as watermark value to the serverside. So i took out watermark textbox out of updatepanel and everything working as expected now.