Making a JS function to delete a certain element - javascript

I need to make a task board website for a school project and need to have a function to delete only one of the notes that was clicked on. A little overview of the code below - user inputs a value, a function puts the values in an object that is pushed into an array and then saved in local storage (using it is required for the project, just mentioning). After the value is saved, the function runs a For loop on the array and prints the notes with the values on them. That works just fine for me. What's the direction I should take with making the delete function? Any help or general direction would be really appreciated, as I feel like I'm really struggling over something that should be rather simple.
// local storage function
var taskArray = [];
$(document).ready(function loadNotes() {
if (localStorage.getItem("user tasks") === null) {
console.log("local storage is empty");
var alertDiv = document.getElementById("addAlert")
alertDiv.innerHTML +=
`
<div class="alert alert-success alert-dismissable show hide">
<strong>Welcome to our task board!</strong> Enter your task, and the app will keep track of it for you, even if you leave the page!
</div>
`
} else {
var mainDiv = document.getElementById("maindiv");
var arrayFromStorage = localStorage.getItem('user tasks');
arrayFromStorage = JSON.parse(arrayFromStorage);
$("#maindiv").empty();
for (var index = 0; index < arrayFromStorage.length; index++) {
mainDiv.innerHTML +=
`
<span class="relative">
<img src="../assets/images/notebg.png" class="fade-in start imgSpacing" alt="">
<span class="centerOnNote" id="textspan" onclick="deleteNote(this)">
<span class="fas fa-times-circle"></span>
<br>
Your task = ${arrayFromStorage[index].name}
Complete by = ${arrayFromStorage[index].date}
</span>
`
}
}
})
function saveToLocalStorage() {
debugger;
var taskName = document.getElementById("task").value;
var taskDate = document.getElementById("date").value;
var task = {
name: taskName,
date: taskDate
}
taskArray.push(task);
var arrayToString = JSON.stringify(taskArray);
localStorage.setItem("user tasks", arrayToString);
var mainDiv = document.getElementById("maindiv");
var arrayFromStorage = localStorage.getItem('user tasks');
arrayFromStorage = JSON.parse(arrayFromStorage);
$("#maindiv").empty();
for (var index = 0; index < arrayFromStorage.length; index++) {
mainDiv.innerHTML +=
`
<span class="relative">
<img src="../assets/images/notebg.png" class="fade-in start imgSpacing" alt="">
<span class="centerOnNote" id="textspan" onclick="deleteNote(this)">
<span class="fas fa-times-circle"></span>
<br>
Your task = ${arrayFromStorage[index].name}
Complete by = ${arrayFromStorage[index].date}
</span>
`
}
}
function deleteNote(note) {
}
.background-image {
background-image: url("../assets/images/wallpaper/chalkboard.jpg");
background-size: 100%;
}
.pageheader {
color: white;
text-align: center;
padding: 30px;
font-size: 80px;
}
.centerInput {
margin: 10px 25px 30px 25px;
}
.imgContainer {
width: 70%;
margin: auto;
}
#-webkit-keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
#-moz-keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
#keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
.fade-in {
-webkit-animation: fadeIn ease-in 1;
-moz-animation: fadeIn ease-in 1;
animation: fadeIn ease-in 1;
-webkit-animation-fill-mode: forwards;
-moz-animation-fill-mode: forwards;
animation-fill-mode: forwards;
-webkit-animation-duration: 1s;
-moz-animation-duration: 1s;
animation-duration: 1s;
}
.fade-in.start {
-webkit-animation-delay: 0s;
-moz-animation-delay: 0s;
animation-delay: 0s;
}
.imgSpacing {
padding: 2% 2% 2% 35px;
margin: auto;
position: relative;
}
.relative {
position: relative;
}
.centerOnNote {
position: absolute;
top: 50%;
left: 45%;
transform: translate(-50%, -45%);
overflow-y: scroll;
overflow-x: hidden;
}
#textspan {
width: 150px;
height: 160px;
overflow-y: scroll;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin="anonymous">
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU"
crossorigin="anonymous">
<title></title>
</head>
<body class="background-image">
<h1 class="pageheader">My Task Board</h1>
<form class="" action="index.html" method="post">
<div class="container">
<div class="row">
<input type="text" class="form-control col-sm centerInput" id="task" placeholder="Enter a Task">
<input type="date" class="form-control col-sm centerInput" id="date" value="">
</div>
<div class="form-group">
<input type="button" class="form-control btn btn-success" id="submit" value="Submit Task" onclick="saveToLocalStorage()">
</div>
<div class="form-group">
<input type="reset" class="form-control btn btn-success " id="reset" value="Reset Form">
</div>
<div id="addAlert">
</div>
</div>
</form>
<!-- style="width: 70%; margin: auto; position: relative;" -->
<div class="imgContainer" id="maindiv">
</div>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript" src="scripts.js"></script>
</body>
</html>

