Im making an user generated music playlist. The user drops files / adds files with the button.
However, whenever more files are dropped / added, the previously added files are replaced.
How to modify code to append the files with the previously added files?
PS:
I have used jquery to build the app. I have used jquery, cos i want to work with audio time duration(to find total playtime of the playlist, etc) and its a bit difficult to accomplish that with vanillaJS.
var dropZoneId = "drop-zone";
var buttonId = "clickHere";
var mouseOverClass = "mouse-over";
var dropZone = $("#" + dropZoneId);
var inputFile = dropZone.find("input");
var finalFiles = {};
var objectUrl;
// Function
$(function() {
var ooleft = dropZone.offset().left;
var ooright = dropZone.outerWidth() + ooleft;
var ootop = dropZone.offset().top;
var oobottom = dropZone.outerHeight() + ootop;
document.getElementById(dropZoneId).addEventListener("dragover", function(e) {
e.preventDefault();
e.stopPropagation();
dropZone.addClass(mouseOverClass);
var x = e.pageX;
var y = e.pageY;
if (!(x < ooleft || x > ooright || y < ootop || y > oobottom)) {
inputFile.offset({
top: y - 15,
left: x - 100
});
} else {
inputFile.offset({
top: -400,
left: -400
});
}
}, true);
if (buttonId != "") {
var clickZone = $("#" + buttonId);
var oleft = clickZone.offset().left;
var oright = clickZone.outerWidth() + oleft;
var otop = clickZone.offset().top;
var obottom = clickZone.outerHeight() + otop;
$("#" + buttonId).mousemove(function(e) {
var x = e.pageX;
var y = e.pageY;
if (!(x < oleft || x > oright || y < otop || y > obottom)) {
inputFile.offset({
top: y - 15,
left: x - 160
});
} else {
inputFile.offset({
top: -400,
left: -400
});
}
});
}
document.getElementById(dropZoneId).addEventListener("drop", function(e) {
$("#" + dropZoneId).removeClass(mouseOverClass);
}, true);
// FILE
inputFile.on('change', function(e) {
finalFiles = {};
$('#filename').html("");
var fileNum = this.files.length,
initial = 0,
counter = 0;
$.each(this.files, function(idx, elm) {
finalFiles[idx] = elm;
});
for (initial; initial < fileNum; initial++) {
counter = counter + 1;
// Object URL
var file = e.currentTarget.files[initial];
objectUrl = URL.createObjectURL(file);
$("#filename").prop("src", objectUrl);
//console.log('Object URL: ', objectUrl);
//console.log('FILE: ', file);
// Object URL End
//$('#filename').append('<div class="playlist draggable" id="file_' + initial + '"><span class="fa-stack fa-lg"><i class="fa fa-file fa-stack-1x "></i><strong class="fa-stack-1x" style="color:#FFF; font-size:12px; margin-top:2px;">' + counter + '</strong></span> ' + this.files[initial].name + ' <span class="fa fa-times-circle fa-lg closeBtn" onclick="removeLine(this)" title="remove"></span></div>');
//$('#filename').append('<div class="playlist draggable" id="file_' + initial + '"><span class="fa-stack fa-lg"><i class="fa fa-file fa-stack-1x "></i><strong class="fa-stack-1x" style="color:#FFF; font-size:12px; margin-top:2px;">' + counter + '</strong></span> ' + this.files[initial].name + ' <span class="fa fa-times-circle fa-lg closeBtn" onclick="removeLine(this)" title="remove"></span></div>');
$('#filename').append('<div class="playlist draggable" id="file_' + initial + '"><span class="fa-stack fa-lg"><i class="fa fa-file-audio-o"></i><strong class="fa-stack-1x" style="color:#FFF; font-size:12px; margin-top:2px;">' + '</strong></span> ' + '<audio controls controlsList="nodownload noplaybackrate" preload="auto" id="audioFiles" >' + '<source src="' + objectUrl + '" type="audio/mpeg" />' + '</audio>' + '<span class="fa fa-times-circle fa-lg closeBtn" onclick="removeLine(this)" title="remove"></span> ' + this.files[initial].name + '</div>');
//$('#filename').append('<div class="playlist draggable" id="file_' + initial + '">' + '<audio controls id="audioFiles" >' + '<source src="' + objectUrl + '/' + this.files[initial].name + '" type="audio/mpeg" />' + '</audio>' + '</div>');
console.log('NAME: ', this.files[initial].name);
//console.log('INITIAL: ', this.files[initial]);
// Audio Duration
var Duration;
$(audioFiles).on("canplay", function() {
console.log('THIS DURATION: ', this.duration);
Duration = this.duration;
});
// Audio Duration End
}
// Total File Count
var count = $('#filename').children().length;
console.log('Number of files: ', count);
$('#totalFiles').css("display", "initial");
$('#totalFiles').html('<font style="color:#06a7e5">Files Uploaded: ' + '<b>' + count + '</b>' + '</font>');
// End Total File Count
});
})
function removeLine(obj) {
inputFile.val('');
var jqObj = $(obj);
var container = jqObj.closest('div');
var index = container.attr("id").split('_')[1];
container.remove();
delete finalFiles[index];
//console.log(finalFiles);
URL.revokeObjectURL(objectUrl);
// Total Files
var count = $('#filename').children().length;
console.log('Number of files: ', count);
$('#totalFiles').html('<font style="color:#06a7e5">Files Uploaded: ' + '<b>' + count + '</b>' + '</font>');
if (count == 0) {
$('#totalFiles').css("display", "none");
} else {}
}
// Draggable Items
$(function() {
$('.draggable, .droppable').sortable({
connectWith: '.playlists'
});
});
#import url('https://fonts.googleapis.com/css?family=Source+Code+Pro');
* {
box-sizing: border-box;
}
body {
margin: 0;
padding: 0;
overflow-x: hidden;
overflow-y: visible;
font-family: 'Source Code Pro', monospace;
}
.dropper {
padding: 10px;
}
#drop-zone {
width: 100%;
min-height: 150px;
border: 3px dashed rgba(0, 0, 0, .3);
border-radius: 5px;
font-family: 'Source Code Pro', monospace;
text-align: center;
position: relative;
font-size: 20px;
color: #7E7E7E;
}
#drop-zone input {
position: absolute;
cursor: pointer;
left: 0px;
top: 0px;
opacity: 0;
}
/*Important*/
#drop-zone.mouse-over {
border: 3px dashed rgba(0, 0, 0, .3);
color: #7E7E7E;
}
/*If you dont want the button*/
#clickHere {
display: inline-block;
cursor: pointer;
color: white;
font-size: 1rem;
width: 200px;
border-radius: 0px;
background-color: #000000;
padding: 10px;
}
#clickHere:hover {
background-color: #376199;
}
.uploadedFiles {
padding: 0;
margin: 10px 50px;
}
#filename {
margin-top: 10px;
margin-bottom: 10px;
padding: 10px;
font-size: 14px;
line-height: 1.5em;
border: 1px solid;
min-height: 200px;
max-height: 400px;
overflow-y: scroll;
color: #240aff;
}
#filename span {
font-size: 1.5rem;
line-height: 1.2rem;
height: 1.5rem;
width: 1.5rem;
}
/* File Info */
#totalFiles {
border: 1px solid #06a7e5;
padding: 5px;
display: none;
}
.file-preview {
background: rgb(99, 8, 8);
border: 5px solid #fff;
box-shadow: 0 0 4px rgba(0, 0, 0, 0.5);
display: inline-block;
width: 60px;
height: 60px;
text-align: center;
font-size: 14px;
margin-top: 5px;
}
.closeBtn {
color: black;
display: inline-block;
vertical-align: -20%!important;
}
.closeBtn:hover {
color: red;
display: inline-block;
cursor: pointer;
}
.playlist {
border: 1px solid black;
padding: 10px;
margin: 5px;
background: #e9eaf9;
}
.playlist:hover {
cursor: move;
}
/* AUDIO CONTROLS */
#audioFiles {
vertical-align: middle;
margin: 0px 10px 0px 0px;
}
audio {
/*
filter: sepia(20%) saturate(70%) grayscale(1) contrast(99%) invert(12%);
*/
width: 25%;
height: 35px;
}
audio::-webkit-media-controls-enclosure {
border-radius: 5px;
background-color: #cfcfcf;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Upload & Draggable</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="./images/favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="./style.css">
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.13.0/jquery-ui.js" integrity="sha256-xH4q8N0pEzrZMaRmd7gQVcTZiFei+HfRTBPJ1OGXC0k=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
</head>
<body>
<div class="dropper">
<div id="drop-zone">
<p>Drop files here</p>
<div id="clickHere">or click here <i class="fa fa-upload"></i>
<input type="file" name="file" id="file" multiple accept="audio/*" />
</div>
</div>
</div>
<div class="uploadedFiles">
<p>Uploaded Files are Draggable. <span id="totalFiles"></span></p>
<div id="filename" class="playlists droppable"></div>
</div>
<!--
<audio id="audio2"></audio>
<p>
<label>File Size:</label>
<span id="filesize"></span>
<input type="hidden" id="size" name="size" value="" />
</p>
<p>
<label>Total Duration:</label>
<span id="duration"></span>
<input type="hidden" id="timelength" name="time" value="" />
</p>
-->
<script src="./script.js" async defer></script>
</body>
</html>
It worked well when i removed the following line of jquery code:
$('#filename').html("");
Related
can someone take a look at the code here is the problem screenshot
enter image description here
when clicking on sidebar user a popup appears after clicking on popup header it will go down and then if someone will click on the same user from sidebar a duplicate instance is created and click on the head will make the first one appear and 2nd one to go down.
I want to stop that duplication when someone clicks on sidebar user again then the already generated popup will toggle.
https://jsfiddle.net/hamzasgd/Lqyajokp/4/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Facebook like chat popup layout</title>
</head>
<body>
<div id="chat-sidebar">
<div id="sidebar-user-box" class="100">
<img src="user.png" />
<span id="slider-username">User 1</span>
</div>
<div id="sidebar-user-box" class="200">
<img src="user.png" />
<span id="slider-username">User 2</span>
</div>
</div>
</body>
</html>
$(document).ready(function(){
var arr = []; // List of users
$(document).on('click', '.msg_head', function() {
var chatbox = $(this).parents().attr("rel") ;
$('[rel="'+chatbox+'"] .msg_wrap').slideToggle('slow');
return false;
});
$(document).on('click', '.close', function() {
var chatbox = $(this).parents().parents().attr("rel") ;
$('[rel="'+chatbox+'"]').hide();
arr.splice($.inArray(chatbox, arr), 1);
displayChatBox();
return false;
});
$(document).on('click', '#sidebar-user-box', function() {
var userID = $(this).attr("class");
var username = $(this).children().text() ;
if ($.inArray(userID, arr) != -1)
{
arr.splice($.inArray(userID, arr), 1);
}
arr.unshift(userID);
chatPopup = '<div class="msg_box" style="right:270px" rel="'+ userID+'">'+
'<div class="msg_head">'+username +
'<div class="close">x</div> </div>'+
'<div class="msg_wrap"> <div class="msg_body"> <div class="msg_push"></div> </div>'+
'<div class="msg_footer"><textarea class="msg_input" rows="4"></textarea></div> </div> </div>' ;
$("body").append( chatPopup );
displayChatBox();
});
$(document).on('keypress', 'textarea' , function(e) {
if (e.keyCode == 13 ) {
var msg = $(this).val();
$(this).val('');
if(msg.trim().length != 0){
var chatbox = $(this).parents().parents().parents().attr("rel") ;
$('<div class="msg-right">'+msg+'</div>').insertBefore('[rel="'+chatbox+'"] .msg_push');
$('.msg_body').scrollTop($('.msg_body')[0].scrollHeight);
}
}
});
function displayChatBox(){
i = 270 ; // start position
j = 260; //next position
$.each( arr, function( index, value ) {
if(index < 4){
$('[rel="'+value+'"]').css("right",i);
$('[rel="'+value+'"]').show();
i = i+j;
}
else{
$('[rel="'+value+'"]').hide();
}
});
}
});
I've added a check that will look if you already have a chatbox with that userID:
var exist = $('.msg_box[rel="' + userID + '"]').length;
if (exist == 0) {
arr.unshift(userID);
chatPopup = '<div class="msg_box" style="right:270px" rel="' + userID + '">' +
'<div class="msg_head">' + username +
'<div class="close">x</div> </div>' +
'<div class="msg_wrap"> <div class="msg_body"> <div class="msg_push"></div> </div>' +
'<div class="msg_footer"><textarea class="msg_input" rows="4"></textarea></div> </div> </div>';
$("body").append(chatPopup);
displayChatBox();
}
Please note that you have some invalid html. You are not allowed, to have the id on multiple element.
Demo
$(document).ready(function() {
var arr = []; // List of users
$(document).on('click', '.msg_head', function() {
var chatbox = $(this).parents().attr("rel");
$('[rel="' + chatbox + '"] .msg_wrap').slideToggle('slow');
return false;
});
$(document).on('click', '.close', function() {
var chatbox = $(this).parents().parents().attr("rel");
$('[rel="' + chatbox + '"]').hide();
arr.splice($.inArray(chatbox, arr), 1);
displayChatBox();
return false;
});
$(document).on('click', '#sidebar-user-box', function() {
var userID = $(this).attr("class");
var username = $(this).children().text();
if ($.inArray(userID, arr) != -1) {
arr.splice($.inArray(userID, arr), 1);
}
var exist = $('.msg_box[rel="' + userID + '"]').length;
if (exist == 0) {
arr.unshift(userID);
chatPopup = '<div class="msg_box" style="right:270px" rel="' + userID + '">' +
'<div class="msg_head">' + username +
'<div class="close">x</div> </div>' +
'<div class="msg_wrap"> <div class="msg_body"> <div class="msg_push"></div> </div>' +
'<div class="msg_footer"><textarea class="msg_input" rows="4"></textarea></div> </div> </div>';
$("body").append(chatPopup);
displayChatBox();
} else {
$('.msg_box[rel="' + userID + '"] .msg_wrap').slideToggle('slow');
}
});
$(document).on('keypress', 'textarea', function(e) {
if (e.keyCode == 13) {
var msg = $(this).val();
$(this).val('');
if (msg.trim().length != 0) {
var chatbox = $(this).parents().parents().parents().attr("rel");
$('<div class="msg-right">' + msg + '</div>').insertBefore('[rel="' + chatbox + '"] .msg_push');
$('.msg_body').scrollTop($('.msg_body')[0].scrollHeight);
}
}
});
function displayChatBox() {
i = 270; // start position
j = 260; //next position
$.each(arr, function(index, value) {
if (index < 4) {
$('[rel="' + value + '"]').css("right", i);
$('[rel="' + value + '"]').show();
i = i + j;
} else {
$('[rel="' + value + '"]').hide();
}
});
}
});
/**** Chat Popup Layout******/
body {
background: #e5e5e5;
font-family: sans-serif;
}
.msg_box {
position: fixed;
bottom: -5px;
width: 250px;
background: white;
border-radius: 5px 5px 0px 0px;
}
.msg_head {
background: black;
color: white;
padding: 8px;
font-weight: bold;
cursor: pointer;
border-radius: 5px 5px 0px 0px;
}
.msg_body {
background: white;
height: 200px;
font-size: 12px;
padding: 15px;
overflow: auto;
overflow-x: hidden;
}
.msg_input {
width: 100%;
height: 55px;
border: 1px solid white;
border-top: 1px solid #DDDDDD;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.close {
float: right;
cursor: pointer;
}
.minimize {
float: right;
cursor: pointer;
padding-right: 5px;
}
.msg-left {
position: relative;
background: #e2e2e2;
padding: 5px;
min-height: 10px;
margin-bottom: 5px;
margin-right: 10px;
border-radius: 5px;
word-break: break-all;
}
.msg-right {
background: #d4e7fa;
padding: 5px;
min-height: 15px;
margin-bottom: 5px;
position: relative;
margin-left: 10px;
border-radius: 5px;
word-break: break-all;
}
/**** Slider Layout Popup *********/
#chat-sidebar {
width: 250px;
position: fixed;
height: 100%;
right: 0px;
top: 0px;
padding-top: 10px;
padding-bottom: 10px;
border: 1px solid #b2b2b2;
}
#sidebar-user-box {
padding: 4px;
margin-bottom: 4px;
font-size: 15px;
font-family: Calibri;
font-weight: bold;
cursor: pointer;
}
#sidebar-user-box:hover {
background-color: #999999;
}
#sidebar-user-box:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
img {
width: 35px;
height: 35px;
border-radius: 50%;
float: left;
}
#slider-username {
float: left;
line-height: 30px;
margin-left: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="chat-sidebar">
<div id="sidebar-user-box" class="100">
<img src="user.png" />
<span id="slider-username">User 1</span>
</div>
<div id="sidebar-user-box" class="200">
<img src="user.png" />
<span id="slider-username">User 2</span>
</div>
</div>
I have a File upload control in my mvc project which should preview the selected images and delete if needed before uploading. This Code Works Fine in Normal (.html)view, but it does not render the images when it is added to my mvc project that is in my (.cshtml) view:
#{
}
<h2>UploadImage</h2>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<title>Sample</title>
<style>
#drop-zone {
margin-left: 32%;
margin-top: 15%;
width: 500px;
min-height: 150px;
border: 3px dashed rgba(0, 0, 0, .3);
border-radius: 5px;
font-family: Arial;
text-align: center;
position: relative;
font-size: 20px;
color: #7E7E7E;
}
#drop-zone input {
position: absolute;
cursor: pointer;
left: 0px;
top: 0px;
opacity: 0;
}
/*Important*/
#drop-zone.mouse-over {
border: 3px dashed rgba(0, 0, 0, .3);
color: #7E7E7E;
}
/*If you dont want the button*/
#clickHere {
display: inline-block;
cursor: pointer;
color: black;
font-size: 17px;
width: 150px;
border-radius: 4px;
background-color: #F5D56D;
padding: 10px;
}
#clickHere:hover {
background-color: #FCE085;
}
#filename {
margin-top: 10px;
margin-bottom: 10px;
font-size: 14px;
line-height: 1.5em;
}
.file-preview {
background: #ccc;
border: 5px solid #fff;
box-shadow: 0 0 4px rgba(0, 0, 0, 0.5);
display: inline-block;
width: 60px;
height: 60px;
text-align: center;
font-size: 14px;
margin-top: 5px;
}
.closeBtn:hover {
color: red;
display: inline-block;
}
</style>
</head>
<body>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
#using (Html.BeginForm("UploadImage", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div id="drop-zone">
<p>Drop files here...</p>
<div id="clickHere">
or click here.. <i class="fa fa-upload"></i>
<input type="file" name="file" id="file" multiple />
</div>
<div id="filename">
</div>
<button type="submit" class="btn btn-success"> Upload</button>
</div>
}
</body>
<script>
var dropZoneId = "drop-zone";
var buttonId = "clickHere";
var mouseOverClass = "mouse-over";
var dropZone = $("#" + dropZoneId);
var inputFile = dropZone.find("input");
var finalFiles = {};
$(function() {
var ooleft = dropZone.offset().left;
var ooright = dropZone.outerWidth() + ooleft;
var ootop = dropZone.offset().top;
var oobottom = dropZone.outerHeight() + ootop;
document.getElementById(dropZoneId).addEventListener("dragover", function(e) {
e.preventDefault();
e.stopPropagation();
dropZone.addClass(mouseOverClass);
var x = e.pageX;
var y = e.pageY;
if (!(x < ooleft || x > ooright || y < ootop || y > oobottom)) {
inputFile.offset({
top: y - 15,
left: x - 100
});
} else {
inputFile.offset({
top: -400,
left: -400
});
}
}, true);
if (buttonId != "") {
var clickZone = $("#" + buttonId);
var oleft = clickZone.offset().left;
var oright = clickZone.outerWidth() + oleft;
var otop = clickZone.offset().top;
var obottom = clickZone.outerHeight() + otop;
$("#" + buttonId).mousemove(function(e) {
var x = e.pageX;
var y = e.pageY;
if (!(x < oleft || x > oright || y < otop || y > obottom)) {
inputFile.offset({
top: y - 15,
left: x - 160
});
} else {
inputFile.offset({
top: -400,
left: -400
});
}
});
}
document.getElementById(dropZoneId).addEventListener("drop", function(e) {
$("#" + dropZoneId).removeClass(mouseOverClass);
}, true);
inputFile.on('change', function(e) {
finalFiles = {};
$('#filename').html("");
var fileNum = this.files.length,
initial = 0,
counter = 0;
$.each(this.files, function(idx, elm) {
finalFiles[idx] = elm;
});
for (initial; initial < fileNum; initial++) {
counter = counter + 1;
$('#filename').append('<div id="file_' + initial + '"> <img src="file:///C:/Users/Ashwanth/Pictures/'+this.files[initial].name+'")/><span class="fa-stack fa-lg"><i class="fa fa-file fa-stack-1x "></i><strong class="fa-stack-1x" style="color:#FFF; font-size:12px; margin-top:2px;">' + counter + '</strong></span>' + this.files[initial].name + '<br><Button class=" btn btn-primary closeBtn" onclick="removeLine(this)" title="remove">Remove</Button></div>');
}
});
})
function removeLine(obj) {
inputFile.val('');
var jqObj = $(obj);
var container = jqObj.closest('div');
var index = container.attr("id").split('_')[1];
container.remove();
delete finalFiles[index];
console.log(finalFiles);
}
</script>
I hope MVC Overwrites the url in my javascript. Any Ideas?
I am using the following code from this SO answer, however it does work on here but when I try to remove an image on my side I get:
Uncaught ReferenceError: removeLine is not defined at
HTMLSpanElement.onclick (https://example.com/test/createst/?myDates=2017&myCountry=Italia:1)
NOTE
One other bit I need to do is to create a preview of the uploaded images, I've found the following code by asking another question on SO where I actually had the opposite situation, managed to have a preview but not the remove
var dropZoneId = "drop-zone";
var buttonId = "clickHere";
var mouseOverClass = "mouse-over";
var dropZone = $("#" + dropZoneId);
var inputFile = dropZone.find("input");
var finalFiles = {};
$(function() {
var ooleft = dropZone.offset().left;
var ooright = dropZone.outerWidth() + ooleft;
var ootop = dropZone.offset().top;
var oobottom = dropZone.outerHeight() + ootop;
document.getElementById(dropZoneId).addEventListener("dragover", function(e) {
e.preventDefault();
e.stopPropagation();
dropZone.addClass(mouseOverClass);
var x = e.pageX;
var y = e.pageY;
if (!(x < ooleft || x > ooright || y < ootop || y > oobottom)) {
inputFile.offset({
top: y - 15,
left: x - 100
});
} else {
inputFile.offset({
top: -400,
left: -400
});
}
}, true);
if (buttonId != "") {
var clickZone = $("#" + buttonId);
var oleft = clickZone.offset().left;
var oright = clickZone.outerWidth() + oleft;
var otop = clickZone.offset().top;
var obottom = clickZone.outerHeight() + otop;
$("#" + buttonId).mousemove(function(e) {
var x = e.pageX;
var y = e.pageY;
if (!(x < oleft || x > oright || y < otop || y > obottom)) {
inputFile.offset({
top: y - 15,
left: x - 160
});
} else {
inputFile.offset({
top: -400,
left: -400
});
}
});
}
document.getElementById(dropZoneId).addEventListener("drop", function(e) {
$("#" + dropZoneId).removeClass(mouseOverClass);
}, true);
inputFile.on('change', function(e) {
finalFiles = {};
$('#filename').html("");
var fileNum = this.files.length,
initial = 0,
counter = 0;
$.each(this.files,function(idx,elm){
finalFiles[idx]=elm;
});
for (initial; initial < fileNum; initial++) {
counter = counter + 1;
$('#filename').append('<div id="file_'+ initial +'"><span class="fa-stack fa-lg"><i class="fa fa-file fa-stack-1x "></i><strong class="fa-stack-1x" style="color:#FFF; font-size:12px; margin-top:2px;">' + counter + '</strong></span> ' + this.files[initial].name + ' <span class="fa fa-times-circle fa-lg closeBtn" onclick="removeLine(this)" title="remove"></span></div>');
}
});
})
function removeLine(obj)
{
inputFile.val('');
var jqObj = $(obj);
var container = jqObj.closest('div');
var index = container.attr("id").split('_')[1];
container.remove();
delete finalFiles[index];
//console.log(finalFiles);
}
#drop-zone {
width: 100%;
min-height: 150px;
border: 3px dashed rgba(0, 0, 0, .3);
border-radius: 5px;
font-family: Arial;
text-align: center;
position: relative;
font-size: 20px;
color: #7E7E7E;
}
#drop-zone input {
position: absolute;
cursor: pointer;
left: 0px;
top: 0px;
opacity: 0;
}
/*Important*/
#drop-zone.mouse-over {
border: 3px dashed rgba(0, 0, 0, .3);
color: #7E7E7E;
}
/*If you dont want the button*/
#clickHere {
display: inline-block;
cursor: pointer;
color: white;
font-size: 17px;
width: 150px;
border-radius: 4px;
background-color: #4679BD;
padding: 10px;
}
#clickHere:hover {
background-color: #376199;
}
#filename {
margin-top: 10px;
margin-bottom: 10px;
font-size: 14px;
line-height: 1.5em;
}
.file-preview {
background: #ccc;
border: 5px solid #fff;
box-shadow: 0 0 4px rgba(0, 0, 0, 0.5);
display: inline-block;
width: 60px;
height: 60px;
text-align: center;
font-size: 14px;
margin-top: 5px;
}
.closeBtn:hover {
color: red;
display:inline-block;
}
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="drop-zone">
<p>Drop files here...</p>
<div id="clickHere">or click here.. <i class="fa fa-upload"></i>
<input type="file" name="file" id="file" multiple />
</div>
<div id='filename'></div>
</div>
I'm using the POPR Jquery plugin to get a simple pop-up menu.
While the script is working fine, i always have to click twice to activate my pop-up. How can i get it to work with a single click?
(function($) {
$.fn.popr = function(options) {
var set = $.extend( {
'speed' : 200,
'mode' : 'bottom'
}, options);
return this.each(function() {
var popr_cont = '.popr_container_' + set.mode;
var popr_show = true;
$(this).click(function(event)
{
$('.popr_container_top').remove();
$('.popr_container_bottom').remove();
if (popr_show)
{
event.stopPropagation();
popr_show = false;
}
else
{
popr_show = true;
}
var d_m = set.mode;
var id = $j(this).closest('td').siblings(':first-child').text();
var but_log = '<button title="Logs" type="button" id="log" value="'+ id +'" class="btn btn-default btn-sm"><span class="glyphicon glyphicon-info-sign"></span></button>';
var but_del = '<button title="Verwijder Contract" type="button" id="rem" value="'+ id +'" class="btn btn-default btn-sm"><span class="glyphicon glyphicon-remove"></span></button>';
var but_edi = '<button title="Bewerk Contract" type="button" id="edit" value="'+ id +'" class="btn btn-default btn-sm"><span class="glyphicon glyphicon-pencil"></span></button>';
var but_verl_nu = '<button title="Verleng vanaf nu" type="button" id="verlengvanafnu" value="'+ id +'" class="btn btn-default btn-sm"><span class="glyphicon glyphicon-upload"></span></button>';
var but_verl_eind = '<button title="Verleng vanaf contract eind" type="button" id="verlengvanafeind" value="'+ id +'" class="btn btn-default btn-sm"><span class="glyphicon glyphicon-ok"></span></button>';
var out = '<div class="popr_container_' + d_m + '"><div class="popr_point_' + d_m + '"><div class="popr_content">'+ but_verl_nu + but_verl_eind + but_edi + but_del + but_log +'</div></div></div>';
$(this).append(out);
var w_t = $(popr_cont).outerWidth();
var w_e = $(this).width();
var m_l = (w_e / 2) - (w_t / 2);
$(popr_cont).css('margin-left', m_l + 'px');
$(this).removeAttr('title alt');
$(popr_cont).fadeIn(set.speed);
});
$('html').click(function()
{
$('.popr_container_top').remove();
$('.popr_container_bottom').remove();
popr_show = true;
});
});
};
})(jQuery);
I'm sorry i see i missed a little part of the script.
The popr is used to get options on a huge datagrid.
The piece of script i use to activate the popr is:
$(document).ready(function() {
$('.popr').popr();
});
$("#datagrid").on("click", "td", function(){
$( this ).popr();
});
When i use:
$("#datagrid").on("click", "td", function(){
alert('Feugait');
});
It works in a single click.
Link to the plug-in: http://www.tipue.com/popr/
Works for me using the documentation and demo - answering here for formatting reasons.
NOTE I left the minified POPR minified since it is only here because there is no CDN for it.
// no need to format this. It is the minified version of the POPR code
(function($){$.fn.popr=function(options){var set=$.extend({'speed':200,'mode':'bottom'},options);return this.each(function(){var popr_cont='.popr_container_'+set.mode;var popr_show=true;$(this).click(function(event)
{$('.popr_container_top').remove();$('.popr_container_bottom').remove();if(popr_show)
{event.stopPropagation();popr_show=false;}
else
{popr_show=true;}
var d_m=set.mode;if($(this).attr('data-mode'))
{d_m=$(this).attr('data-mode')
popr_cont='.popr_container_'+d_m;}
var out='<div class="popr_container_'+d_m+'"><div class="popr_point_'+d_m+'"><div class="popr_content">'+$('div[data-box-id="'+$(this).attr('data-id')+'"]').html()+'</div></div></div>';$(this).append(out);var w_t=$(popr_cont).outerWidth();var w_e=$(this).width();var m_l=(w_e / 2)-(w_t / 2);$(popr_cont).css('margin-left',m_l+'px');$(this).removeAttr('title alt');if(d_m=='top')
{var w_h=$(popr_cont).outerHeight()+39;$(popr_cont).css('margin-top','-'+w_h+'px');}
$(popr_cont).fadeIn(set.speed);});$('html').click(function()
{$('.popr_container_top').remove();$('.popr_container_bottom').remove();popr_show=true;});});};})(jQuery);
// ACTUAL INVOCATION:
$(function() {
$('.popr').popr();
});
/*
Popr 1.0
Copyright (c) 2015 Tipue
Popr is released under the MIT License
http://www.tipue.com/popr
*/
.popr
{
cursor: pointer;
}
.popr a
{
color: #333;
text-decoration: none;
border: 0;
}
.popr-box
{
display: none;
}
.popr_content
{
background-color: #fff;
padding: 7px 0;
margin: 0;
}
.popr-item
{
font: 300 14px/1.7 'Helvetica Neue', Helvetica, Arial, sans-serif;
color: #333;
padding: 4px 29px 5px 29px;
}
.popr-item:hover
{
color: #333;
background-color: #dcdcdc;
}
.popr_container_bottom
{
display: none;
position: absolute;
margin-top: 10px;
box-shadow: 2px 2px 5px #f9f9f9;
z-index: 1000;
}
.popr_container_top
{
display: none;
position: absolute;
box-shadow: 2px 2px 5px #f9f9f9;
z-index: 1000;
}
.popr_point_top, .popr_point_bottom
{
position: relative;
background: #fff;
border: 1px solid #dcdcdc;
}
.popr_point_top:after, .popr_point_top:before
{
position: absolute;
pointer-events: none;
border: solid transparent;
top: 100%;
content: "";
height: 0;
width: 0;
}
.popr_point_top:after
{
border-top-color: #fff;
border-width: 8px;
left: 50%;
margin-left: -8px;
}
.popr_point_top:before
{
border-top-color: #dcdcdc;
border-width: 9px;
left: 50%;
margin-left: -9px;
}
.popr_point_bottom:after, .popr_point_bottom:before
{
position: absolute;
pointer-events: none;
border: solid transparent;
bottom: 100%;
content: "";
height: 0;
width: 0;
}
.popr_point_bottom:after
{
border-bottom-color: #fff;
border-width: 8px;
left: 50%;
margin-left: -8px;
}
.popr_point_bottom:before
{
border-bottom-color: #dcdcdc;
border-width: 9px;
left: 50%;
margin-left: -9px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="popr" data-id="1">Feugait nostrud</div>
<div class="popr-box" data-box-id="1">
<div class="popr-item">Feugait delenit</div>
<div class="popr-item">Vero dolor et</div>
<div class="popr-item">Exerci ipsum</div>
</div>
I am making a game so I stared at it for awhile (and yes, I did look at the developer log console for errors), and found no errors (within my reasoning) of why it wouldn't open a battle function.
It is saying that for whatever reason that Giant is not defined when clicked, Zombie is not defined when clicked, and for Giant Spider it says something along the lines of missing parameter. I am quite sure it falls down to the code below -->
for(var z = 0; z < monsters.length; z++) {
Gid("atkOpt_container").innerHTML += ("<div onclick='battle(" + monsters[z].name + "," + this.value + ")' class='monsterContainer' value=" + z + "><div class='monsterT'>" + monsters[z].name + "</div><table><tr><td>Strength</td><td>Health</td><td>XP</td><td>Level</td></tr><tr><td>" + monsters[z].dmg + "</td><td>" + monsters[z].hp + "</td><td>" + monsters[z].xp + "</td><td>" + monsters[z].lvl + "</td></tr></table></div>");
}
If you wish to look at all the code look below. And if you're wondering why everything is so small it's because I'm making it on my phone, and transferred it to ask via GitHub.
var monsters = []; //All monsters are stored here
//All types of monsters are listed below
monsters.push(new monster_prototype("Giant", 50, 30, 1, 20, 20));
monsters.push(new monster_prototype("Giant spider", 20, 50, 1, 15, 30));
monsters.push(new monster_prototype("Zombie", 50, 50, 2, 40, 70));
for (var z = 0; z < monsters.length; z++) {
Gid("atkOpt_container").innerHTML += ("<div onclick='battle(" + monsters[z].name + "," + this.value + ")' class='monsterContainer' value=" + z + "><div class='monsterT'>" + monsters[z].name + "</div><table><tr><td>Strength</td><td>Health</td><td>XP</td><td>Level</td></tr><tr><td>" + monsters[z].dmg + "</td><td>" + monsters[z].hp + "</td><td>" + monsters[z].xp + "</td><td>" + monsters[z].lvl + "</td></tr></table></div>");
} //Where I believe the error occurs, it basically loads all monster stats into a div
function Gid(id) {
return document.getElementById(id);
} //So I don't have to write the whole document.getElementById
function monster_prototype(name, hp, dmg, lvl, xp, money) {
this.name = name;
this.hp = hp;
this.dmg = dmg;
this.lvl = lvl;
this.xp = xp,
this.money = money;
} //How I store the monsters info
function save() {
localStorage.player = JSON.stringify(playerStats);
}
var playerStats = {
lvl: 1,
xp: 0,
xpToLvl: 100,
name: null,
dmg: null,
hp: null,
money: 100
};
if (localStorage.player === undefined) {
save();
playerSetup();
} else {
playerStats = JSON.parse(localStorage.player);
alert("Welcome back " + playerStats.name);
refreshStats();
} //Checks if the player is new, and if so starts the main player setup. If not it loads it
function refreshStats() {
Gid("maxDmg").innerHTML = "Max damage: " + playerStats.dmg;
Gid("hp").innerHTML = "Health: " + playerStats.hp;
} //Refreshes some stats
function playerSetup() {
document.getElementById("mainContainer").style.display = "none";
$("#class_container").show();
}
function classChosen(pClass) {
if (pClass === "Juggernaut") {
playerStats.hp = 100;
playerStats.dmg = 10;
} else if (pClass === "Average Joe") {
playerStats.hp = 60;
playerStats.dmg = 30;
} else {
playerStats.hp = 40;
playerStats.dmg = 70;
}
refreshStats();
document.getElementById("class_container").style.display = "none";
var getName = prompt("What is your name?");
playerStats.name = getName;
document.getElementById("mainContainer").style.display = "block";
save();
} //Starts the class choosing feature
function toggle(id) {
$("#" + id).toggle();
} //Toggles display (Hidden or block)
function restartGame() {
localStorage.removeItem('player');
location.reload();
}
function battle(enemy, enemyLoc) {
console.log(enemy + " and " + enemyLoc);
enemy = enemy.toLowerCase();
Gid("attackInfo").innerHTML = "";
var battleWords = ['slashed', 'bashed', 'stabbed', 'punched'];
var enemyHp = monsters[enemyLoc].hp;
var enemyDmg = monsters[enemyLoc].dmg;
var playerHp = playerStats.hp;
var playerDmg = playerStats.dmg;
var battleLoop = setInterval(function() {
var atkName1 = Math.floor(Math.random() * battleWords.length);
var atkName2 = Math.floor(Math.random() * battleWords.length);
var enemyDealt = Math.round(Math.random() * enemyDmg);
var playerDealt = Math.round(Math.random() * enemyDmg);
playerHp -= enemyDealt;
enemyHp -= playerDealt;
Gid("attackInfo").innerHTML += ("<strong>•</strong>" + enemy + " " + battleWords[atkName1] + " you and dealt " + enemyDealt + " damage to you and you now have " + playerHp + " health remaining.<br>You " + battleWords[atkName2] + " the " + enemy + " and dealt " + playerDealt + " damage. The " + enemy + " has " + enemyHp + " health remaining.<br><br>");
if (enemyHp <= 0 && playerHp <= 0) {
clearInterval(battleLoop);
alert("You both died at the same time! A win... but mainly a loss. Game over");
restartGame();
} else if (enemyHp <= 0) {
clearInterval(battleLoop);
alert("You won!");
playerStats.money += monsters[enemyLoc].money;
playerStats.xp += monsters[enemyLoc].xp;
if (playerStats.xp >= playerStats.xpToLvl) levelUp();
} else if (playerHp <= 0) {
alert("Game over");
clearInterval(battleLoop);
restartGame();
}
}, 1000);
} //Main battle, this is the function that won't load
function levelUp() {
} //TBA
#container {
background-color: gray;
width: 300px;
height: 350px;
margin: auto;
}
#atkOpt_container {
display: none;
}
#attackBtn {
background-color: black;
width: 96px;
color: yellow;
border: 4px groove red;
float: left;
font-size: 30px;
text-align: center;
display: block;
margin-top: 5px;
margin-left: 5px;
}
#attackInfo {
float: left;
background-color: #eee;
width: 200px;
font-size: 10px;
height: 250px;
clear: left;
display: block;
margin-top: 5px;
margin-left: 5px;
border: 2px solid red;
}
#class_container {
z-index: 10;
display: none;
width: 300px;
height: 150px;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
background-color: orange;
overflow: auto;
border: 5px groove black;
}
.playerClass {
margin: auto;
width: 200px;
border: 5px groove red;
color: #00FF00;
font-size: 35px;
text-align: center;
margin-bottom: 5px;
display: block;
background-color: black;
}
#title {
width: 95%;
background-color: black;
color: #00FF00;
border: 1px solid orange;
font-size: 25px;
font-weight: bolder;
text-align: center;
margin: auto;
}
#atkOpt_container {
z-index: 11;
width: 275px;
height: 300px;
overflow: auto;
background-color: black;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
border: 2px solid orange;
}
.monsterContainer {
width: 200px;
margin: auto;
text-align: center;
background-color: orange;
border: 5px groove red;
margin-bottom: 5px;
}
.monsterT {
width: 100%;
background-color: black;
color: #eee;
font-size: 30px;
text-align: center;
}
td {
background-color: Cyan;
font-size: 15px;
width: 49%;
border: 1px solid black;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id="class_container">
<div id="title">Choose a class</div>
<div onclick="classChosen(this.innerHTML)" class="playerClass">Juggernaut</div>
<div onclick="classChosen(this.innerHTML)" class="playerClass">Masculine Mat</div>
<div onclick="classChosen(this.innerHTML)" class="playerClass">Average Joe</div>
</div>
<div id="mainContainer">
<div id="container">
<div id="attackBtn" onclick="toggle('atkOpt_container'); toggle('mainContainer');">Attack</div>
<div id="attackInfo"></div>
<div id="maxDmg">Max damage: 0</div>
<div id="hp">Health: 0</div>
</div>
<button onclick="restartGame();">Delete stats</button>
</div>
<div id="atkOpt_container"></div>
</body>
</html>
Because
"<div onclick='battle(" + monsters[z].name + "," + this.value + ")'
produces
<div onclick='battle(whatever, whatever)'
Which is wrong, because you do not have quotes around the strings. You need to quote them. So add in the "
"<div onclick='battle(\"" + monsters[z].name + "\",\"" + this.value + "\")'
Ideally you would use DOM methods such as createElement and addEventListener so you would not have to deal with this.