I need this below image uploader to: only run the hasAlpha() parameter if:
form.uploader is a descendant of .checkalpha.
Otherwise I need the uploader to work without checking alpha for every instance of the form.uploader that isn't a descendant of .checkalpha.
In the snippet example:
The first uploader isn't a descendant of .checkalpha and needs to allow image uploads without checking hasAlpha
The second uploader is a descendant of .checkalpha and needs to allow image uploads with checking hasAlpha
$(function() {
$(".file-drag").click(function(event) {
$(this).siblings(".file-upload").click();
});
function ekUpload(item) {
var form = $(this).find("form.uploader"),
fileSelect = $(this).find(".file-upload"),
fileDrag = $(this).find(".file-drag"),
submitButton = $(this).find(".submit-button");
function Init() {
$(document).on("change", "form", function(e) {
fileSelectHandler(e);
});
// Is XHR2 available?
var xhr = new XMLHttpRequest();
if (xhr.upload) {
if (isAdvancedUpload) {
$(document)
.on(
"drag dragstart dragend dragover dragenter dragleave",
"form",
function(e) {
// fileDragHover(e);
e.preventDefault();
e.stopPropagation();
}
)
.on("dragover dragenter", "form", function(e) {
e.preventDefault();
e.stopPropagation();
$(e.target).addClass("is-dragover");
})
.on("dragleave dragend drop", "form", function(e) {
e.preventDefault();
e.stopPropagation();
$(e.target).removeClass("is-dragover");
})
.on("drop dragover", "body", function(e) {
e.preventDefault();
e.stopPropagation();
})
.on("drop", "form", function(e) {
e.preventDefault();
e.stopPropagation();
fileSelectHandler(e);
});
}
}
}
function fileDragHover(e) {
e.stopPropagation();
e.preventDefault();
e.target.className =
e.type === "dragover" ? "hover" : "modal-body file-upload";
}
async function fileSelectHandler(e) {
var theForm = $(e.target).parent("form.uploader");
var files = e.target.files || e.originalEvent.dataTransfer.files;
// Process all File objects
for (let i = 0; i < files.length; i++) {
const f = files[i];
if (await hasAlpha(f)) {
console.log("Selected image is transparent");
parseFile(f, theForm);
uploadFile(f, theForm);
} else {
console.log("Selected image is not transparent");
$(theForm)
.closest(".checkalpha")
.find(".response, .error-image")
.removeClass("hidden");
$(theForm).find(".file-image, .start").addClass("hidden");
output(
'<strong class="warning">Image background is not transparent</strong>'
);
}
}
}
// Output
function output(msg) {
// Response
var m = $(item).find(".message");
m.html(msg);
}
function hasAlpha(file) {
return new Promise((resolve, reject) => {
let hasAlpha = false;
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
const img = new Image();
img.crossOrigin = "Anonymous";
img.onerror = reject;
img.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height)
.data;
for (let j = 0; j < imgData.length; j += 4) {
if (imgData[j + 3] < 255) {
hasAlpha = true;
break;
}
}
resolve(hasAlpha);
};
img.src = URL.createObjectURL(file);
});
}
function parseFile(file, thisForm) {
console.log(file.name);
output("<strong>" + encodeURI(file.name) + "</strong>");
// var fileType = file.type;
// console.log(fileType);
var imageName = file.name;
var isGood = /\.(?=svg|jpg|png|jpeg)/gi.test(imageName);
if (isGood) {
$(thisForm).find(".start, .notimage").addClass("hidden");
$(thisForm)
.closest(".checkalpha")
.find(".response")
.addClass("hidden");
$(thisForm).find(".error-image").addClass("hidden");
$(thisForm)
.find("label.has-advanced-upload")
.removeClass("has-advanced-upload");
$(thisForm)
.find(".file-image")
.removeClass("hidden")
.attr("src", URL.createObjectURL(file));
} else {
$(thisForm).find(".error-image").removeClass("hidden");
$(thisForm)
.closest(".checkalpha")
.find(".response, .file-image")
.addClass("hidden");
$(thisForm).find(".file-upload-form").trigger("reset");
$(thisForm)
.find('label[for="file-upload"]')
.addClass("has-advanced-upload");
}
}
function uploadFile(file, thisForm) {
var xhr = new XMLHttpRequest(),
fileSizeLimit = 1024; // in MB
if (xhr.upload) {
// Check if file is less than x MB
if (file.size <= fileSizeLimit * 1024 * 1024) {
// File received / failed
xhr.onreadystatechange = function(e) {
if (xhr.readyState == 4) {
// Everything is good!
console.log("everything is good");
}
};
// Start upload
xhr.open(
"POST",
$(thisForm).find(".file-upload-form").attr("action"),
true
);
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Size", file.size);
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.send(file);
} else {
output("Please upload a smaller file (< " + fileSizeLimit + " MB).");
}
}
}
// Check for the various File API support.
if (window.File && window.FileList && window.FileReader) {
Init();
} else {
document.getElementById("file-drag").style.display = "none";
}
}
var isAdvancedUpload = (function() {
var div = document.createElement("div");
return (
("draggable" in div || ("ondragstart" in div && "ondrop" in div)) &&
"FormData" in window &&
"FileReader" in window
);
})();
if (isAdvancedUpload) {
$(".file-drag").addClass("has-advanced-upload");
}
$(".uploader").each(function() {
ekUpload(this);
});
});
#import url(https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css);
#import url("https://fonts.googleapis.com/css?family=Roboto");
body {
padding: 2rem;
background: #f8f8f8;
}
img.error-image {
max-height: 160px;
}
.uploader {
display: block;
clear: both;
margin: 0 auto;
width: 100%;
max-width: 600px;
}
.uploader label {
float: left;
clear: both;
width: 100%;
padding: 2rem 1.5rem;
text-align: center;
background: #fff;
border-radius: 7px;
border: 3px solid #eee;
transition: all 0.2s ease;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
cursor: pointer;
}
.uploader label.has-advanced-upload {
background-color: white;
outline: 2px dashed lightgrey;
outline-offset: -10px;
}
.uploader label:hover {
border: 3px solid #454cad;
box-shadow: inset 0 0 0 6px #eee;
}
.uploader label.is-dragover,
.uploader label.is-dragover:hover {
background-color: #eef;
}
.uploader label:hover {
border: 3px solid #454cad;
box-shadow: inset 0 0 0 6px #eee;
}
.uploader label:hover .start i.fa {
-webkit-transform: scale(0.8);
transform: scale(0.8);
opacity: 0.3;
}
.uploader .start {
float: left;
clear: both;
width: 100%;
pointer-events: none;
}
.uploader .start.hidden {
display: none;
}
.uploader .start i.fa {
font-size: 50px;
margin-bottom: 1rem;
transition: all 0.2s ease-in-out;
}
.uploader .response {
float: left;
clear: both;
width: 100%;
}
.uploader .response.hidden {
display: none;
}
.uploader .response .messages {
margin-bottom: 0.5rem;
}
.uploader .file-image {
display: inline;
pointer-events: none;
margin: 0 auto 0.5rem auto;
width: auto;
height: auto;
max-width: 180px;
}
.uploader .file-image.hidden {
display: none;
}
.uploader .notimage {
display: block;
float: left;
clear: both;
width: 100%;
}
.uploader .notimage.hidden {
display: none;
}
.uploader progress,
.uploader .progress {
display: inline;
clear: both;
margin: 0 auto;
width: 100%;
max-width: 180px;
height: 8px;
border: 0;
border-radius: 4px;
background-color: #eee;
overflow: hidden;
}
.uploader .progress[value]::-webkit-progress-bar {
border-radius: 4px;
background-color: #eee;
}
.uploader .progress[value]::-webkit-progress-value {
background: linear-gradient(to right, #393f90 0%, #454cad 50%);
border-radius: 4px;
}
.uploader .progress[value]::-moz-progress-bar {
background: linear-gradient(to right, #393f90 0%, #454cad 50%);
border-radius: 4px;
}
.uploader input[type="file"] {
display: none;
}
.uploader div {
margin: 0 0 0.5rem 0;
color: #5f6982;
}
.uploader .btn {
display: inline-block;
margin: 0.5rem 0.5rem 1rem 0.5rem;
clear: both;
font-family: inherit;
font-weight: 700;
font-size: 14px;
text-decoration: none;
text-transform: initial;
border: none;
border-radius: 0.2rem;
outline: none;
padding: 0 1rem;
height: 36px;
line-height: 36px;
color: #fff;
transition: all 0.2s ease-in-out;
box-sizing: border-box;
background: #454cad;
border-color: #454cad;
cursor: pointer;
}
.uploader input[type="file"],
.hidden {
display: none;
}
input[type="file"].hidden {
display: block;
width: 0.1px;
height: 0.1px;
opacity: 0;
overflow: hidden;
position: absolute;
z-index: -1;
}
.warning {
color: red;
font-weight: bold;
}
canvas {
position: absolute;
top: -2000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Upload -->
<div class="">
<form class="file-upload-form uploader">
<input class="file-upload" type="file" name="fileUpload" accept="image/*" />
<label for="file-upload" class="file-drag">
<img class="file-image hidden" src="#" alt="Preview">
<img class="error-image hidden" src="https://cdn3.iconfinder.com/data/icons/online-states/150/Snooze-512.png">
<div class="start">
<i class="fa fa-download" aria-hidden="true"></i>
<div>Select a file or drag here</div>
<div class="notimage hidden">Please select an image</div>
</div>
<div class="response hidden">
<div class="message"></div>
</div>
</label>
</form>
<div class="filename"></div>
<canvas></canvas>
</div>
<div class="checkalpha">
<form class="file-upload-form uploader">
<input class="file-upload" type="file" name="fileUpload" accept="image/*" />
<label for="file-upload" class="file-drag">
<img class="file-image hidden" src="#" alt="Preview">
<img class="error-image hidden" src="https://cdn3.iconfinder.com/data/icons/online-states/150/Snooze-512.png">
<div class="start">
<i class="fa fa-download" aria-hidden="true"></i>
<div>Select a file or drag here</div>
<div class="notimage hidden">Please select an image</div>
</div>
<div class="response hidden">
<div class="message"></div>
</div>
</label>
</form>
<div class="filename"></div>
<canvas></canvas>
</div>
Check if doesn't have parent .checkalpha using .closest
if (theForm.closest('.checkalpha').length === 0 || await hasAlpha(f)) {
$(function() {
$(".file-drag").click(function(event) {
$(this).siblings(".file-upload").click();
});
function ekUpload(item) {
var form = $(this).find("form.uploader"),
fileSelect = $(this).find(".file-upload"),
fileDrag = $(this).find(".file-drag"),
submitButton = $(this).find(".submit-button");
function Init() {
$(document).on("change", "form", function(e) {
fileSelectHandler(e);
});
// Is XHR2 available?
var xhr = new XMLHttpRequest();
if (xhr.upload) {
if (isAdvancedUpload) {
$(document)
.on(
"drag dragstart dragend dragover dragenter dragleave",
"form",
function(e) {
// fileDragHover(e);
e.preventDefault();
e.stopPropagation();
}
)
.on("dragover dragenter", "form", function(e) {
e.preventDefault();
e.stopPropagation();
$(e.target).addClass("is-dragover");
})
.on("dragleave dragend drop", "form", function(e) {
e.preventDefault();
e.stopPropagation();
$(e.target).removeClass("is-dragover");
})
.on("drop dragover", "body", function(e) {
e.preventDefault();
e.stopPropagation();
})
.on("drop", "form", function(e) {
e.preventDefault();
e.stopPropagation();
fileSelectHandler(e);
});
}
}
}
function fileDragHover(e) {
e.stopPropagation();
e.preventDefault();
e.target.className =
e.type === "dragover" ? "hover" : "modal-body file-upload";
}
async function fileSelectHandler(e) {
var theForm = $(e.target).parent("form.uploader");
var files = e.target.files || e.originalEvent.dataTransfer.files;
// Process all File objects
for (let i = 0; i < files.length; i++) {
const f = files[i];
if (theForm.closest('.checkalpha').length === 0 || await hasAlpha(f)) {
console.log("Selected image is transparent");
parseFile(f, theForm);
uploadFile(f, theForm);
} else {
console.log("Selected image is not transparent");
$(theForm)
.closest(".checkalpha")
.find(".response, .error-image")
.removeClass("hidden");
$(theForm).find(".file-image, .start").addClass("hidden");
output(
'<strong class="warning">Image background is not transparent</strong>'
);
}
}
}
// Output
function output(msg) {
// Response
var m = $(item).find(".message");
m.html(msg);
}
function hasAlpha(file) {
console.log('hasAlpha');
return new Promise((resolve, reject) => {
let hasAlpha = false;
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
const img = new Image();
img.crossOrigin = "Anonymous";
img.onerror = reject;
img.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height)
.data;
for (let j = 0; j < imgData.length; j += 4) {
if (imgData[j + 3] < 255) {
hasAlpha = true;
break;
}
}
resolve(hasAlpha);
};
img.src = URL.createObjectURL(file);
});
}
function parseFile(file, thisForm) {
console.log(file.name);
output("<strong>" + encodeURI(file.name) + "</strong>");
// var fileType = file.type;
// console.log(fileType);
var imageName = file.name;
var isGood = /\.(?=svg|jpg|png|jpeg)/gi.test(imageName);
if (isGood) {
$(thisForm).find(".start, .notimage").addClass("hidden");
$(thisForm)
.closest(".checkalpha")
.find(".response")
.addClass("hidden");
$(thisForm).find(".error-image").addClass("hidden");
$(thisForm)
.find("label.has-advanced-upload")
.removeClass("has-advanced-upload");
$(thisForm)
.find(".file-image")
.removeClass("hidden")
.attr("src", URL.createObjectURL(file));
} else {
$(thisForm).find(".error-image").removeClass("hidden");
$(thisForm)
.closest(".checkalpha")
.find(".response, .file-image")
.addClass("hidden");
$(thisForm).find(".file-upload-form").trigger("reset");
$(thisForm)
.find('label[for="file-upload"]')
.addClass("has-advanced-upload");
}
}
function uploadFile(file, thisForm) {
var xhr = new XMLHttpRequest(),
fileSizeLimit = 1024; // in MB
if (xhr.upload) {
// Check if file is less than x MB
if (file.size <= fileSizeLimit * 1024 * 1024) {
// File received / failed
xhr.onreadystatechange = function(e) {
if (xhr.readyState == 4) {
// Everything is good!
console.log("everything is good");
}
};
// Start upload
xhr.open(
"POST",
$(thisForm).find(".file-upload-form").attr("action"),
true
);
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Size", file.size);
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.send(file);
} else {
output("Please upload a smaller file (< " + fileSizeLimit + " MB).");
}
}
}
// Check for the various File API support.
if (window.File && window.FileList && window.FileReader) {
Init();
} else {
document.getElementById("file-drag").style.display = "none";
}
}
var isAdvancedUpload = (function() {
var div = document.createElement("div");
return (
("draggable" in div || ("ondragstart" in div && "ondrop" in div)) &&
"FormData" in window &&
"FileReader" in window
);
})();
if (isAdvancedUpload) {
$(".file-drag").addClass("has-advanced-upload");
}
$(".uploader").each(function() {
ekUpload(this);
});
});
#import url(https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css);
#import url("https://fonts.googleapis.com/css?family=Roboto");
body {
padding: 2rem;
background: #f8f8f8;
}
img.error-image {
max-height: 160px;
}
.uploader {
display: block;
clear: both;
margin: 0 auto;
width: 100%;
max-width: 600px;
}
.uploader label {
float: left;
clear: both;
width: 100%;
padding: 2rem 1.5rem;
text-align: center;
background: #fff;
border-radius: 7px;
border: 3px solid #eee;
transition: all 0.2s ease;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
cursor: pointer;
}
.uploader label.has-advanced-upload {
background-color: white;
outline: 2px dashed lightgrey;
outline-offset: -10px;
}
.uploader label:hover {
border: 3px solid #454cad;
box-shadow: inset 0 0 0 6px #eee;
}
.uploader label.is-dragover,
.uploader label.is-dragover:hover {
background-color: #eef;
}
.uploader label:hover {
border: 3px solid #454cad;
box-shadow: inset 0 0 0 6px #eee;
}
.uploader label:hover .start i.fa {
-webkit-transform: scale(0.8);
transform: scale(0.8);
opacity: 0.3;
}
.uploader .start {
float: left;
clear: both;
width: 100%;
pointer-events: none;
}
.uploader .start.hidden {
display: none;
}
.uploader .start i.fa {
font-size: 50px;
margin-bottom: 1rem;
transition: all 0.2s ease-in-out;
}
.uploader .response {
float: left;
clear: both;
width: 100%;
}
.uploader .response.hidden {
display: none;
}
.uploader .response .messages {
margin-bottom: 0.5rem;
}
.uploader .file-image {
display: inline;
pointer-events: none;
margin: 0 auto 0.5rem auto;
width: auto;
height: auto;
max-width: 180px;
}
.uploader .file-image.hidden {
display: none;
}
.uploader .notimage {
display: block;
float: left;
clear: both;
width: 100%;
}
.uploader .notimage.hidden {
display: none;
}
.uploader progress,
.uploader .progress {
display: inline;
clear: both;
margin: 0 auto;
width: 100%;
max-width: 180px;
height: 8px;
border: 0;
border-radius: 4px;
background-color: #eee;
overflow: hidden;
}
.uploader .progress[value]::-webkit-progress-bar {
border-radius: 4px;
background-color: #eee;
}
.uploader .progress[value]::-webkit-progress-value {
background: linear-gradient(to right, #393f90 0%, #454cad 50%);
border-radius: 4px;
}
.uploader .progress[value]::-moz-progress-bar {
background: linear-gradient(to right, #393f90 0%, #454cad 50%);
border-radius: 4px;
}
.uploader input[type="file"] {
display: none;
}
.uploader div {
margin: 0 0 0.5rem 0;
color: #5f6982;
}
.uploader .btn {
display: inline-block;
margin: 0.5rem 0.5rem 1rem 0.5rem;
clear: both;
font-family: inherit;
font-weight: 700;
font-size: 14px;
text-decoration: none;
text-transform: initial;
border: none;
border-radius: 0.2rem;
outline: none;
padding: 0 1rem;
height: 36px;
line-height: 36px;
color: #fff;
transition: all 0.2s ease-in-out;
box-sizing: border-box;
background: #454cad;
border-color: #454cad;
cursor: pointer;
}
.uploader input[type="file"],
.hidden {
display: none;
}
input[type="file"].hidden {
display: block;
width: 0.1px;
height: 0.1px;
opacity: 0;
overflow: hidden;
position: absolute;
z-index: -1;
}
.warning {
color: red;
font-weight: bold;
}
canvas {
position: absolute;
top: -2000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Upload -->
<div class="">
<form class="file-upload-form uploader">
<input class="file-upload" type="file" name="fileUpload" accept="image/*" />
<label for="file-upload" class="file-drag">
<img class="file-image hidden" src="#" alt="Preview">
<img class="error-image hidden" src="https://cdn3.iconfinder.com/data/icons/online-states/150/Snooze-512.png">
<div class="start">
<i class="fa fa-download" aria-hidden="true"></i>
<div>Select a file or drag here</div>
<div class="notimage hidden">Please select an image</div>
</div>
<div class="response hidden">
<div class="message"></div>
</div>
</label>
</form>
<div class="filename"></div>
<canvas></canvas>
</div>
<div class="checkalpha">
<form class="file-upload-form uploader">
<input class="file-upload" type="file" name="fileUpload" accept="image/*" />
<label for="file-upload" class="file-drag">
<img class="file-image hidden" src="#" alt="Preview">
<img class="error-image hidden" src="https://cdn3.iconfinder.com/data/icons/online-states/150/Snooze-512.png">
<div class="start">
<i class="fa fa-download" aria-hidden="true"></i>
<div>Select a file or drag here</div>
<div class="notimage hidden">Please select an image</div>
</div>
<div class="response hidden">
<div class="message"></div>
</div>
</label>
</form>
<div class="filename"></div>
<canvas></canvas>
</div>
Related
I want to add a small player to my site to listen to music. I found a beautiful example that I liked and want to change and finish it a little.
Specifically, I want to add a button here to randomly play tracks.
To start, I add this button to the html:
<button type="submit" id="btn-random">
<i class="fas fa-random"></i>
</button>
Next, I add a check to the next track switching function, if the random button has an active class, then the tracks will play randomly:
else if (to == 'next') {
stop();
if (document.getElementById("btn-random").classList.contains("active")) {
let songs = document.getElementById("sourceUrl").length - 1;
let randomSong = Math.floor(Math.random() * songs) + 1;
} else {
currentSong = (++currentSong)%playlist.length;
}
playpause();
}
Next, it remains to make sure that when you click on the random button, the active class turns on and off. To do this, I make a onclick function for this button and implement it:
<button type="submit" id="btn-random" onclick="random()">
<i class="fas fa-random"></i>
</button>
//
var randomTrack = false;
function random() {
if (randomTrack) {
document.getElementById('btn-random').classList.add("active");
randomTrack = false;
}
else {
document.getElementById('btn-random').classList.remove("active");
randomTrack = true;
}
}
But in the end, when the random button has an active class and I try to switch the song, instead of a random track, the current track plays in a circle.
What could be the problem?
var song = new Audio;
var isStopped = true;
var currentSong = 0;
var playlist = [];
var playlistVisible = false;
var randomTrack = false;
function skip(to) {
if (to == 'prev') {
stop();
currentSong = (--currentSong)%playlist.length;
if (currentSong < 0) {
currentSong += playlist.length;
}
playpause();
}
else if (to == 'next') {
stop();
if (document.getElementById("btn-random").classList.contains("active")) {
let songs = document.getElementById("sourceUrl").length - 1;
let randomSong = Math.floor(Math.random() * songs) + 1;
} else {
currentSong = (++currentSong)%playlist.length;
}
playpause();
}
}
function playpause() {
if (!song.paused) {
song.pause();
document.getElementById("glow").classList.add("disable-animation");
}
else if (playlist.length == 0){
togglePlaylist();
}
else {
if (isStopped) {
song.src = playlist[currentSong];
}
song.play();
songFile = playlist[currentSong].split("/");
songName = document.getElementById("songName");
songName.innerHTML = songFile[songFile.length - 1].split('.').slice(0, -1).join('.');
document.getElementById("glow").classList.remove("disable-animation");
isStopped = false;
}
}
function random() {
if (randomTrack) {
document.getElementById('btn-random').classList.add("active");
randomTrack = false;
}
else {
document.getElementById('btn-random').classList.remove("active");
randomTrack = true;
}
}
function stop() {
song.pause();
document.getElementById("glow").classList.add("disable-animation");
song.currentTime = 0;
document.getElementById("seek").value = 0;
isStopped = true;
document.getElementById("songName").innerHTML = "playing track..";
}
function setPos(pos) {
song.currentTime = pos;
}
function mute() {
if (song.muted) {
song.muted = false;
document.getElementById('mute').className = "fa fa-volume-up";
}
else {
song.muted = true;
document.getElementById('mute').className = "fa fa-volume-off";
}
}
function setVolume(volume) {
song.volume = volume;
}
function togglePlaylist() {
if (playlistVisible) {
document.getElementById('playlist').className = "hide";
document.getElementById('player').className = "";
playlistVisible = false;
}
else {
document.getElementById('player').className = "hide";
document.getElementById('playlist').className = "";
playlistVisible = true;
}
}
function addList() {
sourceUrl = document.getElementById('sourceUrl').value;
sourceUrl.split(",").forEach((file) => {
fileUrl = file.trim();
if (fileUrl != "" && playlist.indexOf(fileUrl) == -1) {
parent = document.getElementById('list');
listItem = document.createElement('div');
listItem.setAttribute('class','list-item');
wrapper = document.createElement('div');
wrapper.setAttribute('class','wrap-text');
span = document.createElement('span');
songFile = fileUrl.split("/");
span.innerHTML = songFile[songFile.length - 1].split('.').slice(0, -1).join('.');
wrapper.appendChild(span);
listItem.appendChild(wrapper);
btn = document.createElement('button');
btn.setAttribute('onclick','removeList(this)');
btn.innerHTML = '×';
listItem.appendChild(btn);
parent.appendChild(listItem);
playlist.push(fileUrl);
}
});
document.getElementById('sourceUrl').value = '';
}
function removeList(item) {
index = playlist.indexOf(item.parentElement.firstChild.innerText);
if (index != -1){
playlist.splice(index,1);
item.parentElement.remove();
}
}
song.addEventListener('error', function(){
stop();
document.getElementById("songName").innerHTML = "error loading audio";
});
song.addEventListener('timeupdate', function() {
curtime = parseInt(song.currentTime,10);
document.getElementById('seek').max = song.duration;
document.getElementById('seek').value = curtime;
});
song.addEventListener("ended", function() {
song.pause();
song.currentTime = 0;
document.getElementById('seek').value = 0;
if ((currentSong + 1) >= playlist.length) {
currentSong = 0;
}
else {
currentSong++;
}
stop();
song.src = playlist[currentSong];
playpause();
});
var input = document.getElementById("sourceUrl");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
addList();
}
});
// This area of code is only for preview purposes only
document.getElementById('sourceUrl').value = ["https://www.bensound.com/bensound-music/bensound-summer.mp3",
"https://www.bensound.com/bensound-music/bensound-anewbeginning.mp3",
"https://www.bensound.com/bensound-music/bensound-littleidea.mp3",
"https://www.bensound.com/bensound-music/bensound-cute.mp3",
"https://www.bensound.com/bensound-music/bensound-memories.mp3"];
addList();
document.getElementById("glow").classList.remove("disable-animation");
// Code for preview ends here
* {
box-sizing: border-box;
}
html {
background: #000000;
}
html,
body,
.container {
height: 100%;
margin: 0;
font-family: Arial, Helvetica, sans-serif;
white-space: nowrap;
user-select: none;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
}
.container {
display: flex;
align-items: center;
justify-content: center;
}
.glow {
position: absolute;
width: 300px;
height: 300px;
background: linear-gradient(0deg, #000000, #262626);
border-radius: 50%;
}
.glow::before,
.glow::after {
content: "";
position: absolute;
top: -2px;
left: -2px;
background: linear-gradient(
45deg,
#ebc6df,
#ebc6c9,
#e1c6eb,
#c6c9eb,
#c6e8eb,
#e373fb,
#f787e6,
#cb87f7,
#87a9f7,
#87f7ee
);
background-size: 400%;
max-width: calc(300px + 4px);
max-height: calc(300px + 4px);
width: calc(300px + 4px);
height: calc(300px + 4px);
z-index: -1;
animation: animate 20s linear infinite;
border-radius: 50%;
}
.disable-animation::before,
.disable-animation::after {
animation-play-state: paused;
}
.glow::after {
filter: blur(28px);
}
#player,
#playlist {
width: 243px;
height: 212px;
text-align: center;
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
#songName {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
padding: 0 30px;
}
.playlist-btn {
width: 243px;
margin-top: 30px;
text-align: center;
position: relative;
left: 50%;
transform: translateX(-50%);
}
.hide {
display: none;
}
#list {
height: 118px;
max-height: 118px;
margin-top: 16px;
font-size: 12px;
overflow-x: hidden;
overflow-y: scroll;
color: #fff;
text-align: left;
padding-left: 8px;
border: 2px solid #262626;
border-radius: 5px;
}
.list-item {
line-height: 30px;
height: 30px;
margin-top: 4px;
}
.list-container button {
width: 30px;
padding: 0;
float: right;
margin-right: 4px;
}
.add-list {
padding: 4px 6px;
}
.wrap-text {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 190px;
display: inline-block;
}
#sourceUrl {
background: none;
padding: 8px;
border: 2px solid #1f1f1f;
border-radius: 47px;
outline: none;
color: white;
height: 30px;
width: 192px;
}
#sourceUrl:active,
#sourceUrl:focus {
border: 2px solid #0088ff;
}
.text {
color: #ffffff;
display: block;
}
button {
background: #000000;
color: #ffffff;
background: linear-gradient(0deg, #000000, #262626);
font-size: 14px;
border: none;
outline: none;
padding: 0px 15px;
width: 55px;
height: 30px;
line-height: 30px;
border-radius: 32px;
}
button:hover {
box-shadow: 0 0 8px 0px #ffffff61;
}
button:active {
box-shadow: inset 0 0 6px 0px #ffffff61;
}
#seek,
#volume {
-webkit-appearance: none;
border: 1px solid #000000;
height: 5px;
vertical-align: middle;
border-radius: 20px;
background-color: #232323;
outline: none;
}
#seek::-webkit-slider-thumb,
#volume::-webkit-slider-thumb {
-webkit-appearance: none;
width: 20px;
height: 20px;
border: 1px solid #000000;
border-radius: 10px;
background: #ffffff;
}
#seek {
display: block;
width: 230px;
}
.scrollbar::-webkit-scrollbar {
max-width: 5px;
max-height: 5px;
}
.scrollbar::-webkit-scrollbar-thumb {
border-radius: 10px;
background: #333;
}
.scrollbar::-webkit-scrollbar-thumb:hover {
box-shadow: inset 0 0 1px 1px #5c6670;
}
.scrollbar::-webkit-scrollbar-track:hover {
border: 1px solid #000000;
border-radius: 20px;
background-color: #232323;
}
#keyframes animate {
0% {
background-position: 0 0;
}
50% {
background-position: 400% 0;
}
100% {
background-position: 0 0;
}
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" rel="stylesheet" type="text/css">
<div class="container">
<div id="glow" class="glow disable-animation">
<div id="player">
<span class="text">iu player</span>
<br>
<span id="songName" class="text">playing track..</span>
<br>
<div class="playback_controls">
<button onclick="skip('prev')">
<i class="fa fa-fast-backward"></i>
</button>
<button onclick="playpause()">
<i class="fa fa-play"></i><i class="fa fa-pause"></i>
</button>
<button onclick="stop()">
<i class="fa fa-stop"></i>
</button>
<button onclick="skip('next')">
<i class="fa fa-fast-forward"></i>
</button>
</div>
<br>
<div id="seekbar">
<input type="range" oninput="setPos(this.value)" id="seek" value="0" max="">
</div>
<br>
<div class="volume_controls">
<button onclick="mute()">
<i id="mute" class="fa fa-volume-up"></i>
</button>
<input type="range" id="volume" oninput="setVolume(this.value)" min="0" max="1" step="0.01" value="1">
</div>
</div>
<div id="playlist" class="hide">
<span class="text">iu playlist</span>
<div class="list-container">
<div id="list" class="scrollbar"></div>
<div class="add-list">
<input id="sourceUrl" type="text" placeholder="enter audio url" />
<button onclick="addList()">+</button>
</div>
</div>
</div>
<div class="playlist-btn">
<button id="btn-random" onclick="random()">
<i class="fas fa-random"></i>
</button>
<button onclick="togglePlaylist()">
<i id="playlist-btn" class="fa fa-list"></i>
</button>
</div>
</div>
</div>
You are never reading your randomSong variable.
Just set currentSong to Math.floor(Math.random() * playlist.length) in that case:
if (
document.getElementById("btn-random").classList.contains("active")
) {
currentSong = Math.floor(Math.random() * playlist.length);
} else {
currentSong = ++currentSong % playlist.length;
}
playpause();
I am trying to upload PDF files using drag and drop. I am using jquery ajax.
ajaxData = new FormData(form);
I tried const form = $("form");, const form = document.getElementsByTagName("form")[0] but still getting the same error.
When I tried const form = $("form")[0], and const form = document.querySelector("form"); I got no error but got empty <FileStorage: '' ('application/octet-stream')> in my python script.
I have tried many solutions from SO but all of them mention above solutions.
Also, If I keep ajaxData = new FormData() I get no error but I get my file <FileStorage: 'certificate.pdf' ('application/pdf')> + another <FileStorage: '' ('application/octet-stream')>
Part of the code:
const script = document.createElement('script');
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
const container = document.querySelector(".container"),
dropArea = container.querySelector(".drop_area"),
form = container.querySelector("form"),
button = container.querySelector(".pdf_btn_container"),
btn = button.querySelector(".pdf_btn"),
label = container.querySelector("label"),
input = container.querySelector("input"),
dropInfo = dropArea.querySelector(".drop_info"),
body = document.querySelector("body"),
icon = dropArea.querySelector(".icon"),
loading = dropArea.querySelector(".loading"),
orSpan = dropArea.querySelector(".or_span");
let file;
let ajaxData;
container.onclick = (e) => {
e.stopPropagation();
input.click();
}
btn.onclick = (e) => {
e.stopPropagation();
}
dropArea.addEventListener("dragover", (e) => {
e.stopPropagation();
e.preventDefault();
dropArea.classList.add("drop_area--drag");
container.classList.add("container--drag");
orSpan.classList.add("or_span--drag");
dropInfo.classList.add("drop_info--drag");
btn.classList.add("pdf_btn--drag")
icon.classList.add("icon--drag");
button.classList.add("pdf_btn_container--drag");
});
["dragleave", "dragend"].forEach(action => {
dropArea.addEventListener(action, (e) => {
e.stopPropagation();
e.preventDefault();
dropArea.classList.remove("drop_area--drag");
container.classList.remove("container--drag");
orSpan.classList.remove("or_span--drag");
dropInfo.classList.remove("drop_info--drag");
btn.classList.remove("pdf_btn--drag")
icon.classList.remove("icon--drag");
button.classList.remove("pdf_btn_container--drag");
});
});
dropArea.addEventListener("drop", (e) => {
e.stopPropagation();
e.preventDefault();
dropArea.classList.add("drop_area--drag");
container.classList.add("container--drag");
orSpan.classList.add("or_span--drag");
dropInfo.classList.add("drop_info--drag");
btn.classList.add("pdf_btn--drag");
icon.classList.add("icon--drop");
loading.classList.remove("loading");
loading.classList.add("loading--drop");
button.classList.add("pdf_btn_container--drag");
file = e.dataTransfer.files;
console.log(file);
if (file.length > 1 || file.length === 0) {
alert("Multiple files selected!");
dropArea.classList.remove("drop_area--drag");
container.classList.remove("container--drag");
orSpan.classList.remove("or_span--drag");
dropInfo.classList.remove("drop_info--drag");
btn.classList.remove("pdf_btn--drag")
loading.classList.add("loading");
loading.classList.remove("loading--drop");
button.classList.remove("pdf_btn_container--drag");
icon.classList.remove("icon--drag");
icon.classList.remove("icon--drop");
} else {
file = file[0];
$(function() {
const $form = $("form");
ajaxData = new FormData($form[0]);
console.log(1, file);
ajaxData.append($('input').attr('name'), file);
console.log(2, file);
console.log(ajaxData);
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: ajaxData,
cache: false,
contentType: false,
processData: false,
success: function(data) {
form.onsubmit = (ev) => {
ev.stopPropagation();
//ev.preventDefault();
}
$form.trigger('submit');
console.log("Success");
},
});
});
}
});
document.getElementById("certificate").onchange = function() {
console.log("Le bhai main bhi chal gya!");
dropArea.classList.add("drop_area--drag");
container.classList.add("container--drag");
orSpan.classList.add("or_span--drag");
dropInfo.classList.add("drop_info--drag");
btn.classList.add("pdf_btn--drag");
icon.classList.add("icon--drop");
loading.classList.remove("loading");
loading.classList.add("loading--drop");
button.classList.add("pdf_btn_container--drag");
console.log(document.getElementById("certificate").value);
document.getElementsByTagName("form")[0].submit();
}
body {}
.container {
background-color: #227fbb;
/ / width: 1131 px;
/ / height: 396 px;
//background-color: #227fbb;
border: 1px solid white;
margin: 100px;
cursor: pointer;
}
.container:hover {
background-image: radial-gradient(rgba(44, 151, 222, 0.6), rgba(44, 151, 222, 0.2));
}
.container--drag {
background-image: radial-gradient(rgba(0, 189, 156, 0.4), rgba(0, 189, 156, 0.2));
}
.pdf_btn {
background-image: url("data:image/svg+xml,%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%20standalone%3D%22no%22%3F%3E%0D%0A%3Csvg%20height%3D%22700%22%20id%3D%22svg8%22%20version%3D%221.1%22%20viewBox%3D%220%200%20185.20832%20185.20832%22%20width%3D%22700%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Asvg%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%0A%20%20%0A%20%20%3Cdefs%20id%3D%22defs2%22%2F%3E%3Cpath%20id%3D%22path2227%22%20style%3D%22fill%3Anone%3Bstroke%3A%23000000%3Bstroke-width%3A5.33076%3Bstroke-linecap%3Around%3Bstroke-linejoin%3Around%3Bstroke-miterlimit%3A4%3Bstroke-dasharray%3Anone%3Bstroke-opacity%3A1%22%20d%3D%22m%20114.84828%2C39.943197%20v%2036.164064%20h%2026.24619%20z%20m%2026.24619%2C36.164064%201e-5%2C81.546409%20H%2041.493543%20V%2039.948209%20l%2073.354737%2C-0.005%22%2F%3E%3Cpath%20style%3D%22fill%3Anone%3Bstroke%3A%23000000%3Bstroke-width%3A5.30424%3Bstroke-linecap%3Around%3Bstroke-linejoin%3Amiter%3Bstroke-miterlimit%3A4%3Bstroke-dasharray%3Anone%3Bstroke-opacity%3A1%22%20d%3D%22M%2060.768038%2C91.352898%20H%20118.0696%22%20id%3D%22path4635%22%2F%3E%3Cpath%20style%3D%22fill%3Anone%3Bstroke%3A%23000000%3Bstroke-width%3A5.30424%3Bstroke-linecap%3Around%3Bstroke-linejoin%3Amiter%3Bstroke-miterlimit%3A4%3Bstroke-dasharray%3Anone%3Bstroke-opacity%3A1%22%20d%3D%22M%2061.351895%2C113.09545%20H%20118.65346%22%20id%3D%22path4635-6%22%2F%3E%3Cpath%20style%3D%22fill%3Anone%3Bstroke%3A%23000000%3Bstroke-width%3A5.30424%3Bstroke-linecap%3Around%3Bstroke-linejoin%3Amiter%3Bstroke-miterlimit%3A4%3Bstroke-dasharray%3Anone%3Bstroke-opacity%3A1%22%20d%3D%22M%2060.599782%2C134.15462%20H%20117.90134%22%20id%3D%22path4635-9%22%2F%3E%3Cg%20id%3D%22g7223-0%22%20style%3D%22opacity%3A1%3Bstroke%3A%23ffffff%22%20transform%3D%22matrix(1.6009321%2C0%2C0%2C1.6009321%2C-39.960567%2C-15.478026)%22%3E%3Cg%20id%3D%22g7072-4%22%20transform%3D%22matrix(0.39164163%2C0%2C0%2C0.39164163%2C101.22551%2C-8.9826794)%22%20style%3D%22stroke%3A%23ffffff%22%3E%3Cpath%20style%3D%22fill%3Anone%3Bstroke%3A%23ffffff%3Bstroke-width%3A26.4583%3Bstroke-linecap%3Around%3Bstroke-linejoin%3Around%3Bstroke-miterlimit%3A4%3Bstroke-dasharray%3Anone%3Bstroke-opacity%3A1%22%20d%3D%22M%20-130.19258%2C189.10654%20V%2032.002645%22%20id%3D%22path6711-7%22%2F%3E%3Cpath%20style%3D%22fill%3Anone%3Bstroke%3A%23ffffff%3Bstroke-width%3A26.4583%3Bstroke-linecap%3Around%3Bstroke-linejoin%3Around%3Bstroke-miterlimit%3A4%3Bstroke-dasharray%3Anone%3Bstroke-opacity%3A1%22%20d%3D%22M%20-208.74454%2C110.5546%20H%20-51.640634%22%20id%3D%22path6711-9-8%22%2F%3E%3C%2Fg%3E%3C%2Fg%3E%3Cg%20id%3D%22g7223%22%20transform%3D%22matrix(1.1716949%2C0%2C0%2C1.1716949%2C-16.33991%2C0.79419857)%22%3E%3Cg%20id%3D%22g7072%22%20transform%3D%22matrix(0.39164163%2C0%2C0%2C0.39164163%2C101.22551%2C-8.9826794)%22%3E%3Cpath%20style%3D%22fill%3Anone%3Bstroke%3A%23008000%3Bstroke-width%3A26.4583%3Bstroke-linecap%3Around%3Bstroke-linejoin%3Around%3Bstroke-miterlimit%3A4%3Bstroke-dasharray%3Anone%3Bstroke-opacity%3A1%22%20d%3D%22M%20-130.19258%2C189.10654%20V%2032.002645%22%20id%3D%22path6711%22%2F%3E%3Cpath%20style%3D%22fill%3Anone%3Bstroke%3A%23008000%3Bstroke-width%3A26.4583%3Bstroke-linecap%3Around%3Bstroke-linejoin%3Around%3Bstroke-miterlimit%3A4%3Bstroke-dasharray%3Anone%3Bstroke-opacity%3A1%22%20d%3D%22M%20-208.74454%2C110.5546%20H%20-51.640634%22%20id%3D%22path6711-9%22%2F%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E");
background-repeat: no-repeat no-repeat;
background-position: 25% 50%;
background-size: 10%;
font-size: 15px;
background-color: #eeeeee;
color: black;
padding: 1rem 3.0rem 1rem 5.0rem;
font-family: "Arial", sans-serif;
font-weight: bold;
border-radius: 0.4rem;
cursor: pointer;
margin-top: 0.5rem;
}
.pdf_btn:hover {
background-color: #dddddd;
}
.drop_area {
padding: 5%;
margin: 5px;
border: 3px dashed #2c97de;
}
.drop_area--drag {
border: 3px solid #2c97de;
overflow: hidden;
}
.icon {
display: flex;
justify-content: center;
color: #cccccc;
font-size: 3em;
}
.icon--drag {
display: flex;
font-size: 10em;
/ / position: relative;
padding: 5.2%;
animation: pulsate_icon 2.4s linear infinite alternate;
overflow: hidden;
}
.icon--drop {
display: none;
}
.or_span {
margin-top: 50px;
color: white;
display: flex;
font-size: 15px;
font-weight: bold;
font-family: "Arial", sans-serif;
justify-content: center;
text-align: center;
}
.pdf_btn--drag,
.or_span--drag,
.pdf_btn_container--drag {
display: none;
}
.drop_info {
margin-top: 10px;
color: white;
display: flex;
font-size: 15px;
/ / font-weight: 500;
text-align: center;
justify-content: center;
font-family: "Arial", sans-serif;
/ / padding: 5 %;
}
.drop_info--drag {
display: none;
}
.pdf_btn_container {
display: flex;
justify-content: center;
padding-top: 2rem;
}
.pdf_btn_container--drag {
display: none;
}
.drop-area--over {}
.loading {
display: none;
}
.loading--drop {
display: flex;
justify-content: center;
font-size: 10em;
padding: 5.2%;
color: #cccccc;
animation: rotate 2.4s linear infinite;
}
#keyframes pulsate_icon {
0% {
opacity: 1;
}
25% {
opacity: 0.6;
}
50% {
opacity: 0.4;
}
75% {
opacity: 0.6;
}
100% {
opacity: 1;
}
}
#keyframes rotate {
0% {
transform: rotate(0deg);
}
12.5% {
transform: rotate(45deg);
}
25% {
transform: rotate(90deg);
}
37.5% {
transform: rotate(135deg);
}
50% {
transform: rotate(180deg);
}
62.5% {
transform: rotate(225deg);
}
75% {
transform: rotate(270deg);
}
87.5% {
transform: rotate(315deg);
}
100% {
transform: rotate(360deg);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class="container">
<form name="pdf_form" action="upload_pic" method="POST" enctype="multipart/form-data">
<div class="drop_area">
<span class="loading"><i class="fas fa-yin-yang"></i></span>
<span class="icon"><i class="far fa-file-pdf"></i></span>
<div class="pdf_btn_container">
<input type="file" name="certificate" id="certificate" accept=".pdf" style="display:none">
<label class="pdf_btn" for="certificate">CHOOSE FILE</label>
</div>
<span class="or_span">OR</span>
<span class="drop_info"><p>Drop your <b>Certificate</b> here</p></span>
</div>
</form>
</div>
<script type="text/javascript" src="{{ url_for('static', filename = 'js/script_cert.js') }}"></script>
</body>
i work with li and i have issues.
I have input field, which add dynamically values to list, after adding some values, i have function to edite, this value, but this func work not correct, after editing li, it's delete all classes and span button.
HTML:
<form class="qa-form">
<input type="text" class="qa-input" placeholder="Enter text">
<button class="qa-button" id="btn-add">+</button>
<button class="qa-button hidden" id="btn-save">Save</button>
</form>
<div class="item-list"></div>
CSS:
.qa-form {
position: relative;
display: table;
width: 100%;
}
.qa-input {
text-align: left;
width: 100%;
box-sizing: border-box;
background: #fff;
max-width: 100%;
padding: 0.7rem 115px 0.7rem 0.7rem;
border: 1px solid #cbcbce;
border-radius: 6px;
color: #3a3d4b;
}
.qa-button {
position: absolute;
background: #31353D;
padding: 0.6rem 1rem;
border: none;
color: #fff;
border-radius: 5px;
right: 4px;
transform: translateY(2.5px);
}
.list-view ul {
list-style: none;
margin: 0;
padding: 0;
}
.list-view li {
margin-top: 5px;
list-style: none;
cursor: pointer;
background: #efefef;
height: auto;
line-height: 40px;
color: #666;
border-radius: 5px;
padding: 10px;
}
.list-view li:nth-child(2n) {
background: #f7f7f7;
}
.completed {
text-decoration: line-through;
color: gray;
}
.slide {
display: none;
}
.list-view li span {
color: white;
height: 40px;
display: inline-block;
margin-right: 4px;
width: 0;
transition: all .5s;
text-align: center;
opacity: 0;
}
.delete-item {
float: right;
background-color: #dc3545;
}
.edite-item {
float: right;
background-color: #fe6d00;
}
.correct-answ {
float: left;
background-color: #28a745;
}
.list-view li:hover span {
width: 40px;
opacity: 1;
}
.hidden {
display: none;
}
.correct-answer-active {
background-color: rgba(42, 176, 49, 0.45);
}
JQUERY:
$(".item-list").append("<ul id='item-data' class='list-view col-12'></ul>")
$("#btn-add").click(function () {
var inputVal = $(".qa-input").val()
if (inputVal != "") {
$("#item-data").append("<li><span class='delete-item'><i class='fa fa-trash-o'></i></span> <span class='edite-item'><i class='fa fa-edit'></i></span><span class='correct-answ'><i class='fa fa-check-circle-o'></i></span>" + inputVal + "</li>");
$(".qa-input").val(null)
} else {
alert("Add answer to input field")
}
});
$(document).on("click", ".delete-item", function () {
$(this).parent().fadeOut(function () {
$(this).remove();
});
})
$(document).on("click", ".edite-item", function () {
var listValues = $(this).parent();
$("#btn-add").hide()
$("#btn-save").show();
$(".qa-input").val(listValues.text())
editeData(listValues)
});
function editeData(val) {
$("#btn-save").click(function () {
var inputValue = $(".qa-input").val()
if (val === inputValue) {
alert("You are not make changes")
} else {
val.text(inputValue)
$("#btn-add").show()
$("#btn-save").hide();
$(".qa-input").val(null)
}
});
}
$(document).on("click", ".correct-answ", function () {
$(this).parent().css("background-color", "rgba(42, 176, 49, 0.45)")
$(this).parent().attr('active', true);
});
So, i try to find mistake, during all day, and i can't
The main problem is that .text() will also alter your html as you already experienced.
You could replace val.text(inputValue) with $(val).contents().last()[0].textContent = inputValue;
There is also a problem with this line if (val === inputValue) { your val represents the <li> object, and inputValue is ofc the text from the input field, so those will never be the same.
Working demo
$(".item-list").append("<ul id='item-data' class='list-view col-12'></ul>")
$("#btn-add").click(function() {
var inputVal = $(".qa-input").val()
if (inputVal != "") {
$("#item-data").append("<li><span class='delete-item'><i class='fa fa-trash-o'></i></span> <span class='edite-item'><i class='fa fa-edit'></i></span><span class='correct-answ'><i class='fa fa-check-circle-o'></i></span><span class='val'>" + inputVal + "</span></li>");
$(".qa-input").val(null)
} else {
alert("Add answer to input field")
}
});
$(document).on("click", ".delete-item", function() {
$(this).parent().fadeOut(function() {
$(this).remove();
});
})
var edited = null
$(document).on("click", ".edite-item", function() {
var listValues = $(this).closest("li");
$("#btn-add").hide()
$("#btn-save").show();
$(".qa-input").val(listValues.find(".val").text())
edited = listValues
});
$("#btn-save").click(function() {
var pretext = edited.find(".val").text();
var inputValue = $(".qa-input").val()
if (pretext === inputValue) {
alert("You are not make changes")
} else {
edited.find(".val").text(inputValue)
$("#btn-add").show()
$("#btn-save").hide();
$(".qa-input").val("")
}
});
$(document).on("click", ".correct-answ", function() {
$(this).parent().css("background-color", "rgba(42, 176, 49, 0.45)")
$(this).parent().attr('active', true);
});
.qa-form {
position: relative;
display: table;
width: 100%;
margin-top: 50px;
}
.qa-input {
text-align: left;
width: 100%;
box-sizing: border-box;
background: #fff;
max-width: 100%;
padding: 0.7rem 115px 0.7rem 0.7rem;
border: 1px solid #cbcbce;
border-radius: 6px;
color: #3a3d4b;
}
.qa-button {
position: absolute;
background: #31353D;
padding: 0.6rem 1rem;
border: none;
color: #fff;
border-radius: 5px;
right: 4px;
transform: translateY(2.5px);
}
.list-view ul {
list-style: none;
margin: 0;
padding: 0;
}
.list-view li {
margin-top: 5px;
list-style: none;
cursor: pointer;
background: #efefef;
height: auto;
line-height: 40px;
color: #666;
border-radius: 5px;
padding: 10px;
}
.list-view li:nth-child(2n) {
background: #f7f7f7;
}
.completed {
text-decoration: line-through;
color: gray;
}
.slide {
display: none;
}
.list-view li span:not(.val) {
color: white;
height: 40px;
display: inline-block;
margin-right: 4px;
width: 0;
transition: all .5s;
text-align: center;
opacity: 0;
}
.delete-item {
float: right;
background-color: #dc3545;
}
.edite-item {
float: right;
background-color: #fe6d00;
}
.correct-answ {
float: left;
background-color: #28a745;
}
.list-view li:hover span {
width: 40px;
opacity: 1;
}
.hidden {
display: none;
}
.correct-answer-active {
background-color: rgba(42, 176, 49, 0.45);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="qa-form">
<input type="text" class="qa-input" placeholder="Enter text">
<button type="button" class="qa-button" id="btn-add">+</button>
<button type="button" class="qa-button hidden" id="btn-save">Save</button>
</form>
<div class="item-list"></div>
My EventListener isn't targeting elements added after the page initially loads. I originally thought it might have been the order I have it in but I changed where the code is located and tried nesting it within the area the new div is created but it either breaks the color change as a whole or the original issue continues.
My final thought was maybe I need to add an EventListener to update the elems variable. I was unsuccessful in finding something to guide me.
If you click the original 4 squares they load, but after using the "Add a Square!" button the added divs dont behave the same.
//Turn div red if clicked
var elems = document.getElementsByClassName("square");
Array.from(elems).forEach(v => v.addEventListener('click', function() {
if (this.style.backgroundColor !== "red") {
this.style.backgroundColor = "red";
} else {
this.style.backgroundColor = "#1E1E1E";
}
}));
//Slider
var slider = document.getElementById("range");
var output = document.getElementById("value");
output.innerHTML = slider.value;
slider.oninput = function() {
var parent = document.getElementById("parent");
output.innerHTML = this.value;
parent.style.width = this.value + "%";
}
//Add Div
function addDiv(parent_div) {
var div = document.createElement("div");
var parent = document.getElementById(parent_div);
if (parent) {
parent.appendChild(div);
}
}
var button = document.getElementById("addsquare");
if (button) {
button.addEventListener("click", function() {
// change dynamically your new div
addDiv('parent', {
'class': 'square'
});
});
}
#parent {
margin: 0 auto;
min-width: 200px;
max-width: 94.2%;
width: 25%;
border: 1px dashed grey;
overflow: hidden;
}
#parent>div {
float: left;
margin: 1px;
width: calc(50px - 2px);
height: calc(50px - 2px);
background-color: #1E1E1E;
}
input,
button {
margin: 0;
}
.controls {
border: 1px solid black;
padding: 10px;
margin-bottom: 10px;
}
.controls>h2 {
margin: 0;
padding: 0;
text-align: center;
}
#addsquare {
padding: 8px;
margin-bottom: 5px;
}
.slidewrap {
width: 100%;
}
.slider {
-webkit-appearance: none;
width: 25%;
height: 25px;
background: #d3d3d3;
outline: none;
opacity: 0.7;
-webkit-transition: .2s;
transition: opacity .2s;
}
.slider:hover {
opacity: 1;
}
.slider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 25px;
height: 25px;
background: #4CAF50;
cursor: pointer;
}
.slider::-moz-range-thumb {
width: 25px;
height: 25px;
background: #4CAF50;
cursor: pointer;
}
<div class="controls">
<h2>Controls</h2>
<button id="addsquare">Add a Square!</button>
<div class="slidewrap">
<input type="range" min="25" max="100" value="25" class="slider" id="range">
<div>Game zone is set to: <span id="value"></span>%</div>
</div>
</div>
<div id="parent">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
You need to add the event listener to the dynamically created divs:
button.addEventListener("click", function() {
// change dynamically your new div
var newDiv = addDiv('parent', { 'class': 'square' });
newDiv.addEventListener('click', squareClickHandler)
});
squareClickHandler is just the old anonymous function you used to change the square color.
//Turn div red if clicked
var elems = document.getElementsByClassName("square");
Array.from(elems).forEach(v =>
v.addEventListener('click', squareClickHandler));
function squareClickHandler() {
if (this.style.backgroundColor !== "red") {
this.style.backgroundColor = "red";
} else {
this.style.backgroundColor = "#1E1E1E";
}
}
//Slider
var slider = document.getElementById("range");
var output = document.getElementById("value");
output.innerHTML = slider.value;
slider.oninput = function() {
var parent = document.getElementById("parent");
output.innerHTML = this.value;
parent.style.width = this.value + "%";
}
//Add Div
function addDiv(parent_div) {
var div = document.createElement("div");
var parent = document.getElementById(parent_div);
if (parent) {
parent.appendChild(div);
}
return div;
}
var button = document.getElementById("addsquare");
if (button) {
button.addEventListener("click", function() {
// change dynamically your new div
var newDiv = addDiv('parent', {
'class': 'square'
});
newDiv.addEventListener('click', squareClickHandler)
});
}
#parent {
margin: 0 auto;
min-width: 200px;
max-width: 94.2%;
width: 25%;
border: 1px dashed grey;
overflow: hidden;
}
#parent>div {
float: left;
margin: 1px;
width: calc(50px - 2px);
height: calc(50px - 2px);
background-color: #1E1E1E;
}
input,
button {
margin: 0;
}
.controls {
border: 1px solid black;
padding: 10px;
margin-bottom: 10px;
}
.controls>h2 {
margin: 0;
padding: 0;
text-align: center;
}
#addsquare {
padding: 8px;
margin-bottom: 5px;
}
.slidewrap {
width: 100%;
}
.slider {
-webkit-appearance: none;
width: 25%;
height: 25px;
background: #d3d3d3;
outline: none;
opacity: 0.7;
-webkit-transition: .2s;
transition: opacity .2s;
}
.slider:hover {
opacity: 1;
}
.slider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 25px;
height: 25px;
background: #4CAF50;
cursor: pointer;
}
.slider::-moz-range-thumb {
width: 25px;
height: 25px;
background: #4CAF50;
cursor: pointer;
}
<div class="controls">
<h2>Controls</h2>
<button id="addsquare">Add a Square!</button>
<div class="slidewrap">
<input type="range" min="25" max="100" value="25" class="slider" id="range">
<div>Game zone is set to: <span id="value"></span>%</div>
</div>
</div>
<div id="parent">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
I would solve this with event delegation instead of binding the event to each single element. This means you bind the listener to the parent or any other ancestor element and then do what you want to the event.target instead.
//Turn div red if clicked
var elems = document.getElementsByClassName("square");
var parent = document.getElementById("parent");
parent.addEventListener('click', (event) => {
let target = event.target;
if (target.style.backgroundColor !== "red") {
target.style.backgroundColor = "red";
} else {
target.style.backgroundColor = "#1E1E1E";
}
});
//Slider
var slider = document.getElementById("range");
var output = document.getElementById("value");
output.innerHTML = slider.value;
slider.oninput = function() {
var parent = document.getElementById("parent");
output.innerHTML = this.value;
parent.style.width = this.value + "%";
}
//Add Div
function addDiv(parent_div) {
var div = document.createElement("div");
var parent = document.getElementById(parent_div);
if (parent) {
parent.appendChild(div);
}
}
var button = document.getElementById("addsquare");
if (button) {
button.addEventListener("click", function() {
// change dynamically your new div
addDiv('parent', {
'class': 'square'
});
});
}
#parent {
margin: 0 auto;
min-width: 200px;
max-width: 94.2%;
width: 25%;
border: 1px dashed grey;
overflow: hidden;
}
#parent>div {
float: left;
margin: 1px;
width: calc(50px - 2px);
height: calc(50px - 2px);
background-color: #1E1E1E;
}
input,
button {
margin: 0;
}
.controls {
border: 1px solid black;
padding: 10px;
margin-bottom: 10px;
}
.controls>h2 {
margin: 0;
padding: 0;
text-align: center;
}
#addsquare {
padding: 8px;
margin-bottom: 5px;
}
.slidewrap {
width: 100%;
}
.slider {
-webkit-appearance: none;
width: 25%;
height: 25px;
background: #d3d3d3;
outline: none;
opacity: 0.7;
-webkit-transition: .2s;
transition: opacity .2s;
}
.slider:hover {
opacity: 1;
}
.slider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 25px;
height: 25px;
background: #4CAF50;
cursor: pointer;
}
.slider::-moz-range-thumb {
width: 25px;
height: 25px;
background: #4CAF50;
cursor: pointer;
}
<div class="controls">
<h2>Controls</h2>
<button id="addsquare">Add a Square!</button>
<div class="slidewrap">
<input type="range" min="25" max="100" value="25" class="slider" id="range">
<div>Game zone is set to: <span id="value"></span>%</div>
</div>
</div>
<div id="parent">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
Here is my problem, I create dynamic span in specif area thanks to "Link", "FirstName", "Lastname" buttons, and I would like to check which button was clicked among them in order to change color. For example, If I click the first time on "Link" button, the span is added in the area, and the "Link" button will become red. And if I click once again on it, the span will be removed, and the button will become grey.
var area = document.getElementById("template");
var message = document.getElementById("message");
var maxLength = 160;
var re = new RegExp("ô|â|ê|ç");
var myTags = new Object();
myTags['company'] = '#ENTREPRISE#';
myTags['city'] = '#VILLE#';
myTags['link'] = '#LIEN#';
myTags['firstname'] = '#PRENOM#';
myTags['lastname'] = '#NOM#';
myTags['title'] = '#TITRE#';
function editTag(zoneId, tag, button) {
var element = document.getElementById(button.id);
var zoneDiv = document.getElementById(zoneId + 'Draft');
var myButton = document.getElementById(zoneId + tag.ucfirst());
var myLabel = document.createElement('span');
var labels = zoneDiv.getElementsByTagName('span');
var spanSize = labels.length;
var delflag = 0;
var delIndex = 0;
if (spanSize != 0) {
for (myLabId = 0; myLabId < spanSize; myLabId++) {
var currentLabel = labels[myLabId];
if (currentLabel.innerHTML === myButton.innerHTML) {
delflag = 1;
delIndex = myLabId;
}
}
}
if (delflag == 1) {
zoneDiv.removeChild(labels[delIndex]);
button.classList.toggle("btn-success");
} else {
myLabel.setAttribute('class', 'label label-info');
myLabel.setAttribute('data-effect', 'pop');
myLabel.setAttribute('contentEditable', 'false');
myLabel.setAttribute('style', 'cursor:move;font-size:100%;');
myLabel.setAttribute('name', tag);
myLabel.setAttribute('draggable', 'true');
myLabel.innerHTML = myButton.innerHTML;
zoneDiv.appendChild(myLabel);
button.classList.toggle("btn-danger");
}
//Clean breaklines;
var bks = zoneDiv.getElementsByTagName('br');
var brSize = bks.length;
if (brSize != 0) {
zoneDiv.removeChild(bks[0]);
}
//Event keyboard on deleted elements
$("span").dblclick(function(handler) {
myLabel.remove(labels[delIndex]);
});
}
function saveMessage(zoneId) {
var zoneDiv = document.getElementById(zoneId + 'Draft');
var message = zoneDiv.childNodes;
var messSize = message.length;
var messageContent = '';
console.log(message);
for (var messId = 0; messId < messSize; messId++) {
var superRegex = /[a-zA-Z0-9áàâäãåçéèêëíìîïñóòôöõúùûüýÿæœÁÀÂÄÃÅÇÉÈÊËÍÌÎÏÑÓÒÔÖÕÚÙÛÜÝŸÆŒ._\s\.\,\--]/g;
if (zoneId === 'mail') {
superRegex = /[a-zA-Z0-9áàâäãåçéèêëíìîïñóòôöõúùûüýÿæœÁÀÂÄÃÅÇÉÈÊËÍÌÎÏÑÓÒÔÖÕÚÙÛÜÝŸÆŒ._\s\.\,\-\n-]/g;
}
if (message[messId].nodeName === '#text' && message[messId].nodeValue.match(superRegex))
// if(message[messId].nodeName === '#text' && message[messId].nodeValue.match(/[a-zA-Z0-9\,]/g) && message[messId].nodeValue.length < 100)
{
messageContent += message[messId].nodeValue;
} else if (message[messId].nodeName === 'SPAN') {
if (message[messId].getAttribute("name") == undefined) {
continue;
}
//messageContent += myTags[message[messId].getAttribute("name")];
var currentTag = '#' + message[messId].getAttribute("name").toUpperCase() + '#';
messageContent += currentTag;
} else if (message[messId].nodeName === 'IMG') {
messageContent += message[messId].outerHTML;
} else if (message[messId].nodeName === 'BR') {
messageContent += message[messId].outerHTML;
} else if (message[messId].nodeName === 'DIV') {
messageContent += '<br>' + message[messId].innerHTML;
}
}
var myRegexp = /\+/;
messageContent.replace(myRegexp, '');
if (zoneId === 'sms') {
myRegexp = /\n/;
messageContent.replace(myRegexp, '');
}
var idInput = document.getElementById('id');
var myData = {
'rm': 'saveMessage',
'type': zoneId,
'message': messageContent,
'pid': idInput.getAttribute('value')
};
if (zoneId === 'mail') {
var mySubject = document.getElementById('objectArea');
myData = {
'rm': 'saveMessage',
'type': zoneId,
'subject': mySubject.value,
'mail': messageContent,
'pid': idInput.getAttribute('value')
};
if (document.getElementById('mailType1').checked) {
myData['mType'] = 'text';
} else if (document.getElementById('mailType2').checked) {
myData['mType'] = 'html';
}
}
$.post("index.pl", myData).done(function(data) {
window.alert(data);
});
}
String.prototype.ucfirst = function() {
return this.charAt(0).toUpperCase() + this.substr(1);
}
function previewMessage(zoneId) {
var zoneDiv = document.getElementById(zoneId + 'Draft');
var message = zoneDiv.childNodes;
var messSize = message.length;
var messageContent = '';
var previewDiv = document.getElementById("preview");
var mailPreview = document.getElementById('mailPreview');
if (zoneId === 'sms') {
previewDiv.setAttribute('style', '');
previewDiv.innerHTML = '<p>Génération en cours ...</p>';
} else if (zoneId === 'mail') {
mailPreview.innerHTML = 'Génération en cours...';
}
for (var messId = 0; messId < messSize; messId++) {
var superRegex = /[a-zA-Z0-9áàâäãåçéèêëíìîïñóòôöõúùûüýÿæœÁÀÂÄÃÅÇÉÈÊËÍÌÎÏÑÓÒÔÖÕÚÙÛÜÝŸÆŒ._\s\.\,\--]/g;
if (message[messId].nodeName === '#text' && message[messId].nodeValue.match(superRegex) && message[messId].nodeValue.length < 100)
//if(message[messId].nodeName === '#text' && message[messId].nodeValue.match(/[a-zA-Z0-9\,]/g) && message[messId].nodeValue.length < 100)
{
messageContent += message[messId].nodeValue;
} else if (message[messId].nodeName === 'SPAN' && message[messId].nodeName.innerHTML !== '') {
if (message[messId].getAttribute("name") == undefined) {
continue;
}
//messageContent += myTags[message[messId].getAttribute("name")];
var currentTag = '#' + message[messId].getAttribute("name").toUpperCase() + '#';
messageContent += currentTag;
}
}
var myRegexp = /\+/;
messageContent.replace(myRegexp, '');
if (zoneId === 'sms') {
myRegexp = /\n/;
messageContent.replace(myRegexp, '');
}
var idInput = document.getElementById('id');
var myData = {
'rm': 'previewMessage',
'type': zoneId,
'message': btoa(messageContent),
'pid': idInput.getAttribute('value')
};
if (zoneId === 'mail') {
var mySubject = document.getElementById('objectArea');
myData = {
'rm': 'previewMessage',
'type': zoneId,
'subject': mySubject.value,
'mail': btoa(messageContent),
'pid': idInput.getAttribute('value')
};
}
$.post("index.pl", myData).done(function(data) {
if (zoneId === 'sms') {
previewDiv.innerHTML = '';
previewDiv.setAttribute("class", "preview");
previewDiv.setAttribute("style", "background-image:url(/assets/img/smartphone_sms.png);width:435px;height:293px;");
var myText = document.createElement('p');
myText.setAttribute('class', 'smstext');
myText.innerHTML = atob(data);
//myText.innerHTML = data;
previewDiv.appendChild(myText);
} else {
mailPreview.innerHTML = atob(data);
}
});
}
function testMessage(zoneId) {
var costTestP = document.getElementById('costTest');
costTestP.innerHTML = 'Calcul en cours ...';
var zoneDiv = document.getElementById(zoneId + 'Area');
var message = zoneDiv.childNodes;
var messSize = message.length;
var messageContent = '';
for (var messId = 0; messId < messSize; messId++) {
if (message[messId].nodeName === '#text' && message[messId].nodeValue.match(/[a-zA-Z0-9\,]/g) && message[messId].nodeValue.length < 100) {
messageContent += message[messId].nodeValue;
} else if (message[messId].nodeName === 'SPAN') {
messageContent += myTags[message[messId].getAttribute("name")];
}
}
var myRegexp = /\+/;
messageContent.replace(myRegexp, '');
myRegexp = /\n/;
messageContent.replace(myRegexp, '');
var idInput = document.getElementById('id');
var myData = {
'rm': 'testsms',
'message': messageContent,
'id': idInput.getAttribute('value')
};
$.post("index.pl", myData).done(function(data) {
var costTestP = document.getElementById('costTest');
costTestP.innerHTML = data;
});
}
$('#smsDraft').on('dragstart', function(e) {
console.log(e.target.nodeName);
if (e.target.nodeName !== 'SPAN') {
e.stopPropagation();
e.preventDefault();
return;
}
});
#smsArea {
-moz-appearance: textfield-multiline;
-webkit-appearance: textarea;
height: 150px;
overflow: auto;
padding: 5px;
resize: both;
width: 100%;
}
.smstext {
/* margin-top: 100px;*/
margin-left: 60px;
margin-right: 20px;
padding-top: 30px;
font-family: verdana, sans-serif;
}
#mailArea {
-moz-appearance: textfield-multiline;
-webkit-appearance: textarea;
height: 200px;
overflow: auto;
padding: 5px;
resize: both;
width: 500px;
font-size: 12px;
margin-top: 5px;
}
.mailInput {
-moz-appearance: textfield-multiline;
-webkit-appearance: textarea;
overflow: auto;
padding: 5px;
resize: both;
font-size: 12px;
margin-top: 5px;
width: 300px;
height: 85px;
margin-left: 100px;
margin-top: -20px;
}
.mailtext {
/* margin-top: 100px;*/
margin-left: 60px;
margin-right: 20px;
padding-top: 30px;
font-family: verdana, sans-serif;
}
#webtag {
margin-top: -392px;
margin-left: 555px;
width: 569px;
}
#result {
display: none;
}
#interaction {
margin-top: 30px;
visibility: hidden;
}
#cd-popup {
background-color: rgba(94, 110, 141, 0.9);
opacity: 1;
-webkit-transition: opacity 0.3s 0s, visibility 0s 0.3s;
-moz-transition: opacity 0.3s 0s, visibility 0s 0.3s;
transition: opacity 0.3s 0s, visibility 0s 0.3s;
position: relative;
width: 100%;
max-width: 800px;
height: 350px;
margin: 4em auto;
border-radius: .25em .25em .4em .4em;
text-align: center;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
-webkit-transform: translateY(-40px);
-moz-transform: translateY(-40px);
-ms-transform: translateY(-40px);
-o-transform: translateY(-40px);
transform: translateY(-40px);
/* Force Hardware Acceleration in WebKit */
-webkit-backface-visibility: hidden;
-webkit-transition-property: -webkit-transform;
-moz-transition-property: -moz-transform;
transition-property: transform;
-webkit-transition-duration: 0.3s;
-moz-transition-duration: 0.3s;
transition-duration: 0.3s;
z-index: 1;
}
#cd-popup.is-visible {
opacity: 1;
visibility: visible;
-webkit-transition: opacity 0.3s 0s, visibility 0s 0s;
-moz-transition: opacity 0.3s 0s, visibility 0s 0s;
transition: opacity 0.3s 0s, visibility 0s 0s;
}
#cd-popup p {
padding: 3em 1em;
margin-left: -250px;
height: 100px;
}
#cd-popup div {
float: left;
width: 30%;
list-style: none;
display: block;
height: 60px;
line-height: 60px;
text-transform: uppercase;
color: #FFF;
-webkit-transition: background-color 0.2s;
-moz-transition: background-color 0.2s;
transition: background-color 0.2s;
}
#object {
background: #fc7169;
border-radius: 0 0 0 .25em;
width: 175px;
margin-left: -400px;
cursor: pointer;
padding: 3px 6px;
display: inline-block;
}
#object:hover {
background-color: #fc8982;
}
#body {
background: #6495ED;
border-radius: 0 0 0 .25em;
width: 175px;
cursor: pointer;
padding: 3px 6px;
display: inline-block;
margin-left: -150px;
}
#body:hover {
background-color: #fc8982;
}
#titre {
background: #A52A2A;
border-radius: 0 0 0 .25em;
width: 175px;
margin-left: 10px;
cursor: pointer;
padding: 3px 6px;
display: inline-block;
}
#titre:hover {
background-color: #fc8982;
}
#note {
background: #006400;
border-radius: 0 0 0 .25em;
width: 175px;
margin-left: 10px;
cursor: pointer;
padding: 3px 6px;
display: inline-block;
}
#cd-popup #note:hover {
background-color: lightsteelblue;
}
#cd-popup .cd-popup-close {
position: absolute;
top: 8px;
right: 8px;
width: 30px;
height: 30px;
}
#cd-popup .cd-popup-close::before,
#cd-popup .cd-popup-close::after {
content: '';
position: absolute;
top: 12px;
width: 14px;
height: 3px;
background-color: #8f9cb5;
}
#cd-popup .cd-popup-close::before {
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
-ms-transform: rotate(45deg);
-o-transform: rotate(45deg);
transform: rotate(45deg);
left: 8px;
}
#cd-popup .cd-popup-close::after {
-webkit-transform: rotate(-45deg);
-moz-transform: rotate(-45deg);
-ms-transform: rotate(-45deg);
-o-transform: rotate(-45deg);
transform: rotate(-45deg);
right: 8px;
}
#media only screen and (min-width: 1170px) {
#cd-popup {
margin: 8em auto;
}
}
.webArea {
-moz-appearance: textfield-multiline;
-webkit-appearance: textarea;
height: 520px;
/*overflow: auto;*/
padding: 5px;
/*resize: both;*/
width: 630px;
font-size: 12px;
/*margin-top: 55px;*/
border: 2px dashed #D9D9D9;
border-radius: 5px;
text-align: center;
margin-top: 12%;
}
.webArea>div {
background-color: #FAEBD7;
border: 3px dashed #D9D9D9;
margin-bottom: 15px;
height: 120px;
width: 612px;
overflow: auto;
overflow-x: hidden;
/* margin-left: -1.5%;*/
}
.webArea>div>div {
transition: all .5s;
text-align: center;
float: left;
padding: 1em;
margin: 0 1em 1em 0;
box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.3);
border-radius: 5px;
border: 2px solid black;
/*background: #F7F7F7;*/
transition: all .5s ease;
width: 582px;
/*background-color: #F8F8FF;*/
height: 110px;
}
.dropTarget>div>div>span {
font-style: italic;
margin-right: 5%;
font-size: 16px;
}
.webArea>div>div>input {
margin-right: 25%;
width: 250px;
height: 40px;
background-color: white;
}
.webArea>div>div:active {
/*-webkit-animation: wiggle 0.3s 0s infinite ease-in;
animation: wiggle 0.3s 0s infinite ease-in;*/
opacity: .6;
border: 2px solid #000;
}
#mailArea {
-moz-appearance: textfield-multiline;
-webkit-appearance: textarea;
height: 200px;
overflow: auto;
padding: 5px;
resize: both;
width: 500px;
font-size: 12px;
margin-top: 5px;
}
#containerZone {
border: 1px solid;
border-radius: 25px;
*/ margin: 3%;
width: 70%;
height: 40px;
text-align: center;
font-weight: bold;
color: #000000;
margin: auto;
margin-top: 8%;
margin-left: -450px;
}
#containerZone2 {
border: 1px solid;
border-radius: 25px;
width: 70%;
height: 40px;
text-align: center;
font-weight: bold;
color: #000000;
margin: auto;
margin-top: 100%;
margin-left: -450px;
}
#webtags {
margin-top: -40px;
}
#webtags>div {
margin-left: 20px;
}
#modalTagBody {
height: 120px;
}
#btnTag {
margin-top: 20px;
margin-right: 15px;
}
<html>
<head>
<meta charset="utf-8">
<title>Drag & drop Tag</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.0/jquery-confirm.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.0/jquery-confirm.min.js"></script>
</head>
<body>
<div class="container mtb">
<div class="row">
<TMPL_IF NAME="PROFILE">
<form role="form" action="<TMPL_VAR NAME=MYURL>?rm=saveTemplate" method="POST" enctype="application/x-www-form-urlencoded">
<TMPL_LOOP NAME="DATA">
<input type="hidden" id='id' name="id" value="<TMPL_VAR NAME=ID>" />
<TMPL_IF NAME="TEMPLATE">
<div class="panel panel-primary" id="panels" data-effect="helix">
<div class="panel-heading">SMS Message</div>
<div class="panel-body">
<div class="col-lg-6">
<div class="form-group">
</div>
<input type="hidden" name="rm" value="saveTemplate" />
<div id="smsArea" class="form-control" contenteditable="true">
<p id="smsDraft">
<TMPL_VAR NAME=TEMPLATE>
</p>
</div><br />
Save
Preview
SMS Costs
<br>
</div>
<div class="col-lg-6" id='smsTags'>
<h4 for="template">Personnalization</h4>
<span class="btn btn-default" onClick="editTag('sms','link', this)" id="smsLink" title="link of your website" draggable="true">Link</span>
<span class="btn btn-default" onClick="editTag('sms','firstname')" id="smsFirstname" title="your firstname" draggable="true">Firstname</span>
<span class="btn btn-default" onClick="editTag('sms','lastname')" id="smsLastname" title="your lastname" draggable="true">Lastname</span>
</div>
<div class="col-lg-6" style="margin-top: 30px">
</div>
</div>
</TMPL_LOOP>
</div>
<! --/row -->
</div>
<! --/container -->
</div>
</body>
</html>
You can pass reference of clicked button using 'this' e.g
onClick = "editTag('sms','link', this)"
Once you get refrence of clicked element in onClick function, you can access the same element and toggle css class(class for red color)
function editTag(zoneId, tag, elementRef) {
// Check if function has received element refrence and toggle class
if(elementRef){
var element = document.getElementById(elementRef.id);
element.classList.toggle("btn-danger")
}
var zoneDiv = document.getElementById(zoneId + 'Draft');
var myButton = document.getElementById(zoneId + tag.ucfirst());
var myLabel = document.createElement('span');