Instead of passing this to deleteNote which doesn't really help you, pass the current index:
onclick="deleteNote(${index})"
that way you can .splice() out that index from the array and rerender / save to localStorage.
PS: That string building is not the most elegant version though, instead you could use the DOM API and .addEventListener.

Related

transition-group with v-show not working in vue2

I want to add some transition-delay effects to each element in transition-group,but something really weird happens.
The first time come and leave works fine,but the second time come and leave both not working.
I thought of many reasons such as key problem,transition style problem,element style problem,but all failed. Maybe settimeout function in js callback can solve it, but is there another way?
I made a simple transition element as comparison,it works fine.
I'll be appreciate if someone can spend time working out this issue.
here are code below
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>v-show标签过渡实现特效单项目探究</title>
<script src="vue.js"></script>
</head>
<body>
<div id="root">
<button #click="isShow2=!isShow2">显示/隐藏</button>
<transition
name="hello"
appear
>
<div class="divwidth" v-show="isShow2" :style="[{transition :'500ms'},{transitionDelay:100+'ms'}]">
<span class="content">英语第1次考试</span>
</div>
</transition>
<button #click="isShow=!isShow">显示/隐藏</button>
<Transition-group
name="hello"
appear
>
<div class="divwidth" v-show="isShow" key="11" :style="[{transition :'500ms'},{transitionDelay:100+'ms'}]">
<span class="content">英语第1次考试</span>
</div>
<div class="divwidth" v-show="isShow" key="12" :style="[{transition :'300ms'},{transitionDelay:100+'ms'}]">
<span class="content">英语第2次考试</span>
</div>
</Transition-group>
</div>
</body>
<script>
new Vue({
el: "#root",
data() {
return {
isShow: true,
isShow2: true
}
},
})
</script>
<style>
.divwidth {
width: 60%;
margin-top: 15px;
}
.content {
/*background-image: linear-gradient(red, yellow, blue);用于创建一个线性渐变的" 图像 "*/
background-color: orange;
width: auto;
/*margin: 20px;*/
/*margin-top: 0px;*/
/*padding-top: 10px;*/
padding: 6px;
font-size: 20px;
border: 10px;
border-radius: 8px;
/*line-height: 30px;*/
}
/*.hello-enter-active, .hello-leave-active {*/
/* transition: 300ms linear;*/
/* !*transition-delay:200ms*!*/
/*}*/
.hello-enter, .hello-leave-to {
opacity: 0;
transform: translateX(50%);
}
/*.hello-move { transition: all 0.6s ease; }*/
/*.hello-leave-active{*/
/* position: absolute; */
/*}*/
</style>
</html>
I tried v-if,it works fine,but I don't want to get rid of elements from DOM .
as to v-show I thought of many reasons such as key problem,transition style problem,element style problem,but all failed.
I expect to see transition effects happens every time i click the button,but in my example ,effects failed at second time come and leave.
for me the is working:
vue docomotion
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>v-show标签过渡实现特效单项目探究</title>
</head>
<body>
<div id="root">
<button #click="isShow2=!isShow2">显示/隐藏</button>
<transition name="hello" appear>
<div class="divwidth" v-show="isShow2" :style="[{transition :'500ms'},{transitionDelay:100+'ms'}]">
<span class="content">英语第1次考试</span>
</div>
</transition>
<button #click="isShow=!isShow">显示/隐藏</button>
<transition v-for="(btn,index) in btns" :key="index" name="hello" appear>
<div class="divwidth" v-show="isShow" :style="[{transition :btn.transition},{transitionDelay:100+'ms'}]">
<span class="content">{{btn.text}}</span>
</div>
</transition>
</div>
<script type="module">
import Vue from "https://cdn.jsdelivr.net/npm/vue#2.7.14/dist/vue.esm.browser.js"
console.log(Vue)
const vue = new Vue({
el: "#root",
data() {
return {
isShow: true,
isShow2: true,
btns: [
{ text: "英语第1次考试", transition: "500ms" },
{ text: "英语第2次考试", transition: "500ms" }
],
}
},
})
</script>
</body>
<style>
.divwidth {
width: 60%;
margin-top: 15px;
}
.content {
/*background-image: linear-gradient(red, yellow, blue);用于创建一个线性渐变的" 图像 "*/
background-color: orange;
width: auto;
/*margin: 20px;*/
/*margin-top: 0px;*/
/*padding-top: 10px;*/
padding: 6px;
font-size: 20px;
border: 10px;
border-radius: 8px;
/*line-height: 30px;*/
}
/*.hello-enter-active, .hello-leave-active {*/
/* transition: 300ms linear;*/
/* !*transition-delay:200ms*!*/
/*}*/
.hello-enter,
.hello-leave-to {
opacity: 0;
transform: translateX(50%);
}
/*.hello-move { transition: all 0.6s ease; }*/
/*.hello-leave-active{*/
/* position: absolute; */
/*}*/
</style>
</html>

