I have a part of the page that looks like this (i use pug view engine)
<div class="product">
<div class="name">#{product.product_name}</div>
<div class="category">#{product.category}</div>
<div class="description">
| #{product.product_description}
</div>
<div class="amount">#{product.product_amount}</div>
<div class="count-stock">#{product.product_count_stock}</div>
<div>
<a href="/editProductProperties?productId=#{product.product_id}">
<img src="images/pencil-white.svg" class="pencil-icon icon" data-product_id="#{product.product_id}"/>
</a>
<img src="images/trash.svg" class="trash-icon icon"/>
</div>
</div>
And style for this part:
.product {
display: grid;
grid-template-columns: [name] 207px [category] 150px [description] 1fr [amount] 100px [count-stock] 100px [action] 54px;
}
.product > div:not(:last-child) {
padding-right: 5px;
}
.product {
padding: 20px 0;
border-top: 1px solid #f2f2f2;
position: relative;
}
.product::after {
width: 0;
height: 0;
border-top: 100px solid red;
border-right: 100px solid transparent;
position: absolute;
}
.product .description {
position: relative;
}
.product .description .showButton {
position: absolute;
top: 10px;
right: 0;
text-decoration: underline;
cursor: pointer;
}
.product:last-child {
border-bottom: 1px solid #f2f2f2;
}
.product:hover {
background: #555454;
}
And js:
window.onresize = addShowButton;
function addShowButton() {
productDescriptionList.forEach(el => {
if(el.offsetHeight > 40) {
if(el.children.length === 0) {
let showButton = document.createElement('span');
showButton.className = 'showButton';
showButton.innerText = 'Показать полностью';
el.append(showButton);
}
el.style["max-height"] = '40px';
el.style.overflow = 'hidden';
} else if(el.offsetHeight <= 40) {
el.style["max-height"] = 'initial';
el.style.overflow = 'visible';
if(el.children.length > 0) {
el.children[0].remove();
}
}
});
}
addShowButton();
The problem is that el.offsetHeight takes either the old element height values or the values before all styles are applied.
That is, I look at the height value of the element in the inspector and it is 80, and offsetHeight = 36 in console and I can not understand why this is
Related
I'm trying to create a simple drag & drop example to use that will allow swapping of items. For example:
Item 0
Item 1
Item 2
Item 3
If I drag and drop "Item 0" over "Item 3" they should swap places. What I have below does not swap the correct elements, will also make some slots "un-droppable" and error out due to e.dataTransfer not providing any data.
const log = console.log.bind(console);
const $ = document.getElementById.bind(document);
function drop(e) {
e.preventDefault();
let dragindex = 0;
let clone = e.target.cloneNode(true);
let data = e.dataTransfer.getData("text/plain");
if (clone.dataset.id !== data) {
[...$("container").children].forEach((el, i) => {
if (el.dataset.id == data) {
dragindex = +i;
}
})
log(data, clone.dataset.id, dragindex, e.target.dataset.id);
$("container").replaceChild(document.querySelector(`[data-id=${data}]`), e.target);
$("container").insertBefore(clone, $("container").childNodes[dragindex]);
}
}
[...document.querySelectorAll(".draggable")].map((el) => {
el.setAttribute("draggable", true);
});
[...document.querySelectorAll(".draggable")].map((el) => {
el.addEventListener("dragover", (e) => {
e.preventDefault();
})
el.addEventListener("dragstart", (e) => {
e.dataTransfer.setData("text/plain", e.target.dataset.id);
});
el.addEventListener("drop", (e) => {
drop(e);
});
})
#container {
width: 200px;
height: auto;
position: absolute;
left: 50%;
top: 50%;
background: dodgerblue;
color: #fff;
transform: translate(-50%, -50%);
border: 1px solid #000;
}
.draggable {
display: flex;
justify-content: start;
align-items: center;
border: 1px solid #fff;
margin: 2px;
padding: .5em;
text-align: center;
cursor: grab;
}
.draggable i {
margin-right: 25px;
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<div id="container">
<div class="draggable" data-id="drag0"><i class="material-icons">drag_indicator</i>Draggable 0</div>
<div class="draggable" data-id="drag1"><i class="material-icons">drag_indicator</i>Draggable 1</div>
<div class="draggable" data-id="drag2"><i class="material-icons">drag_indicator</i>Draggable 2</div>
<div class="draggable" data-id="drag3"><i class="material-icons">drag_indicator</i>Draggable 3</div>
</div>
So.... I finally cracked it. It was several things.
You have to re-add event listeners to a cloned node if they were added via "document.addEventListener()".
Had to use ".childNodes" not ".children" as the indexing does not work out the same.
Had to take care where/when I created the variable holding the reference node.
Also figured out that it acts weird in Safari on IOS if the drag/drop parent container is absolutely positioned so need to use flex positioning, as well as a few other minor details; any how, in case any one finds it helpful, here is the working code. Works in Android-Chrome/IOS-Safari.
const log = console.log.bind(console);
const $ = document.getElementById.bind(document);
function drop(e) {
e.preventDefault();
let dragindex = 0;
let referenceNode = "";
let clone = e.target.cloneNode(true);
addListeners(clone);
let data = e.dataTransfer.getData("text/plain");
if (clone.dataset.id !== data) {
[...$("container").childNodes].forEach((el, i) => {
if (el.dataset?.id == data) {
dragindex = i;
}
});
$("container").replaceChild(
document.querySelector(`[data-id=${data}]`),
e.target
);
referenceNode = $("container").childNodes[dragindex];
$("container").insertBefore(clone, referenceNode);
clone.classList.remove("dragActive");
}
}
function addListeners(el) {
el.addEventListener("dragover", (e) => {
e.preventDefault();
e.target.classList.add("dragActive");
});
el.addEventListener("dragstart", (e) => {
e.dataTransfer.setData("text/plain", e.target.dataset.id);
});
el.addEventListener("dragleave", (e) => {
e.target.classList.remove("dragActive");
});
el.addEventListener("dragend", (e) => {
e.target.classList.remove("dragActive");
});
el.addEventListener("drop", (e) => {
e.target.classList.remove("dragActive");
drop(e);
});
}
[...document.querySelectorAll(".draggable")].map((el) => {
el.setAttribute("draggable", true);
});
[...document.querySelectorAll(".draggable")].map((el) => {
addListeners(el);
});
html,
body {
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 100%;
}
#container {
width: 200px;
height: auto;
background: dodgerblue;
color: #fff;
border: 1px solid #000;
position: absolute;
/* top: 50%;
left: 50%;
transform: translate(-50%, -50%); */
}
.draggable {
border: 1px solid #fff;
margin: 2px;
padding: .5em;
text-align: center;
cursor: grab;
color: #000;
background: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACMAAAAzCAYAAAAdD7HCAAAACXBIWXMAAA7DAAAOwwHHb6hkAAADGElEQVRYhe1Zy2oUURA9MSoiWYQRxEdAMBoDxpVGZhFQF5qV+AgSPyK6CPgFbswvCD4WrkQQHwsFDUY3JuomISjic8CZhYk6PtCoUev07Rlm2p7uPj2TXR84zUxSValO31t16nYb6rHM2G/sMf40PjG+QGvQaTxo7DX+Nk4Z7xp/hBkfMr4y/g1w3LityURGjV9CYheMg0HjkRDDWpaNO1MmMhYTexHuH+Ghz/grxoF8aVwpJjKQIC45b8zR4VJCB/K4mMxVIfYJLtg9QvBBMZndgu1eJtMlOKyFhpxg28FkCoJDCRreCLZvmcwdweEmNFwTbK/wssW4gPgFNgNXFBXwMb1PEHui1mkY0du75CedBnnjx4jY08Z1QSfuqsmAIRO8DG2Rh2GT8SLqq3DReNq4umLUFuK42dgN1z+Y9TxaBxbN9X7sd8iQIcMSIWxrrzH2+p+foXVbm9V7l3GH/30WTnr+CTOmtGTvofKqLXrXjd1NJrLP/+PB6jvr/64OLNllNC7ZLOdpZecQolsNb/5YxbgDrvfENbOSb6uAPaecIPY32rbb5aTxaILATGTO+FBI5pTxQAK7FXCjER4guU69DQ1K7EmucEUabhCT6RRsPdn5VXD4AA1FwXZOlZ33oOGWYHuDF654rua4Z1pGiCKLQaqdStm5GGHMOjGEdOBBQpTs5E3mg05SlRSxFa6S1xY/3jwrfvVQIexIhFPgdv87J4LHaNA/UmCp+l6GDBnq0N7g5xvhGuh3uHrQKnBrs3T0+HHLjQw583L2ZXOrFCbOxufhZuVmwFmdM3tQ8XG2/+/kjD1nGo1LNotTPmUiPL2I6k9McLjWYQLxzYznLDkxEVb0mQSxF/ykPVmYVI2dEZM5LMQ+R4ezgsNTMZkLQmzvTE9ZnOqhkSJTu1TZ+RkaFNlZZDL3BYcpaFAkrXfIyB3CrZvkuQ6IyfDY7HWCuNzefRWnI4iWneQY0oFjcdxUORJ04nuBQoghq/AomgOl5XhIbL7fqr7eCcrOVcb9cEcXy+GkIUeIT2gNWNj6/djPjY9QlbTAPz6/t2nPvICTAAAAAElFTkSuQmCC');
background-repeat: no-repeat;
background-size: 15px;
background-position: 5px;
position: relative;
}
.dragActive {
background: rgba(255, 255, 255, .25);
color: #000;
border: 1px solid #000;
}
<div id="container">
<div class="draggable" data-id="drag0">Draggable 0</div>
<div class="draggable" data-id="drag1">Draggable 1</div>
<div class="draggable" data-id="drag2">Draggable 2</div>
<div class="draggable" data-id="drag3">Draggable 3</div>
</div>
im trying to make a search bar for my website to redirect pepole on other pages of my website by selecting values from autocomplete suggestions, but when i select a suggestion (example:"Home") and hit search nothing happends, instead when i write the value (example:"chat") it works just fine and it redirects me to another page, my question is: what im doing wrong and why my autocompleted values are not seen by the searchbar?
Here is the code example for values "chat, Home, youtube"
function ouvrirPage() {
var a = document.getElementById("search").value;
if (a === "chat") {
window.open("/index.html");
}
if (a === "Home") {
window.open("/customizedalert.html");
}
if (a === "youtube") {
window.open("https://www.youtube.com/");
}
}
And here is the entire thing:
https://codepen.io/galusk0149007/pen/LYeXvww
Try this in your IDE : Clicking the search icon will navigate to your urls.
// getting all required elements
const searchWrapper = document.querySelector(".search-input");
const inputBox = searchWrapper.querySelector("input");
const suggBox = searchWrapper.querySelector(".autocom-box");
const icon = searchWrapper.querySelector(".icon");
let linkTag = searchWrapper.querySelector("a");
let webLink;
let suggestions = ['chat','home', 'youtube']
// if user press any key and release
inputBox.onkeyup = (e)=>{
let userData = e.target.value; //user enetered data
let emptyArray = [];
if(userData){
icon.onclick = ()=>{
webLink = `https://www.google.com/search?q=${userData}`;
linkTag.setAttribute("href", webLink);
linkTag.click();
}
emptyArray = suggestions.filter((data)=>{
//filtering array value and user characters to lowercase and return only those words which are start with user enetered chars
return data.toLocaleLowerCase().startsWith(userData.toLocaleLowerCase());
});
emptyArray = emptyArray.map((data)=>{
// passing return data inside li tag
return data = `<li>${data}</li>`;
});
searchWrapper.classList.add("active"); //show autocomplete box
showSuggestions(emptyArray);
let allList = suggBox.querySelectorAll("li");
for (let i = 0; i < allList.length; i++) {
//adding onclick attribute in all li tag
allList[i].setAttribute("onclick", "select(this)");
}
}else{
searchWrapper.classList.remove("active"); //hide autocomplete box
}
}
function select(element){
let selectData = element.textContent;
inputBox.value = selectData;
icon.onclick = ()=>{
webLink = `https://www.google.com/search?q=${selectData}`;
linkTag.setAttribute("href", webLink);
linkTag.click();
}
searchWrapper.classList.remove("active");
}
function showSuggestions(list){
let listData;
if(!list.length){
userValue = inputBox.value;
listData = `<li>${userValue}</li>`;
}else{
listData = list.join('');
}
suggBox.innerHTML = listData;
}
function ouvrirPage() {
var a = document.getElementById("search").value;
if (a === "chat") {
window.open("/index.html");
}
if (a === "Home") {
window.open("/customizedalert.html");
}
if (a === "youtube") {
window.open("https://www.youtube.com/");
}
}
#import url('https://fonts.googleapis.com/css2?family=Poppins:wght#200;300;400;500;600;700&display=swap');
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Poppins', sans-serif;
}
body{
background: #544b8b;
padding: 0 20px;
}
::selection{
color: #fff;
background: #7c71bd;
}
.wrapper{
max-width: 450px;
margin: 150px auto;
}
.wrapper .search-input{
background: #fff;
width: 100%;
border-radius: 5px;
position: relative;
box-shadow: 0px 1px 5px 3px rgba(0,0,0,0.12);
}
.search-input input{
height: 55px;
width: 100%;
outline: none;
border: none;
border-radius: 5px;
padding: 0 60px 0 20px;
font-size: 18px;
box-shadow: 0px 1px 5px rgba(0,0,0,0.1);
}
.search-input.active input{
border-radius: 5px 5px 0 0;
}
.search-input .autocom-box{
padding: 0;
opacity: 0;
pointer-events: none;
max-height: 280px;
overflow-y: auto;
}
.search-input.active .autocom-box{
padding: 10px 8px;
opacity: 1;
pointer-events: auto;
}
.autocom-box li{
list-style: none;
padding: 8px 12px;
display: none;
width: 100%;
cursor: default;
border-radius: 3px;
}
.search-input.active .autocom-box li{
display: block;
}
.autocom-box li:hover{
background: #efefef;
}
.search-input .icon{
position: absolute;
right: 0px;
top: 0px;
height: 55px;
width: 55px;
text-align: center;
line-height: 55px;
font-size: 20px;
color: #644bff;
cursor: pointer;
}
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"/>
</head>
<body>
<div class="wrapper">
<div class="search-input">
<a href="" target="_blank" hidden></a>
<input type="text" placeholder="Type to search..">
<div class="autocom-box">
</div>
<div class="icon" onclick="ouvrirPage()"><i class="fas fa-search"></i></div>
</div>
</div>
</body>
I don’t want use or i don't know how to use 'the CSS:after prototype' by javascript .
Now, I change it is by add height not width,and when i remove the class prototype, reback is a short time,no transtion.
What can i do for it?
this is my codepen link
<div class="block">
<div id="top">my block/div>
<div>
<button id="btn">submit</button>
</div>
</div>
.block {
height: 200px;
width: 250px;
margin:150px auto;
text-align: center;
}
#top {
margin-bottom: 20px;
height: 30px;
display: inline-block;
border-bottom: 3px solid;
transition: 1s all cubic-bezier(.46, 1, .23, 1.52);
}
.addtop {
border-bottom: 3px solid blue;
color: blue;
}
let btn = document.getElementById('btn');
btn.addEventListener('click',() => {
let topBlock = document.getElementById('top');
if(topBlock.classList.length > 0) {
topBlock.classList = [];
} else {
topBlock.classList.add('addtop');
}
});
Try this:
document.getElementById('top');
if(topBlock.classList.length > 0) {
topBlock.classList.remove('addtop');
} else {
topBlock.classList.add('addtop');
}
});
Also add to .top class:
border-bottom: 0px solid blue;
I've been struggling with this problem 3 entire days. Any help would be appreciated!
I have a button 'ADD MY PHOTO' and when clicked, it comes a popup with the option to upload a picture or more. So, when I click 'Select Files' button or I drag & drop a picture or more, it will preview the pictures on the right side.
What I need help with is: when I upload a picture or 2, I want on the right side of every picture to display a textarea where the user can write something (like a caption). Also, after the pictures and captures are displayed I need the option to remove one or all of them. Here is a picture:
Here is the CodePen code: https://codepen.io/anon/pen/VEQMwm
Thanks in advance for help.
Also, here is the code:
// ---------- THIS IS FOR THE POPUP ---------- //
function CustomAlert() {
this.performCustomAlert = function (dialog) {
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
var dialogoverlay = document.getElementById('dialogoverlay');
var dialogbox = document.getElementById('dialogbox');
dialogoverlay.style.display = "block";
dialogoverlay.style.height = windowHeight + "px";
dialogbox.style.display = "block";
}
this.ok = function () {
document.getElementById('dialogbox').style.display = "none";
document.getElementById('dialogoverlay').style.display = "none";
}
}
var newAlert = new CustomAlert();
// ------------- TABS ----------------- //
function openTab(evt, tabName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(tabName).style.display = "block";
evt.currentTarget.className += " active";
}
document.getElementById("defaultOpen").click();
// ---------------- UPLOAD --------------------------//
// ************************ Drag and drop ***************** //
let dropArea = document.getElementById("drop-area")
// Prevent default drag behaviors
;['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
dropArea.addEventListener(eventName, preventDefaults, false)
document.body.addEventListener(eventName, preventDefaults, false)
})
// Highlight drop area when item is dragged over it
;['dragenter', 'dragover'].forEach(eventName => {
dropArea.addEventListener(eventName, highlight, false)
})
;['dragleave', 'drop'].forEach(eventName => {
dropArea.addEventListener(eventName, unhighlight, false)
})
// Handle dropped files
dropArea.addEventListener('drop', handleDrop, false)
function preventDefaults (e) {
e.preventDefault()
e.stopPropagation()
}
function highlight(e) {
dropArea.classList.add('highlight')
}
function unhighlight(e) {
dropArea.classList.remove('active')
}
function handleDrop(e) {
var dt = e.dataTransfer
var files = dt.files
handleFiles(files)
}
let uploadProgress = []
let progressBar = document.getElementById('progress-bar')
function initializeProgress(numFiles) {
progressBar.value = 0
uploadProgress = []
for(let i = numFiles; i > 0; i--) {
uploadProgress.push(0)
}
}
function updateProgress(fileNumber, percent) {
uploadProgress[fileNumber] = percent
let total = uploadProgress.reduce((tot, curr) => tot + curr, 0) / uploadProgress.length
console.debug('update', fileNumber, percent, total)
progressBar.value = total
}
function handleFiles(files) {
files = [...files]
initializeProgress(files.length)
files.forEach(uploadFile)
files.forEach(previewFile)
}
function previewFile(file) {
let reader = new FileReader()
reader.readAsDataURL(file)
reader.onloadend = function() {
let img = document.createElement('img')
img.src = reader.result
document.getElementById('gallery').appendChild(img)
}
}
function uploadFile(file, i) {
var xhr = new XMLHttpRequest()
var formData = new FormData()
xhr.open('POST', true)
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
// Update progress (can be used to show progress indicator)
xhr.upload.addEventListener("progress", function(e) {
updateProgress(i, (e.loaded * 100.0 / e.total) || 100)
})
xhr.addEventListener('readystatechange', function(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
updateProgress(i, 100) // <- Add this
}
else if (xhr.readyState == 4 && xhr.status != 200) {
// Error. Inform the user
}
})
formData.append('upload_preset', 'ujpu6gyk')
formData.append('file', file)
xhr.send(formData)
}
.add-photo{
width: 18%;
background-color: #00a100;
color: #fff;
padding: 11px 13px;
border: 3px solid #00a100;
-webkit-transition: 0.3s ease;
transition: 0.3s ease;
cursor: pointer;
text-align: center;
font-size: 13px;
font-weight: 550;
border-radius: 1px;
margin-left: 41%;
}
* {
box-sizing: border-box;
}
#dialogoverlay {
display: none;
opacity: 0.5;
/*so that user can see through it*/
position: fixed;
top: 0px;
left: 0px;
background: black;
z-index: 10;
height: 100%;
width: 100%;
}
#dialogbox {
display: none;
position: fixed;
background: #ffffff;
border-radius: 1px;
border: 0.5px solid #ccc;
z-index: 10;
left: 25%;
top: 20%;
width: 50%;
height: 400px;
-webkit-animation: fadeEffect 0.3s;
animation: fadeEffect 0.3s;
}
#close-popup {
float: right;
background-color: red;
color: #474747;
font-size: 15px;
}
.header{
position: absolute;
width: 100.2%;
background-color: white;
height: 11%;
top: 5.4%;
left: 50%;
transform: translate(-50%, -50%);
}
.content-centre{
width: 99%;
height: 77%;
margin-left: 3px;
margin-top: 46px;
}
#content-leftside{
width: 65%;
height: 100%;
float: left;
}
.tab {
overflow: hidden;
}
.tab button {
width: 33.3%;
height: 14%;
background-color: #acacac;
float: left;
color: white;
outline: none;
cursor: pointer;
padding: 6px;
transition: 0.3s;
border-right: 1px solid #fff;
}
.tab button:hover {
background-color: #474747;
}
.tab button.active {
background-color: #474747;
}
.tabcontent {
display: none;
padding: 6px 12px;
}
#content-rightside{
width: 35%;
height: 100%;
float: right;
background-color: #ffffff;
border-left: 1px solid #dddddd;
}
#right-topbar{
width: 100%;
height: 9%;
background-color: #474747;
color: #fff;
padding: 5px;
text-align: center;
transition: 0.3s;
}
.footer{
position: absolute;
width: 100.2%;
background-color: #474747;
height: 11%;
bottom: -5.6%;
left: 50%;
/* top: calc(50% - 50px); */
transform: translate(-50%, -50%);
}
/*------------------- UPLOAD AREA -----------------------*/
#drop-area {
border: 2px dashed #ccc;
border-radius: 8px;
width: 98%;
margin: 24px auto;
padding: 15px;
}
#progress-bar{
display: none;
}
#gallery {
margin-top: 5%;
}
#gallery img {
width: 55px;
height: 50px;
margin-bottom: 10px;
margin-left: 10px
}
.button {
display: inline-block;
padding: 10px;
background: #00a100;
color: #fff;
cursor: pointer;
border-radius: 5px;
}
#fileElem {
display: none;
}
#upload-button{
font-size: 40px;
color: #00a100;
<button class="add-photo" onclick="newAlert.performCustomAlert()">ADD MY PHOTO</button>
<div class="popup-upload">
<div id="dialogoverlay"></div>
<!--------------- SELECT MEDIA BOX ---------------->
<div id="dialogbox">
<!--------------- HEADER OF THE BOX ---------------->
<div class="header">
<!--------------- CLOSE POPUP ---------------->
<button id="close-popup" onclick="newAlert.ok()"><i class="fa fa-times" style="margin-top: 8px; margin-right: 7px;"></i></button>
<div class="select-media">
<i class="fa fa-camera" id="select-camera"></i>
<h2 id="select-media">SELECT YOUR MEDIA</h2>
</div>
</div>
<!--------------- CONTENT OF THE BOX ---------------->
<div class="content-centre">
<!--------------- LEFT CONTENT ---------------->
<div id="content-leftside">
<div class="tab">
<button class="tablinks" id="defaultOpen" onclick="openTab(event, 'Desktop')"><span class="fa fa-desktop"></span> Desktop</button>
<button class="tablinks" onclick="openTab(event, 'Facebook')"><span class="fa fa-facebook"></span> Facebook</button>
<button class="tablinks" onclick="openTab(event, 'Instagram')"><span class="fa fa-instagram"></span> Instagram</button>
</div>
<div id="Desktop" class="tabcontent">
<div id="drop-area">
<form class="my-form">
<span class="fa fa-cloud-upload" id="upload-button"></span>
<p id="drag-text">Drag & Drop Your <br> Photos or Videos <br> To Upload</p>
<input type="file" id="fileElem" multiple accept="image/*" onchange="handleFiles(this.files)">
<label class="button" for="fileElem">or Select Files</label>
</form>
</div>
</div>
<div id="Facebook" class="tabcontent">
<h3>Facebook</h3>
</div>
<div id="Instagram" class="tabcontent">
<h3>Instagram</h3>
</div>
</div>
<!--------------- RIGHT CONTENT ---------------->
<div id="content-rightside">
<!--------------- RIGHT TOPBAR ---------------->
<div id="right-topbar">
<h1>Selected Media</h1>
</div>
<progress id="progress-bar" max=100 value=0></progress>
<div id="gallery"/></div>
</div>
</div>
<div class="footer">
</div>
</div>
</div>
</div>
Look into below code, I made some changes on previewFile() function.
I hope, by looking below code you can get idea.
// ---------- THIS IS FOR THE POPUP ---------- //
function CustomAlert() {
this.performCustomAlert = function(dialog) {
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
var dialogoverlay = document.getElementById('dialogoverlay');
var dialogbox = document.getElementById('dialogbox');
dialogoverlay.style.display = "block";
dialogoverlay.style.height = windowHeight + "px";
dialogbox.style.display = "block";
}
this.ok = function() {
document.getElementById('dialogbox').style.display = "none";
document.getElementById('dialogoverlay').style.display = "none";
}
}
var newAlert = new CustomAlert();
// ------------- TABS ----------------- //
function openTab(evt, tabName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(tabName).style.display = "block";
evt.currentTarget.className += " active";
}
document.getElementById("defaultOpen").click();
// ---------------- UPLOAD --------------------------//
// ************************ Drag and drop ***************** //
let dropArea = document.getElementById("drop-area")
// Prevent default drag behaviors
;
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
dropArea.addEventListener(eventName, preventDefaults, false)
document.body.addEventListener(eventName, preventDefaults, false)
})
// Highlight drop area when item is dragged over it
;
['dragenter', 'dragover'].forEach(eventName => {
dropArea.addEventListener(eventName, highlight, false)
})
;
['dragleave', 'drop'].forEach(eventName => {
dropArea.addEventListener(eventName, unhighlight, false)
})
// Handle dropped files
dropArea.addEventListener('drop', handleDrop, false)
function preventDefaults(e) {
e.preventDefault()
e.stopPropagation()
}
function highlight(e) {
dropArea.classList.add('highlight')
}
function unhighlight(e) {
dropArea.classList.remove('active')
}
function handleDrop(e) {
var dt = e.dataTransfer
var files = dt.files
handleFiles(files)
}
let uploadProgress = []
let progressBar = document.getElementById('progress-bar')
function initializeProgress(numFiles) {
progressBar.value = 0
uploadProgress = []
for (let i = numFiles; i > 0; i--) {
uploadProgress.push(0)
}
}
function updateProgress(fileNumber, percent) {
uploadProgress[fileNumber] = percent
let total = uploadProgress.reduce((tot, curr) => tot + curr, 0) / uploadProgress.length
console.debug('update', fileNumber, percent, total)
progressBar.value = total
}
function handleFiles(files) {
files = [...files]
initializeProgress(files.length)
files.forEach(uploadFile)
files.forEach(previewFile)
}
function previewFile(file) {
let reader = new FileReader()
reader.readAsDataURL(file)
reader.onloadend = function() {
let img = document.createElement('img')
img.src = reader.result
var mainDiv = document.createElement("div")
mainDiv.className = "box"
mainDiv.appendChild(img)
var textbx = document.createElement("textarea")
textbx.placeholder ="Caption..."
mainDiv.appendChild(textbx)
var btn = document.createElement("button")
var tx = document.createTextNode("X");
btn.onclick = function() {
$(this).closest(".box").remove()
}
btn.appendChild(tx);
mainDiv.appendChild(btn)
document.getElementById('gallery').appendChild(mainDiv)
}
}
function uploadFile(file, i) {
var xhr = new XMLHttpRequest()
var formData = new FormData()
xhr.open('POST', true)
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
// Update progress (can be used to show progress indicator)
xhr.upload.addEventListener("progress", function(e) {
updateProgress(i, (e.loaded * 100.0 / e.total) || 100)
})
xhr.addEventListener('readystatechange', function(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
updateProgress(i, 100) // <- Add this
} else if (xhr.readyState == 4 && xhr.status != 200) {
// Error. Inform the user
}
})
formData.append('upload_preset', 'ujpu6gyk')
formData.append('file', file)
xhr.send(formData)
}
.add-photo {
width: 18%;
background-color: #00a100;
color: #fff;
padding: 11px 13px;
border: 3px solid #00a100;
-webkit-transition: 0.3s ease;
transition: 0.3s ease;
cursor: pointer;
text-align: center;
font-size: 13px;
font-weight: 550;
border-radius: 1px;
margin-left: 41%;
}
* {
box-sizing: border-box;
}
#dialogoverlay {
display: none;
opacity: 0.5;
/*so that user can see through it*/
position: fixed;
top: 0px;
left: 0px;
background: black;
z-index: 10;
height: 100%;
width: 100%;
}
#dialogbox {
display: none;
position: fixed;
background: #ffffff;
border-radius: 1px;
border: 0.5px solid #ccc;
z-index: 10;
left: 25%;
top: 20%;
width: 50%;
height: 400px;
-webkit-animation: fadeEffect 0.3s;
animation: fadeEffect 0.3s;
}
#close-popup {
float: right;
background-color: red;
color: #474747;
font-size: 15px;
}
.header {
position: absolute;
width: 100.2%;
background-color: white;
height: 11%;
top: 5.4%;
left: 50%;
transform: translate(-50%, -50%);
}
.content-centre {
width: 99%;
height: 77%;
margin-left: 3px;
margin-top: 46px;
}
#content-leftside {
width: 65%;
height: 100%;
float: left;
}
.tab {
overflow: hidden;
}
.tab button {
width: 33.3%;
height: 14%;
background-color: #acacac;
float: left;
color: white;
outline: none;
cursor: pointer;
padding: 6px;
transition: 0.3s;
border-right: 1px solid #fff;
}
.tab button:hover {
background-color: #474747;
}
.tab button.active {
background-color: #474747;
}
.tabcontent {
display: none;
padding: 6px 12px;
}
#content-rightside {
width: 35%;
height: 100%;
float: right;
background-color: #ffffff;
border-left: 1px solid #dddddd;
}
#right-topbar {
width: 100%;
height: 9%;
background-color: #474747;
color: #fff;
padding: 5px;
text-align: center;
transition: 0.3s;
}
.footer {
position: absolute;
width: 100.2%;
background-color: #474747;
height: 11%;
bottom: -5.6%;
left: 50%;
/* top: calc(50% - 50px); */
transform: translate(-50%, -50%);
}
/*------------------- UPLOAD AREA -----------------------*/
#drop-area {
border: 2px dashed #ccc;
border-radius: 8px;
width: 98%;
margin: 24px auto;
padding: 15px;
}
#progress-bar {
display: none;
}
#gallery {
margin-top: 5%;
}
#gallery img {
width: 55px;
height: 50px;
margin-bottom: 10px;
margin-left: 10px
}
.button {
display: inline-block;
padding: 10px;
background: #00a100;
color: #fff;
cursor: pointer;
border-radius: 5px;
}
#fileElem {
display: none;
}
#upload-button {
font-size: 40px;
color: #00a100;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="add-photo" onclick="newAlert.performCustomAlert()">ADD MY PHOTO</button>
<div class="popup-upload">
<div id="dialogoverlay"></div>
<!--------------- SELECT MEDIA BOX ---------------->
<div id="dialogbox">
<!--------------- HEADER OF THE BOX ---------------->
<div class="header">
<!--------------- CLOSE POPUP ---------------->
<button id="close-popup" onclick="newAlert.ok()"><i class="fa fa-times" style="margin-top: 8px; margin-right: 7px;"></i></button>
<div class="select-media">
<i class="fa fa-camera" id="select-camera"></i>
<h2 id="select-media">SELECT YOUR MEDIA</h2>
</div>
</div>
<!--------------- CONTENT OF THE BOX ---------------->
<div class="content-centre">
<!--------------- LEFT CONTENT ---------------->
<div id="content-leftside">
<div class="tab">
<button class="tablinks" id="defaultOpen" onclick="openTab(event, 'Desktop')"><span class="fa fa-desktop"></span> Desktop</button>
<button class="tablinks" onclick="openTab(event, 'Facebook')"><span class="fa fa-facebook"></span> Facebook</button>
<button class="tablinks" onclick="openTab(event, 'Instagram')"><span class="fa fa-instagram"></span> Instagram</button>
</div>
<div id="Desktop" class="tabcontent">
<div id="drop-area">
<form class="my-form">
<span class="fa fa-cloud-upload" id="upload-button"></span>
<p id="drag-text">Drag & Drop Your <br> Photos or Videos <br> To Upload</p>
<input type="file" id="fileElem" multiple accept="image/*" onchange="handleFiles(this.files)">
<label class="button" for="fileElem">or Select Files</label>
</form>
</div>
</div>
<div id="Facebook" class="tabcontent">
<h3>Facebook</h3>
</div>
<div id="Instagram" class="tabcontent">
<h3>Instagram</h3>
</div>
</div>
<!--------------- RIGHT CONTENT ---------------->
<div id="content-rightside">
<!--------------- RIGHT TOPBAR ---------------->
<div id="right-topbar">
<h1>Selected Media</h1>
</div>
<progress id="progress-bar" max=100 value=0></progress>
<div id="gallery" /></div>
</div>
</div>
<div class="footer">
</div>
</div>
</div>
</div>
just replace previewFile function with this.
function previewFile(file) {
let reader = new FileReader()
reader.readAsDataURL(file);
reader.onloadend = function() {
var gallleryDiv=document.getElementById('gallery');
var wrapperDiv = document.createElement("div");
let img = document.createElement('img');
img.src = reader.result;
wrapperDiv.className = "wrapperDiv";
wrapperDiv.appendChild(img)
var textbx = document.createElement("textarea");
wrapperDiv.appendChild(textbx);
var btn = document.createElement("button");
var tx = document.createTextNode("X");
btn.onclick = function() {$(this).closest(".wrapperDiv").remove()}
btn.appendChild(tx);
wrapperDiv.appendChild(btn);
gallleryDiv.appendChild(wrapperDiv);
}
}
I would please like an explanation to why the slideshow is not working. Below I have used an interval to perpetually change the slideshow, if userClick is false. The white and squared buttons (made of divs) are set to call upon two functions; slideRight() or slideLeft() and clicked(). When the buttons are clicked however, the clicked() function does not seem to change the variable, based on the data on top of the page.
<body>
<div class="page-wrapper">
<header>
<div class="headContent">
<h1 class="titleText">Slideshow</h1>
<h2 class="subTitleText">A slideshow made with JavaScript.</h2>
<p>userClick <span id="uc"></span></p>
</div>
<nav>
<ul>
<li>Home</li>
<li>About</li>
<li>Gallery</li>
</ul>
</nav>
</header>
<div class="body-wrapper">
<h1 class="titleText">Slideshow</h1>
<div id="slideshow">
<div id="leftSlide" onclick="leftSlide(); clicked()"></div>
<div id="rightSlide" onclick="rightSlide(); clicked()"></div>
</div>
<p>The image is not invoked by a tag, but invoked by the background property using Javascript.</p>
</div>
<footer>
<p id="footerText">© 2017 <br>Designed by JastineRay</p>
</footer>
</div>
<script language="javascript">
// Slide function
var slide = ["minivan", "lifeinthecity", "sunsetbodyoflove"];
var slideTo = 1;
window.onload = getSlide();
// Previous Image
function leftSlide() {
if (slideTo != 0) {
slideTo = slideTo - 1;
} else if (slideTo == 0) {
slideTo = slide.length - 1;
} else {
alert('SLIDE ERROR');
}
getSlide();
}
// Next Image
function rightSlide() {
if (slideTo != (slide.length - 1)) {
slideTo = slideTo + 1;
} else if (slideTo == (slide.length - 1)) {
slideTo = 0;
} else {
alert('SLIDE ERROR');
}
getSlide();
}
function getSlide() {
imageURL = 'url(images/' + slide[slideTo] + '.jpg)';
document.getElementById("slideshow").style.backgroundImage = imageURL;
}
// Interval Slideshow & Check if user clicked (timeout)
var userClick = false;
window.onload = slideInterval(5000);
// Start Slideshow
function slideInterval(interval) {
while (userClick = false) {
setInterval(function() {
rightSlide();
}, interval)
}
}
// Stop Slideshow and start timeout
function clicked() {
userClick = true;
setTimeout(function() {
userClick = false;
slideInterval();
}, 2000)
}
window.onload = function() {
setInterval(document.getElementById("uc").innerHTML = userClick), 100
}
</script>
</body>
CSS coding below.
* {
margin: 0;
padding: 0;
}
.page-wrapper {
width: 100%;
}
// Class Styling
.titleText {
font-family: monospace;
font-size: 40px;
}
.subTitleText {
font-family: monospace;
font-size: 20px;
font-weight: normal;
}
// Header Styling
header {
height: 500px;
}
.headContent {
margin: 30px 7%;
}
// Navigation Styling
nav {
overflow: hidden;
}
nav ul {
background: black;
background: linear-gradient(#595959, black);
list-style-type: none;
font-size: 0;
padding-left: 13.33%;
margin: 40px 0;
}
nav ul li {
padding: 15px 20px;
border-right: 1px solid #595959;
border-left: 1px solid #595959;
color: white;
display: inline-block;
font-size: 20px;
font-family: sans-serif;
}
// Body Styling
.body-wrapper {
}
.body-wrapper > .titleText {
text-align: center;
font-size: 50px;
}
#slideshow {
overflow: hidden;
margin: 20px auto;
border: 2px solid blue;
height: 350px;
max-width: 800px;
background-size: cover;
background-position: center;
position: relative;
}
#leftSlide {
position: absolute;
left: 40px;
top: 175px;
background-color: white;
height: 40px;
width: 40px;
}
#rightSlide {
position: absolute;
left: 100px;
top: 175px;
background-color: white;
height: 40px;
width: 40px;
}
// Footer Styling
Try changing the checking part to:
window.onload = function() {
setInterval(function () {
document.getElementById("uc").innerHTML = userClick;
}, 100);
}
The first argument of setInterval has to be a function (something that can be called), not a generic piece of code.