Display gif after confirm until loading is finished in javascript - javascript

I have a form that includes a Submit button. After the submit button is clicked, a confirmation popup appears. Once the confirm condition is met, an HTTP post takes place. However, sometimes that post can take a while. As such, I would like to display a loading gif after the confirm condition is met, up until the post response comes back, whereby the page is already reloading.

I would suggest using an element as some sort of modal then setting the css property visibility to and from hidden and visible.
Then you can add event handlers to your button presses and requests to hide or show this element.
See the example below:
const requestButton = document.querySelector('.request');
const yes = document.querySelector('.yes');
const no = document.querySelector('.no');
const confirmation = document.querySelector('.confirmation');
const loading = document.querySelector('.loading');
const content = document.querySelector('.content');
requestButton.addEventListener('click', event => {
confirmation.style.visibility = 'visible';
});
yes.addEventListener('click', event => {
// instead of a setTimeout, you'd actually make a request using `fetch` or jquery ajax
loading.style.visibility = 'visible';
confirmation.style.visibility = 'hidden';
window.setTimeout(() => {
// the code in this callback would be the same code you'd put in your `success` callback
// i.e. this code should run when the request finishes
loading.style.visibility = 'hidden';
const p = document.createElement('p');
p.innerText = 'Loaded!';
content.appendChild(p);
}, 2000);
});
no.addEventListener('click', event => {
confirmation.style.visibility = 'hidden';
});
.hidden-center {
position: absolute;
height: 100%;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
top: 0;
left: 0;
visibility: hidden;
}
.modal {
background-color: lightgray;
padding: 3em;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<div class="content">
<button class="request">load a thingy?</button>
</div>
<div class="confirmation hidden-center">
<div class="modal">
Are you sure?
<div>
<button class="yes">Yes</button>
<button class="no">No</button></div>
</div>
</div>
<div class="loading hidden-center">
<div class="modal">
<div>Loading...</div>
<i class="fa fa-spinner fa-spin fa-3x"></i>
</div>
</div>
EDIT:
Reading the comments above, it looks like your application is not a single page application (I just assume nowadays). Instead of attaching an event listener to the button click, you need to attach the event listener to the form like so:
document.querySelector('#my-form-id').addEventListener('submit', event => {/*code to show loading*/})
Also, you probably don't need to add an event listener for the request coming back because the new document will replace the current one.

Related

How to close a popup on a click outside of it

I have a popup button in my header. I need to make sure that when clicking outside its zone, the popup closes. How can i do this? In the code I'm trying to add remove active classes when clicking on body.active-search but it doesn't work.
const body = document.querySelector("body");
const searchButton = document.querySelector(".search-button");
const searchPopup = document.querySelector(".search-popup");
if (searchButton) {
searchButton.addEventListener("click", () => {
searchPopup.classList.toggle("active");
searchButton.classList.toggle("active");
body.classList.toggle("active-search");
});
}
$(".active-search").click(function() {
searchPopup.removeClass("active");
searchButton.removeClass("active");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header>
<div class="search-wrapper">
<button class="search-button">Open Search</button>
<div class="search-popup"></div>
</div>
</header>
On BODY "click" use Event.target.closest("selector") to determine if a click landed on specific elements selectors, if that's the case do nothing (return from the function); otherwise toggle the "active-search" class on BODY.
Also, there's no need to specifically toggle other active classes on elements. Use CSS instead.
const el = (sel, par) => (par??document).querySelector(sel);
const elSearchButton = el(".search-button");
const elSearchPopup = el(".search-popup");
const elBody = el("body");
elSearchButton.addEventListener("click", () => {
elBody.classList.toggle("active-search");
});
elBody.addEventListener("click", (evt) => {
// Do nothing if popup clicked or button
if (evt.target.closest(".search-button, .search-popup")) return;
// Else...
elBody.classList.remove("active-search");
});
/*QuickReset*/ * {margin:0; box-sizing: border-box;}
body {
min-height: 100vh;
}
.active-search {
background: #eee;
}
.search-popup {
display: none;
padding: 1rem;
background: gold;
}
.active-search .search-popup {
display: block !important;
}
<header>
<div class="search-wrapper">
<button type="button" class="search-button">Toggle Search</button>
<div class="search-popup"><input type="search" placeholder="Search..."></div>
</div>
</header>
See this closely related answer: https://stackoverflow.com/a/70691308/383904
Similar issue was described here Hide popup by clicking elsewhere
Basically you have to add a couple of code lines
$("body").click(function(){
searchPopup.remove("active");
searchButton.remove("active");
});
searchPopup.click(function(e){
e.stopPropagation();
});
searchButton.click(function(e){
e.stopPropagation();
});
Hope this helps.

Display content related to only those button it is clicked in HTML

I have three buttons in HTML, orders and products and supplier. I want when the user clicks orders order is being shown, when the user clicks products, the product is shown, and the name of the supplier when it is clicked.
function changedata(parameter){
if(parameter==0){
document.getElementById('myorders').style.fontSize="25px";
}
else if(parameter==1){
document.getElementById('myproducts').style.fontSize="25px";
}
else{
document.getElementById('mysupplier').style.fontSize="25px";
}
}
<button class="button" onclick="changedata(0)">ORDERS</button>
<button class="button" onclick="changedata(1)">PRODUCTS</button>
<button class="button" onclick="changedata(2)">SUPPLIER</button>
<div id="myorders">
<p>Laptop, Earphone</p>
</div>
<div id="myproducts">
<p>Earphone, smart watch</p>
</div>
<div id="mysupplier">
<p>Amazon, E-kart</p>
</div>
But it won't hide data and serve my need, I'm a beginner in web development, looking for kind help to show data only when the corresponding button is pressed.
Try giving each element a default value of display:none in your css, as such -
#myorders,
#mysuppliers,
#myproducts {
font-size: 25px;
display: none;
}
This will select each element and hide them right away.
Then, when a button is pressed, you can use
document.getElementById('___').style.display = 'block';
to then show that element.
Here is the final product:
function changedata(parameter){
if(parameter==0){
document.getElementById('myorders').style.display = 'block';
}
else if(parameter==1){
document.getElementById('myproducts').style.display = 'block';
}
else{
document.getElementById('mysupplier').style.display = 'block';
}
}
#myorders,
#myproducts,
#mysupplier{
font-size: 25px;
display: none;
}
<button class="button" onclick="changedata(0)">ORDERS</button>
<button class="button" onclick="changedata(1)">PRODUCTS</button>
<button class="button" onclick="changedata(2)">SUPPLIER</button>
<div id="myorders">
<p>Laptop, Earphone</p>
</div>
<div id="myproducts">
<p>Earphone, smart watch</p>
</div>
<div id="mysupplier">
<p>Amazon, E-kart</p>
</div>
If you would like to have the element toggle between hidden and shown on each button press, I recommend toggling a class with javascript, as such:
function changedata(parameter){
if(parameter==0){
document.getElementById('myorders').classList.toggle('active');
}
else if(parameter==1){
document.getElementById('myproducts').classList.toggle('active');
}
else{
document.getElementById('mysupplier').classList.toggle('active');
}
}
#myorders,
#myproducts,
#mysupplier{
font-size: 25px;
display: none;
}
#myorders.active,
#myproducts.active,
#mysupplier.active{
display: block;
}
<button class="button" onclick="changedata(0)">ORDERS</button>
<button class="button" onclick="changedata(1)">PRODUCTS</button>
<button class="button" onclick="changedata(2)">SUPPLIER</button>
<div id="myorders">
<p>Laptop, Earphone</p>
</div>
<div id="myproducts">
<p>Earphone, smart watch</p>
</div>
<div id="mysupplier">
<p>Amazon, E-kart</p>
</div>
There are slightly easier ways to connect each div to its corresponding button, and one of them is to use data attributes. We can add a data attribute to each button the text of which matches the id of its corresponding div.
(I'm assuming that when you click on one button all the other divs are hidden, and only its div shows.)
This example uses more modern JS techniques but I'll guide you through them, comment everything, and provide documentation at the end. You don't have to understand everything here but you're probably going to bump up against these things eventually, so you might as well take a look at them now.
Here's a rundown of how this all works:
Remove the inline listeners from the buttons. Modern JS uses addEventListener.
Wrap the buttons in a container. What we're going to use is a technique called event delegation. Instead of attaching listeners to every button we attach one to the container and this captures any events that "bubble up" the DOM from its child elements. We can then call a function when a child element is clicked.
The function does a few things. First it checks to see if the clicked element was actually a button. Then it hides all the "panels" by removing a class called "show" from them ("show" sets the element's display to block - initially all panels have their display set to none). Then based on the id from the button's data attribute it forms a selector with it, and we use that to target its corresponding div and apply the "show" class.
// Cache out buttons container, and all of the panels
const buttons = document.querySelector('.buttons');
const panels = document.querySelectorAll('.panel');
// Add an event listener to the buttons container
buttons.addEventListener('click', handleClick);
// When a child element of `buttons` is clicked
function handleClick(e) {
// Check to see if its a button
if (e.target.matches('button')) {
// For every element in the `panels` node list use `classList`
// to remove the show class
panels.forEach(panel => panel.classList.remove('show'));
// "Destructure" the `id` from the button's data set
const { id } = e.target.dataset;
// Create a selector that will match the corresponding
// panel with that id. We're using a template string to
// help form the selector. Basically it says find me an element
// with a "panel" class which also has an id that matches the id of
// the button's data attribute which we just retrieved.
const selector = `.panel[id="${id}"]`;
// Select the `div` and, using classList, again add the
// show class
document.querySelector(selector).classList.add('show');
}
}
.panel { display: none; }
.show { display: block; }
.button { text-transform: uppercase; }
.button:hover { cursor: pointer; background-color: #fffff0; }
<div class="buttons">
<button data-id="myorders" class="button">Orders</button>
<button data-id="myproducts" class="button">Products</button>
<button data-id="mysupplier" class="button">Supplier</button>
</div>
<div class="panel" id="myorders"><p>Laptop, Earphone</p></div>
<div class="panel" id="myproducts"><p>Earphone, smart watch</p></div>
<div class="panel" id="mysupplier"><p>Amazon, E-kart</p></div>
Additional documentation
addEventListener
classList
Destructuring assignment
forEach
matches
querySelector
querySelectorAll
Template string

File Upload Form Not Working When Image Preview Wrapper Is Moved

I have a file uploader that handles multiple files which all works as intended.
The previews of the files to be uploaded are place inside a container in the upload form. When I move this element to a different part of the form (or outside of the form) the uploader doesn't work? I would ideally like the preview container that holds the images to be below the submit button (either inside or outside of the form).
I cannot for the life of me work out why this is happening. The element itself is empty prior to the image previews populating it, and I don't think the issue is being caused by the javascript (although happy to take guidance on this).
The element in question is this one:
<div id="show-selected-images"></div>
It currently sits in the middle of the form between the drop zone and the (hidden) file input element and a visible submit button, but as mentioned I would like to move it below the submit button.
NOTE: I've included the JS so the uploader works, but I suspect the JS may not be the issue.
Codepen: https://codepen.io/pauljohnknight/pen/xxdrvmR
// Query all needed elements in one go
const [dropZone, showSelectedImages, fileUploader] = document.querySelectorAll(
"#standard-upload-files, #drop-zone, #show-selected-images"
);
dropZone.addEventListener("click", (evt) => {
// assigns the dropzone to the hidden input element so when you click 'select files' it brings up a file picker window
fileUploader.click();
});
// Prevent browser default when draging over
dropZone.addEventListener("dragover", (evt) => {
evt.preventDefault();
});
fileUploader.addEventListener("change", (evt) => {
// Clear the already selected images
showSelectedImages.innerHTML = "";
// this function is further down but declared here and shows a thumbnail of the image
[...fileUploader.files].forEach(updateThumbnail);
});
dropZone.addEventListener("drop", (evt) => {
evt.preventDefault();
// Clear the already selected images
showSelectedImages.innerHTML = "";
// assign dropped files to the hidden input element
if (evt.dataTransfer.files.length) {
fileUploader.files = evt.dataTransfer.files;
}
// function is declared here but written further down
[...evt.dataTransfer.files].forEach(updateThumbnail);
});
// updateThumbnail function that needs to be able to handle multiple files
function updateThumbnail(file) {
if (file.type.startsWith("image/")) {
const thumbnailElement = new Image();
thumbnailElement.classList.add("drop-zone__thumb");
thumbnailElement.src = URL.createObjectURL(file);
showSelectedImages.append(thumbnailElement);
}
} // end of 'updateThumbnail' function
body {
margin: 0;
display: flex;
justify-content: center;
width: 100%;
}
form {
width: 30%;
}
#drop-zone {
border: 1px dashed;
width: 100%;
padding: 1rem;
margin-bottom: 1rem;
}
.select-files {
text-decoration: underline;
cursor: pointer;
}
/* image that is previewed prior to form submission*/
.drop-zone__thumb {
width: 200px;
height: auto;
display: block;
}
#submit-images {
margin-top: 1rem;
}
<form id="upload-images-form" enctype="multipart/form-data" method="post">
<h1>Upload Your Images</h1>
<div id="drop-zone" class="drop-zone">
<p class="td text-center">DRAG AND DROP IMAGES HERE</p>
<p>Or</p>
<p class="select-files">Select Files</p>
</div>
<!-- below is the element that has the issue when moved -->
<div id="show-selected-images"></div>
<div class="inner-input-wrapper">
<div class="upload-label-wrapper">
<input id="standard-upload-files" style="display:none" type="file" name="standard-upload-files[]" multiple>
</div>
<input type="submit" name="submit-images" id="submit-images" value="SUBMIT IMAGES">
</div>
</form>
I think this part causes the issue:
// Query all needed elements in one go
const [dropZone, showSelectedImages, fileUploader] = document.querySelectorAll(
"#standard-upload-files, #drop-zone, #show-selected-images"
);
It is very bad practice to query elements like that, because then you cannot change their order inside html without changing elements inside destructured array. In your case you are moving previews in the end and now your showSelectedImages variable is actually uploader and fileUploader is now div which holds previews, and everything messes up.
You need to query them one by one:
const fileUploader = document.getElementById('standard-upload-files');
const dropZone = document.getElementById('drop-zone');
const showSelectedImages = document.getElementById('show-selected-images');

relatedTarget is null in Firefox when onBlur is called

I'm trying to create a help message that will disappear when the user either clicks the toggle button to display the help message or clicks away by clicking elsewhere on the page. The solution appears to be to look at the relatedTarget property of the onblur event and prevent the onblur handler from running when the relatedTarget is the button to toggle the help message. This seems to work in Chrome, but in Firefox and Safari, the relatedTarget property is set to the container div rather than the button, which makes it impossible to distinguish between the toggle button click and a "click away".
I've created a simple demonstrator that illustrates the problem:
let openState = false;
let contentDiv = document.getElementById("show-hide-content");
let accordionDiv = document.getElementById("accordion");
let showHideButton = document.getElementById("show-hide-toggle");
function setOpenState(state) {
openState = state;
if(openState) {
contentDiv.style.visibility = "visible";
contentDiv.focus();
}
else {
contentDiv.style.visibility = "hidden";
}
}
function toggleVisibility(override) {
if (typeof override === "boolean") {
setOpenState(override);
}
else {
setOpenState(!openState);
}
}
function buttonClickHandler(event) {
toggleVisibility();
}
function contentBlurHandler(event) {
if(!accordionDiv.contains(event.relatedTarget)) {
toggleVisibility(false);
}
}
showHideButton.onclick = buttonClickHandler;
contentDiv.onblur = contentBlurHandler;
.parent {
display: flex;
width: 100vw;
height: 100vh;
flex-direction: row;
background-color: #409958;
}
.accordion {
background-color: #28a7c9;
}
.show-hide-content {
visibility: hidden;
background-color: #c91e63;
}
<h1>Show/Hide Test</h1>
<div class="parent">
<div class="drawer">
<div class="accordion" id="accordion">
<button class="show-hide-toggle" id="show-hide-toggle">Show/Hide</button>
<div class="show-hide-content" id="show-hide-content" tabindex="-1">
<p>This is some content that should be shown or hidden depending on the toggle.</p>
</div>
</div>
<div class="spacer">
</div>
</div>
</div>
This code works correctly in Chrome. However, in Firefox, clicking the "Show/Hide" button displays the hidden content, but doesn't hide it when the button is clicked again. As far as I can tell, this is because the onblur handler is hiding the div, and then the onclick handler is toggling it open again, even though I'm checking onblur.relatedTarget to ensure that it's not anywhere inside the drawer.
What is the correct way to detect click-away in Firefox?
The problem is that clicking the <button> doesn't focus it on some browser/OS combinations (notably on macOS except in Chrome), so onblur's event.relatedTarget is null as nothing on the page receives focus. If you SHIFT+TAB from the <div id="show-hide-content">, you'll see that relatedTarget is set as you expect, as the button does receive focus in this scenario.
I would run the code to hide the div off a small timeout, to give the click handler a chance to run first.
In the example below I implemented this suggestion and added some logging to make it easier to see what's going on:
let openState = false;
let contentDiv = document.getElementById("show-hide-content");
let accordionDiv = document.getElementById("accordion");
let showHideButton = document.getElementById("show-hide-toggle");
function setOpenState(state) {
openState = state;
if(openState) {
contentDiv.style.visibility = "visible";
contentDiv.focus();
}
else {
contentDiv.style.visibility = "hidden";
}
}
function buttonClickHandler(event) {
console.log("click, setting openState to", !openState);
setOpenState(!openState);
}
function contentBlurHandler(event) {
console.log("blur, relatedTarget is", event.relatedTarget);
setTimeout(function() {
console.log("blur, after timeout, openState is", openState);
setOpenState(false);
}, 100);
}
showHideButton.onclick = buttonClickHandler;
showHideButton.onmousedown = function() {console.log("button mousedown"); };
contentDiv.onblur = contentBlurHandler;
showHideButton.onfocus = function(ev) { console.log("button onfocus"); }
.parent {
display: flex;
width: 100vw;
height: 100vh;
flex-direction: row;
background-color: #409958;
}
.accordion {
background-color: #28a7c9;
}
.show-hide-content {
visibility: hidden;
background-color: #c91e63;
}
<h1>Show/Hide Test</h1>
<div class="parent">
<div class="drawer">
<div class="accordion" id="accordion">
<button class="show-hide-toggle" id="show-hide-toggle">Show/Hide</button>
<div class="show-hide-content" id="show-hide-content" tabindex="-1">
<p>This is some content that should be shown or hidden depending on the toggle.</p>
</div>
</div>
<div class="spacer">
</div>
</div>
</div>
This happened to me as well on both Safari and Firefox.
I had an use case where I needed to show clear icon/button only when user focused input (with input having value of course). And clicking that icon would make a blur on input and I had check if new focused element is contained within input but since relatedTarget was null I could not check it.
I added dummy span around my clear button and relatedTarget wasnt't null anymore:
<span aria-hidden="true" tabindex="-1" style="outline: none;">
<button>X</button>
</span>
For thoses who just need a specific value from the target, remember, if your application's design and size allows this possibility, that you can just hardcode the value:
onBlur={()=>function(value)}
For a lot of case it could just work, before an automatic, better scaling solution occurs you have this possibility.

jQuery.one() event handler is not executing

I am Trying to use jQuery.one() to disable a button that shows an image of a tree after it is clicked. The showImage function works fine, but not .one.
Can I not use javascript inside of a jquery event handler?
html:
<div class="grove">
<button id="plant" onclick="showImage()">Plant Orange Tree</button>
</div>
<div id="orange-tree-template">
<div class="orange-tree">
<h2>Tree Name</h2>
<h3>etc...</h3>
css:
.display-tree-big{
background: url('../images/tree_big.jpg');
background-repeat: no-repeat;
height:1000px;
width:1000px;
border: solid black 2px;
}
#orange-tree-template { visibility: hidden; }
javascript
function showImage() {
var img = document.getElementById('orange-tree-template');
img.style.visibility = 'visible';
}
$(document).ready(function() {
$("#plant").one( "click", function() {
document.getElementById("#plant").disabled = true;
});
});
A couple of issues.
You have an inline onclick handler assigned to the button. This will not respect the jQuery.one method, so because of error 2 you could continue to click the button and showImage will be called.
The function assigned to the click event via jQuery.one() is being called, however the statement document.getElementById("#plant") should not contain #, thus the button was not disabled.
jQuery(function($) {
$("#plant").one("click", function() {
// yes of course you can use JavaScript
document.getElementById('orange-tree-template').style.visibility = 'visible';
this.disabled = true;
});
});
#orange-tree-template {
visibility: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<button id="plant">Plant Orange Tree</button>
<div id="orange-tree-template">
TEST
</div>
Also the jQuery.one() method does not disable anything, it just executes a callback at most once per element per event type.

Categories