Dynamically added form elements hides other elements until resize

I have a form with a button that when clicked adds a new input to the form.
While the input is added, the form does not expand so that any contend below the added form is no longer visible, however the form resizes and all content is viewable if a user resizes their window.
See below
Is this a CSS issue? If so what elements could it possibly be?
The HTML
<div id="single-form-next-prev" class="multisteps-form__panel shadow p-4 rounded bg-white" data-animation="scaleIn">
<h3 class="text-center multisteps-form__title">Skills</h3>
<div id="form-content-1" class="multisteps-form__content">
<div id="input-grp-single-1" class="form-row mt-4">
<div class="col-12"><input class="form-control multisteps-form__input" type="text" placeholder="Skill 1"></div>
</div>
<br>
<button id='addButton' class="btn btn-outline-primary text-truncate float-none float-sm-none add-another-btn" data-bss-hover-animate="pulse" type="button">Add Skill<i class="fas fa-plus-circle edit-icon"></i></button>
<div id="next-prev-buttons" class="button-row d-flex mt-4"><button class="btn btn btn-primary js-btn-prev" type="button" title="Prev">Prev</button><button class="btn btn btn-primary ml-auto js-btn-next" type="button" title="Next">Find Results</button></div>
</div>
</div>
The JQUERY
$(document).ready(function(){
let id = 1;
$('#addButton').click(function() {
$('#input-grp-single-'+id).after('<div id="input-grp-single-'+(id+1)+'" class="form-row mt-4"> <div class="col-12"><input class="form-control multisteps-form__input" type="text" placeholder="Skill '+(id+1)+'"></div></div>');
id++;
});
});
The CSS
.multisteps-form__form {
position: relative;
}
.multisteps-form__panel {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 0;
opacity: 0;
visibility: hidden;
}
.multisteps-form__panel.js-active {
height: auto;
opacity: 1;
visibility: visible;
}
.multisteps-form__panel[data-animation="scaleIn"] {
-webkit-transform: scale(0.9);
transform: scale(0.9);
}
.multisteps-form__panel[data-animation="scaleIn"].js-active {
transition-property: all;
transition-duration: 0.2s;
transition-timing-function: linear;
transition-delay: 0s;
-webkit-transform: scale(1);
transform: scale(1);
}
Codepen link added
https://codepen.io/jdog6652/pen/ExZJvaQ
Remove the overflow-hidden class on your #multple-step-form-n element:
$(document).ready(function() {
let id = 1;
$('[data-bss-hover-animate]')
.mouseenter(function() {
var elem = $(this);
elem.addClass('animated ' + elem.attr('data-bss-hover-animate'))
})
.mouseleave(function() {
var elem = $(this);
elem.removeClass('animated ' + elem.attr('data-bss-hover-animate'))
});
$('#addButton').click(function() {
$('#input-grp-single-' + id).after('<div id="input-grp-single-' + (id + 1) + '" class="form-row mt-4"> <div class="col-12"><input class="form-control multisteps-form__input" type="text" placeholder="Skill ' + (id + 1) + '"></div></div>');
id++;
});
});
//DOM elements
const DOMstrings = {
stepsBtnClass: 'multisteps-form__progress-btn',
stepsBtns: document.querySelectorAll(`.multisteps-form__progress-btn`),
stepsBar: document.querySelector('.multisteps-form__progress'),
stepsForm: document.querySelector('.multisteps-form__form'),
stepsFormTextareas: document.querySelectorAll('.multisteps-form__textarea'),
stepFormPanelClass: 'multisteps-form__panel',
stepFormPanels: document.querySelectorAll('.multisteps-form__panel'),
stepPrevBtnClass: 'js-btn-prev',
stepNextBtnClass: 'js-btn-next'
};
//remove class from a set of items
const removeClasses = (elemSet, className) => {
elemSet.forEach(elem => {
elem.classList.remove(className);
});
};
//return exect parent node of the element
const findParent = (elem, parentClass) => {
let currentNode = elem;
while (!currentNode.classList.contains(parentClass)) {
currentNode = currentNode.parentNode;
}
return currentNode;
};
//get active button step number
const getActiveStep = elem => {
return Array.from(DOMstrings.stepsBtns).indexOf(elem);
};
//set all steps before clicked (and clicked too) to active
const setActiveStep = activeStepNum => {
//remove active state from all the state
removeClasses(DOMstrings.stepsBtns, 'js-active');
//set picked items to active
DOMstrings.stepsBtns.forEach((elem, index) => {
if (index <= activeStepNum) {
elem.classList.add('js-active');
}
});
};
//get active panel
const getActivePanel = () => {
let activePanel;
DOMstrings.stepFormPanels.forEach(elem => {
if (elem.classList.contains('js-active')) {
activePanel = elem;
}
});
return activePanel;
};
//open active panel (and close unactive panels)
const setActivePanel = activePanelNum => {
//remove active class from all the panels
removeClasses(DOMstrings.stepFormPanels, 'js-active');
//show active panel
DOMstrings.stepFormPanels.forEach((elem, index) => {
if (index === activePanelNum) {
elem.classList.add('js-active');
setFormHeight(elem);
}
});
};
//set form height equal to current panel height
const formHeight = activePanel => {
const activePanelHeight = activePanel.offsetHeight;
DOMstrings.stepsForm.style.height = `${activePanelHeight}px`;
};
const setFormHeight = () => {
const activePanel = getActivePanel();
formHeight(activePanel);
};
//STEPS BAR CLICK FUNCTION
DOMstrings.stepsBar.addEventListener('click', e => {
//check if click target is a step button
const eventTarget = e.target;
if (!eventTarget.classList.contains(`${DOMstrings.stepsBtnClass}`)) {
return;
}
//get active button step number
const activeStep = getActiveStep(eventTarget);
//set all steps before clicked (and clicked too) to active
setActiveStep(activeStep);
//open active panel
setActivePanel(activeStep);
});
//PREV/NEXT BTNS CLICK
DOMstrings.stepsForm.addEventListener('click', e => {
const eventTarget = e.target;
//check if we clicked on `PREV` or NEXT` buttons
if (!(eventTarget.classList.contains(`${DOMstrings.stepPrevBtnClass}`) || eventTarget.classList.contains(`${DOMstrings.stepNextBtnClass}`))) {
return;
}
//find active panel
const activePanel = findParent(eventTarget, `${DOMstrings.stepFormPanelClass}`);
let activePanelNum = Array.from(DOMstrings.stepFormPanels).indexOf(activePanel);
//set active step and active panel onclick
if (eventTarget.classList.contains(`${DOMstrings.stepPrevBtnClass}`)) {
activePanelNum--;
} else {
activePanelNum++;
}
setActiveStep(activePanelNum);
setActivePanel(activePanelNum);
});
//SETTING PROPER FORM HEIGHT ONLOAD
window.addEventListener('load', setFormHeight, false);
//SETTING PROPER FORM HEIGHT ONRESIZE
window.addEventListener('resize', setFormHeight, false);
//changing animation via animation select !!!YOU DON'T NEED THIS CODE (if you want to change animation type, just change form panels data-attr)
const setAnimationType = newType => {
DOMstrings.stepFormPanels.forEach(elem => {
elem.dataset.animation = newType;
});
};
//selector onchange - changing animation
const animationSelect = document.querySelector('.pick-animation__select');
/*
====NOTICE====
The block of code below was giving an error not related to the question, so it was commented out
animationSelect.addEventListener('change', () => {
const newAnimationType = animationSelect.value;
setAnimationType(newAnimationType);
});
*/
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body a {
color: inherit;
text-decoration: none;
}
.multisteps-form__progress {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(0, 1fr));
}
.multisteps-form__progress-btn {
transition-property: all;
transition-duration: 0.15s;
transition-timing-function: linear;
transition-delay: 0s;
position: relative;
padding-top: 20px;
color: rgba(108, 117, 125, 0.7);
text-indent: -9999px;
border: none;
background-color: transparent;
outline: none !important;
cursor: pointer;
}
#media (min-width: 500px) {
.multisteps-form__progress-btn {
text-indent: 0;
}
}
.multisteps-form__progress-btn:before {
position: absolute;
top: 0;
left: 50%;
display: block;
width: 13px;
height: 13px;
content: '';
-webkit-transform: translateX(-50%);
transform: translateX(-50%);
transition: all 0.15s linear 0s, -webkit-transform 0.15s cubic-bezier(0.05, 1.09, 0.16, 1.4) 0s;
transition: all 0.15s linear 0s, transform 0.15s cubic-bezier(0.05, 1.09, 0.16, 1.4) 0s;
transition: all 0.15s linear 0s, transform 0.15s cubic-bezier(0.05, 1.09, 0.16, 1.4) 0s, -webkit-transform 0.15s cubic-bezier(0.05, 1.09, 0.16, 1.4) 0s;
border: 2px solid currentColor;
border-radius: 50%;
background-color: #fff;
box-sizing: border-box;
z-index: 3;
}
.multisteps-form__progress-btn:after {
position: absolute;
top: 5px;
left: calc(-50% - 13px / 2);
transition-property: all;
transition-duration: 0.15s;
transition-timing-function: linear;
transition-delay: 0s;
display: block;
width: 100%;
height: 2px;
content: '';
background-color: currentColor;
z-index: 1;
}
.multisteps-form__progress-btn:first-child:after {
display: none;
}
.multisteps-form__progress-btn.js-active {
color: #007bff;
}
.multisteps-form__progress-btn.js-active:before {
-webkit-transform: translateX(-50%) scale(1.2);
transform: translateX(-50%) scale(1.2);
background-color: currentColor;
}
.multisteps-form__form {
position: relative;
}
.multisteps-form__panel {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 0;
opacity: 0;
visibility: hidden;
}
.multisteps-form__panel.js-active {
height: auto;
opacity: 1;
visibility: visible;
}
.multisteps-form__panel[data-animation="scaleIn"] {
-webkit-transform: scale(0.9);
transform: scale(0.9);
}
.multisteps-form__panel[data-animation="scaleIn"].js-active {
transition-property: all;
transition-duration: 0.2s;
transition-timing-function: linear;
transition-delay: 0s;
-webkit-transform: scale(1);
transform: scale(1);
}
.edit-icon {
margin-left: 10px;
font-size: 15px;
}
.add-another-btn {
border: 2px solid #5C99C7;
color: #5C99C7;
font-size: 14px;
line-height: 1.8em;
}
.add-another-btn:hover {
border: 2px solid #5C99C7;
background: #5C99C7;
color: white;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css">
<body style="background: var(--gray-dark);">
<h1 class="text-center" style="color: var(--light);">Skill Finder</h1>
<section>
<div id="multple-step-form-n" class="container" style="margin-top: 0px;margin-bottom: 10px;padding-top: 57px;">
<div id="progress-bar-button" class="multisteps-form">
<div class="row">
<div class="col-12 col-lg-8 ml-auto mr-auto mb-4">
<div class="multisteps-form__progress"><a class="btn multisteps-form__progress-btn js-active" role="button" title="User Info">City</a><a class="btn multisteps-form__progress-btn" role="button" title="User Info">Skills</a><a class="btn multisteps-form__progress-btn" role="button"
title="User Info">Results</a></div>
</div>
</div>
</div>
<div id="multistep-start-row" class="row">
<div id="multistep-start-column" class="col-12 col-lg-8 m-auto">
<form id="main-form" class="multisteps-form__form">
<div id="single-form-next" class="multisteps-form__panel shadow p-4 rounded bg-white js-active" data-animation="scaleIn">
<h3 class="text-center multisteps-form__title">Enter your City</h3>
<div id="form-content" class="multisteps-form__content">
<div id="input-grp-single" class="form-row mt-4">
<div class="col-12"><input class="form-control multisteps-form__input" type="text" placeholder="City"></div>
</div>
<div id="next-button" class="button-row d-flex mt-4"><button class="btn btn btn-primary ml-auto js-btn-next" type="button" title="Next">Next</button></div>
</div>
</div>
<div id="single-form-next-prev" class="multisteps-form__panel shadow p-4 rounded bg-white" data-animation="scaleIn">
<h3 class="text-center multisteps-form__title">Skills</h3>
<div id="form-content-1" class="multisteps-form__content">
<div id="input-grp-single-1" class="form-row mt-4">
<div class="col-12"><input class="form-control multisteps-form__input" type="text" placeholder="Skill 1"></div>
</div>
<br>
<button id='addButton' class="btn btn-outline-primary text-truncate float-none float-sm-none add-another-btn" data-bss-hover-animate="pulse" type="button">Add Skill<i class="fas fa-plus-circle edit-icon"></i></button>
<div id="next-prev-buttons" class="button-row d-flex mt-4"><button class="btn btn btn-primary js-btn-prev" type="button" title="Prev">Prev</button><button class="btn btn btn-primary ml-auto js-btn-next" type="button" title="Next">Find Results</button></div>
</div>
</div>
<div id="single-form-next-prev-1" class="multisteps-form__panel shadow p-4 rounded bg-white" data-animation="scaleIn">
<h3 class="text-center multisteps-form__title">Map</h3>
<div id="form-content-2" class="multisteps-form__content">
<div id="mapid"></div>
<div id="next-prev-buttons-1" class="button-row d-flex mt-4"><button class="btn btn btn-primary js-btn-prev" type="button" title="Prev">Prev</button><button class="btn btn btn-primary ml-auto js-btn-next" type="button" title="Next">Next</button></div>
</div>
</div>
</form>
</div>
</div>
</div>
</section>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/js/bootstrap.min.js"></script>

Pre-loader loads behind block content and navbar

I have a preloader which is loading in front of the <body> but not in front of the site <navbar> or the {% block content %}. #preloader{z-index:999;}
Django 2.2.7
Bootstrap 4.4.1
JQuery 3.4.1
$(window).on('load', function() {
$('#preloader').addClass('loaded');
setTimeout(function(){
$('#preloader').addClass("notta");
}, 2000);
});
#preloader:before {
content: '';
z-index: 999;
display: block;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,1);
}
#preloader.loaded {
opacity: 0;
transition: .3s ease-in 1s;
}
#preloader.notta {
display: none;
}
<header>
<div class="flex-center" id="preloader">
<div class="preloader-wrapper active">
<div class="spinner-grow text-warning" role="status">
<span class="sr-only">Loading...</span>
</div>
</div>
</div>
</header>
If I put the preloader at the bottom of the <body> it will load on top of the {% block content %} but underneath the navbar. I assume this means it has to do with the order of loading?
How do I get it to show up above everything on the site?
Problem come here from your :before element in css. Just combine it with #preloader:
$(window).on('load', function() {
$('#preloader').addClass('loaded');
setTimeout(function() {
$('#preloader').addClass("notta");
}, 2000);
});
#preloader {
color: white;
z-index: 999;
display: block;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 1);
}
#preloader.loaded {
opacity: 0;
transition: .3s ease-in 1s;
}
#preloader.notta {
display: none;
}
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<header>
<div class="flex-center" id="preloader">
<div class="preloader-wrapper active">
<div class="spinner-grow text-warning" role="status">
<span class="sr-only">Loading...</span>
</div>
</div>
</div>
</header>
You can write this code with pure Javascript
`let loader = document.getElementById('preloader');
window.addEventListener('load',function(){
loader.style.display = 'none';
});`
Try this

How can I change the text content in html to a randomly generated value from Javascript?

I am facing an issue while coding for a small project. Basically, I am trying to make a flip box which, upon clicked by a user will show him if its any of the superhero mentioned in an array. Please take a look at this code pen to have an idea about it: https://codepen.io/zakero/pen/YmGmwK .
The code works perfectly when I am using alert(), as you can see in code pen. It randomizes every time a square is clicked. But I want the result to be displayed after it's clicked and flipped. I mean instead of "Back", I want it to be the random names of the superheroes. I have both tried .textContent and .innerHTML to change it but it doesn't seem to work This is the code I have tried:
Javascript:
function setupSquares() {
for(var i = 0; i < frontSquare.length; i++) {
frontSquare[i].addEventListener("click", function() {
var randomNumber = frontSquare[i] = generateRandomNumbers(numbers);
for(var j = 0; j < superhero.length; j++) {
var index = superhero.indexOf(superhero[j]);
if(randomNumber === index){
backSquare.textContent = superhero[j];
}
}
});
}
}
var superhero = ["Ironman", "Superman", "Batman", "Spiderman", "Black Panther", "Hawkeye", "Hulk", "Captain America", "Thor", "Quicksilver", "Loki"];
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var frontSquare = document.querySelectorAll(".front");
var backSquare = document.querySelectorAll(".back");
init();
function init() {
setupSquares();
}
function generateRandomNumbers(num) {
var random = Math.floor(Math.random() * num.length + 1);
return random;
}
function setupSquares() {
for (var i = 0; i < frontSquare.length; i++) {
frontSquare[i].addEventListener("click", function() {
var randomNumber = frontSquare[i] = generateRandomNumbers(numbers);
for (var j = 0; j < superhero.length; j++) {
var index = superhero.indexOf(superhero[j]);
if (randomNumber === index) {
alert(superhero[j]);
}
}
});
}
}
#import url(https://fonts.googleapis.com/css?family=Open+Sans);
body {
background: #96CEB4;
font-family: Open Sans;
font-size: 50px;
color: #222;
}
#container {
margin: 37px auto;
max-width: 1000px;
background: #96CEB4;
height: 550px;
overflow: hidden;
}
.square {
width: 30%;
padding-top: 35px;
margin: 1.66%;
float: left;
-webkit-perspective: 1000px;
perspective: 1000px;
-webkit-transform-style: preserve-3d;
transform-style: preserve-3d;
display: block;
height: 200px;
-webkit-transform: translate(0%, 0%);
transform: translate(0%, 0%);
cursor: pointer;
/*border-radius: 50px;*/
}
.card {
position: relative;
height: 100%;
width: 100%;
-webkit-transform-style: preserve-3d;
transform-style: preserve-3d;
-webkit-transition: all 600ms;
transition: all 600ms;
z-index: 20;
}
.card div {
position: absolute;
height: 100%;
width: 100%;
background: #FFEEAD;
text-align: center;
line-height: 200px;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
border-radius: 10px;
}
.card .back {
background: #FF6F69;
color: #FFF;
-webkit-transform: rotateX(180deg);
transform: rotateX(180deg);
}
label:hover .card {
-webkit-transform: rotateX(20deg);
transform: rotateX(20deg);
box-shadow: 0 20px 20px rgba(50, 50, 50, .2);
}
input {
display: none;
}
:checked+.card {
transform: rotateX(180deg);
-webkit-transform: rotateX(180deg);
}
label:hover :checked+.card {
transform: rotateX(160deg);
-webkit-transform: rotateX(160deg);
box-shadow: 0 20px 20px rgba(255, 255, 255, .2);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" type="text/css" href="css/style.css">
<title>Flip Box</title>
</head>
<body>
<div id="container">
<label class="square">
<input type="checkbox"/>
<div class="card">
<div class="front">Front</div>
<div class="back">Back</div>
</div>
</label>
<label class="square">
<input type="checkbox"/>
<div class="card">
<div class="front">Front</div>
<div class="back">Back</div>
</div>
</label>
<label class="square">
<input type="checkbox"/>
<div class="card">
<div class="front">Front</div>
<div class="back">Back</div>
</div>
</label>
<label class="square">
<input type="checkbox"/>
<div class="card">
<div class="front">Front</div>
<div class="back">Back</div>
</div>
</label>
<label class="square">
<input type="checkbox"/>
<div class="card">
<div class="front">Front</div>
<div class="back">Back</div>
</div>
</label>
<label class="square">
<input type="checkbox"/>
<div class="card">
<div class="front">Front</div>
<div class="back">Back</div>
</div>
</label>
</div>
<script type="text/javascript" src="js/script.js"></script>
</body>
</html>
You could get to the .back of the .front clicked using the following:
this.parentNode.querySelector('.back').innerText = superhero[j];
You see, for your case, you're missing a bunch of things. First of all backSquare is an array, so you have to access the element which you want to modify out of it. Instead of backSquare.textContent = superhero[j];, use backSquare[i].innerText = superhero[j] which allows you to access the same i-th backSquare as frontSquare. But careful, this would not work because you're using var i = ... in the loop variable and var doesn't create a closure over the loop. So to fix that, you could change var to let.
More about this here: Closures versus ES6 Let
Or, you could use this which refers to the current element being clicked. this gets populated by the current element being clicked with your addEventListener function.
More about this: https://codeburst.io/all-about-this-and-new-keywords-in-javascript-38039f71780c
Demo: https://codepen.io/anon/pen/JgbPEK
You can also do it like this this.closest('.card').querySelector('.back').textContent = superhero[j]

How to makea div appear after X seconds with javascript?

I am starting with JS and I would like to make the block on the following code appear after 10 seconds.
https://jsfiddle.net/74hmx0vb/1
<div class='popup1' id="popup1">
<div class="container">
<div class="row rowpopup">
<div class="iconpopup">
<img class="imgpopup" src="" />
</div>
<div class="textpopup">
<div class="textpopup1">
</div>
<div class="textpopup2">
</div>
</div>
<button type="button" class="close" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
</div>
</div>
I would also like to add a slide-in transition when the block appears.
How to do that?
This is using CSS for the animation.
Move .popup1 out of the view to prepare for its animation by setting left: -350px;
Then #keyframes leftSlideIn will contain the style to animate into.
Finally, get .popup1 to animate using leftSlideIn.
animation-fill-mode of forwards will keep the last keyframe state after animation ends.
.popup1 {
height: 100px;
width: 300px;
position: fixed;
z-index: 99999;
background: white;
bottom: 50px;
left: -350px;
border-radius: 10px;
box-shadow: 0 0 30px rgba(0, 0, 0, 0.45);
-moz-box-shadow: 0 0 30px rgba(0, 0, 0, 0.45);
-webkit-box-shadow: 0 0 30px rgba(0, 0, 0, 0.45);
animation: 1s leftSlideIn forwards;
animation-delay: 10s;
}
#keyframes leftSlideIn {
to {
left: 50px;
}
}
.rowpopup {
display: inline-flex;
}
.textpopup {
padding: 10px;
margin-top: -15px;
}
.textpopup1 {
font-size: 16px;
}
.textpopup2 {
font-size: 14px;
}
.iconpopup {
padding: 10px;
}
.imgpopup {
width: 30px;
}
.hidepopup {
display: none !important;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div class="popup1" id="popup1">
<div class="container">
<div class="row rowpopup">
<div class="iconpopup">
<img
class="imgpopup"
src="https://cdn.shopify.com/s/files/1/0076/6931/7690/files/clock2.png?8339"
/>
</div>
<div class="textpopup">
<div class="textpopup1">
Order as soon as possible
</div>
<div class="textpopup2">
there is little time remaining for this deal to end
</div>
</div>
<button type="button" class="close" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
</div>
</div>
Here is a jQuery- CSS solution. I have added the hidepopup class to the main div of you content. I remove it after 10 seconds and add the animation class.
$(document).ready(function(){
setTimeout(displayBox, 10000);
});
function displayBox(){
$('.popup1').removeClass('hidepopup');
$('.popup1').addClass('anim-effect ');
}
.popup1 {
height: 100px;
width:300px;
position: fixed;
z-index: 99999;
background: white;
border-radius: 10px;
box-shadow: 0 0 30px rgba(0,0,0,0.45);
}
.anim-effect{
bottom: 50px;
left:50px;
-webkit-animation: slideIn 1s forwards;
-moz-animation: slideIn 1s forwards;
animation: slideIn 1s forwards;
}
#-webkit-keyframes slideIn {
0% {
transform: translateX(-900px);
}
100% {
transform: translateX(0);
}
}
.rowpopup {
display: inline-flex;
}
.textpopup {
padding: 10px;
margin-top: -15px;
}
.textpopup1 {
font-size:16px;
}
.textpopup2 {
font-size:14px;
}
.iconpopup {
padding:10px;
}
.imgpopup {
width:30px;
}
.hidepopup {
display: none !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div class='popup1 hidepopup' id="popup1">
<div class="container">
<div class="row rowpopup">
<div class="iconpopup">
<img class="imgpopup" src="https://cdn.shopify.com/s/files/1/0076/6931/7690/files/clock2.png?8339" />
</div>
<div class="textpopup">
<div class="textpopup1">
Order as soon as possible
</div>
<div class="textpopup2">
there is little time remaining for this deal to end
</div>
</div>
<button type="button" class="close" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
</div>
</div>
document.getElementById("div_to_display").style.display="block"},time);
so the sample code will look like this
document.getElementById("textpopup1").style.display="block"},10000);
the textpopup1 will display after 10 seconds.

Categories

Resources