I make a drop down on pop up screen. I am able to make that drop down using jQuery mobile. I used dform plugin. Everything is working fine. But I have one issue my first character display in capital letter when I added bootstrap.min.css - why?
When I run my program without bootstrap.min.css, it works fine. But when I run with bootstrap.css, it give first letter capital after . . As I written in small. This problem is only in chrome browser. When I run in firefox it works perfectly.
Can you please explain why it is occurring?
Here is my code.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<link href=" https://dl.dropboxusercontent.com/s/bbvcx2zc4ocuqzt/bootstrap.min.css?m=" rel="stylesheet" type="text/css" />
<link href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css" rel="stylesheet" type="text/css" />
<link href=" https://dl.dropboxusercontent.com/s/hg36tk1m7rc4gnj/style.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
<script src="https://rawgit.com/daffl/jquery.dform/master/dist/jquery.dform-1.1.0.js"></script>
</head>
<body>
<button id="test">test</button>
<div data-role="popup" data-dismissible='false' data-transition="flip" id="tabbedPopup" data-theme="a"><a href="#"
data-rel="back"
data-role="button"
data-theme="a"
data-icon="delete"
data-iconpos="notext"
class="ui-btn-right cross-border cross-border closePopUp_h button circleClass" >Close</a>
<div id="commandInfo"></div>
<div id="commandInfoheader" class="comandinfoheader"></div>
<div data-role="collapsible-set" data-theme="b" data-content-theme="b" id="tabbedSet" data-iconpos="left">
</div>
</div>
</body>
<script type="text/javascript">
$(function () {
$('#test').click(function(){
createCommandPopUpTabs("tc_2-cmd_1_VoiceCallAudioMosMO");
$("#tabbedPopup").popup("open");
})
});
function createCommandPopUpTabs(id) {
var tabsHeader = ["InputParameter"];
var header = "<h3 >hh</h3>";
var commmand = "VoiceCallAudioMosMO";
var button = '<button onclick="return submitCommand("' + id
+ '")" style="" class="donebtn common-button1">Save</button>';
//$("#commandInfo").append(header);
$("#commandInfo").append(button);
$("#commandInfoheader").html(header);
for ( var i = 0; i < tabsHeader.length; i++) {
var headerId = tabsHeader[i] + "_tab" + commmand;
var header = "<div data-role='collapsible' data-collapsed='false' id='"
+ headerId + "'><h3>hhh</h3></div>";
var content = generateCommandTabContent(tabsHeader[i], id);
$("#tabbedSet").append(header);
$("#tabbedSet").find("#" + headerId).append(content);
$("#tabbedSet").collapsibleset("refresh");
$('input[name=direction]').parent().addClass('cleassr')
$("#tabbedSet").children(":first").collapsible( "expand" );
}
}
function generateCommandTabContent(name, id) {
var commandName = "VoiceCallAudioMosMO";
if (name == "InputParameter") {
var object = new window[commandName]();
var map = object.generateInputRequirment();
var formData = generateInputParamForm(map, id, status);
var form = $("<form />");
var dform = form.dform(formData);
return dform;
}
return null;
}
function VoiceCallAudioMosMO() {
COMMAND_NAME = "VoiceCallMos";
COMMAND_DISPLAY_NAME = "VoiceCallMOS";
this.map = {};
}
VoiceCallAudioMosMO.prototype.generateInputRequirment = function () {
if(typeof VoiceCallAudioMosMO.JSON!="undefined") {
var inputs = VoiceCallAudioMosMO.JSON.input;
for (var key in inputs) {
var inputField = inputs[key];
var inputParameterInfo = new InputParameterInfo();
for (var inputKey in inputField) {
inputParameterInfo[inputKey] = inputField[inputKey];
}
this.map[inputParameterInfo.name] = inputParameterInfo;
}
return this.map;
}
};
function InputParameterInfo() {
}
VoiceCallAudioMosMO.JSON = {
"commandName": "VoiceCallAudioMosMO",
"input": {
"refFileName": {
"displayDetail": "The reference file name to play in case of uplink channel",
"displayName": "Ref File Name",
"inputType": "SWITCH",
"name": "refFileName",
"inputValues": {
"USAReference.wav": "USAReference.wav",
"Reference.wav": "Reference.wav"
},
"value": "",
"unit": "NONE",
"required": false,
"visible": true
}
}
};
function generateInputParamForm(map, id, status) {
var formId = "form_" + id;
var formdata = {
elements : []
};
formdata.id = formId;
formdata.name = formId;
formdata.method = "post";
var div = {
html : []
};
div.type = "div";
div.class = "inputDiv";
div.caption = "<h3>Input Parameters</h3>";
var tabIndex = 1;
var arr = id.split("-");
var data = null;
for ( var key in map) {
var inputObj = map[key];
if (inputObj.visible==false && inputObj.required==false) {
continue;
}else {
var obj = createFormObject(inputObj);
}
//var obj = createFormObject(inputObj);
if(typeof data=="undefined"){
obj.value = inputObj["value"];
}else if (data != undefined && data.hasOwnProperty(inputObj["name"])) {
obj.value = data[inputObj["name"]];
}
/*if (data != undefined && data.hasOwnProperty(inputObj["name"])) {
obj.value = data[inputObj["name"]];
} else if (inputObj.hasOwnProperty("value")) {
obj.value = inputObj["value"];
}*/
if (status == "view") {
obj.readonly = "true";
obj.disabled = "disabled";
}
obj.tabindex = tabIndex;
var objName = "VoiceCallAudioMosMO";
obj.onblur = "validateElement('" + objName + "', '" + formId + "','"
+ obj.name + "')";
var unit = {};
var fieldset = {
html : []
};
fieldset.type = "fieldset";
fieldset.caption = inputObj["displayName"];
fieldset.html.push(obj);
$("div > fieldset legend:contains('*')").each(function () {
$(this).html($(this).html().replace("*", "<span class='red'>*</span>"));
});
div.html.push(fieldset);
tabIndex++;
}
formdata.elements.push(div);
return formdata;
}
function createFormObject(inputObj) {
var obj = {};
if (inputObj.hasOwnProperty("inputType")) {
if (inputObj["inputType"] == "LIST") {
var list = inputObj["inputValues"];
obj.type = "select";
obj.options = list;
} else if (inputObj["inputType"] == "NUMBER") {
obj.type = "text";
} else if (inputObj["inputType"] == "SWITCH") {
var list = inputObj["inputValues"];
obj.type = "select";
obj.options = list;
} else {
obj.type = "text";
}
} else {
obj.type = "text";
}
if (!inputObj.hasOwnProperty("displayName")) {
obj.type = "hidden";
}
obj.id = inputObj["name"];
obj.name = inputObj["name"];
obj.required = inputObj["required"];
obj.placeholder = inputObj["placeholder"];
obj.classes = inputObj["class"];
obj.className = inputObj["class"];
obj.class = inputObj["class"];
obj.title= inputObj["displayDetail"];
return obj;
}
</script>
</html>
It display a drop down when you click button.Drop down Value USAReference.wav.here I written "w" in small but it display in capital.but when I remove this css
https://dl.dropboxusercontent.com/s/bbvcx2zc4ocuqzt/bootstrap.min.css?m=" rel="stylesheet" type="text/css" />
it show in small letter ? why ?
After a long research I found the solution own .there is a property
text-transform: capitalize written on 247 line Number bootstrap.css file.I remove that property.I am able to solve my problem
Related
I am creating a status posting and commenting system.
It is implemented in Vanilla JavaScript. Anyone can add a post and can comment on the post.
Everything is working fine but the comment section is working on first post only.
deletion of comment and post is working fine.
I don't know what's the problem is, if anyone could help me..
Here is the HTML code
<div class="container-post" id="container-post">
<div class="create-post">
<form>
<div class="form-group">
<div class="username">
<p class="name" style="top:15px;">User Name</p>
</div>
<p class="qoutes">
<textarea style=" font-size: 15pt;" class="form-control" id="enter-post" rows="7" id="mypara" placeholder="Share Your Thoughts..."></textarea>
</p>
<div class="postbar">
<button type="button" class="btn btn-primary post-me" id="post-button"> <span id="postText">Post</span></button>
</div>
</div>
</form>
</div>
<hr class="line-bar">
<div class="allpost">
<div class="mainpost" id="post-div"></div>
</div>
Here is the JavaSCript code
showTask();
showComment();
let addPost = document.getElementById("enter-post");
let addPostBtton = document.getElementById("post-button");
addPostBtton.addEventListener("click", function () {
var addPostVal = addPost.value;
if (addPostVal.trim() != 0) {
let webtask = localStorage.getItem("localtask");
if (webtask == null) {
var taskObj = [];
}
else {
taskObj = JSON.parse(webtask);
}
taskObj.push(addPostVal);
localStorage.setItem("localtask", JSON.stringify(taskObj));
}
showTask();
});
function showTask() {
let webtask = localStorage.getItem("localtask");
if (webtask == null) {
var taskObj = [];
}
else {
taskObj = JSON.parse(webtask);
}
let htmlVal = '';
let createPost = document.getElementById("post-div");
taskObj.forEach((item, index) => {
htmlVal += `
<div class="post-class"><div class="username u-name">
<p class="name i-name">${"User Name " + index}</p>
<i class="fas fa-trash-alt" onclick="removePost(${index});"></i></button>
</div>
<hr>
<p class="quotes">
${item}
</p>
<div class="comment-section" id="comment-section">
<p class="comment-qoute">
<textarea style=" font-size: 15pt;" class="form-control commentBox" rows="3" id="mypara" placeholder="Leave a comment"></textarea>
</p>
<button class="btn btn-primary comment-btn" id="commentBtn">comment</button>
<ul class="comments" id="comments-portion">
<p></p>
</ul>
</div>
</div>
<br><br>`
});
createPost.innerHTML = htmlVal;
}
function removePost(index) {
let webtask = localStorage.getItem("localtask");
let taskObj = JSON.parse(webtask);
taskObj.splice(index, 1);
localStorage.setItem("localtask", JSON.stringify(taskObj));
showTask();
}
var commentPost = document.getElementById('mypara');
var commentBtn = document.getElementById('commentBtn');
commentBtn.addEventListener('click', function () {
var commentValue = commentPost.value;
if (commentValue.trim() != 0) {
let commentTask = localStorage.getItem("comments");
if (commentTask == null) {
var commentObj = [];
}
else {
commentObj = JSON.parse(commentTask);
}
commentObj.push(commentValue);
localStorage.setItem("comments", JSON.stringify(commentObj));
}
showComment();
});
function showComment() {
let commentsTask = localStorage.getItem("comments");
if (commentsTask == null) {
var commentObj = [];
}
else {
commentObj = JSON.parse(commentsTask);
}
let commentHTMLValue = '';
var createComment = document.getElementById("comments-portion");
commentObj.forEach((item, index) => {
commentHTMLValue += `<div class="comment-box-btn">
<p>${index + ". "}<span>${item}</span></p>
<i class="far fa-times-circle fa-2x" onclick="removeComment(${index});"></i>
</div>
`;
});
createComment.innerHTML = commentHTMLValue;
}
var deleteBtn = document.querySelector('.comment-del');
deleteBtn.addEventListener('click', () => {
});
// remove comment
function removeComment(index) {
let commentTask = localStorage.getItem("comments");
let commentObj = JSON.parse(commentTask);
commentObj.splice(index, 1);
localStorage.setItem("comments", JSON.stringify(commentObj));
showComment();
}
When you use code like:
createComment.innerHTML = commentHTMLValue;
you are completely replacing the contents of the element. Try using:
createComment.innerHTML += commentHTMLValue;
which appends new content to the end of the existing contents.
I can't do a snippet here as the use of localStorage is not allowed. Copy this block into a blank file and save it as an html file and then open that in a browser.
This is how I think you are describing your requirements and is also based on the data format in my comments. It's not pretty and needs plenty of sprucing up, but it runs.
<!DOCTYPE html>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
<html>
<head>
<title>Task listing</title>
<script type="text/javascript">
let taskList = [];
function checkTasks() {
let tasksList = getTasksList();
if (tasksList.length == 0) {
let newTask = prompt("Please enter a task description");
if (newTask) {
let thisIndex = getNewIndex();
let a = {"id": thisIndex, "task": newTask, "comments": []}
taskList.push(a);
saveTasksList(taskList);
}
}
displayTasks();
}
function displayTasks() {
let container = document.getElementById("tasks");
container.innerHTML = "";
let taskList = getTasksList();
taskList.forEach(function(task){
let d = document.createElement("div");
d.id = "task_" + task.id;
d.className = "commentdiv";
d.innerHTML = "<h3>" + task.task + "</h3>";
let l = document.createElement("ul");
l.id = "comments_" + task.id;
let comments = task.comments;
if (comments.length > 0) {
let commentindex = 0;
comments.forEach(function(comment) {
let c = document.createElement("li");
c.innerHTML = comment;
let cb = document.createElement("button");
cb.id = "deletecomment_" + task.id + "_" + commentindex;
cb.innerHTML = "Delete comment";
cb.onclick = function() {deleteComment(task.id, commentindex);};
c.appendChild(cb);
l.appendChild(c);
})
}
let b = document.createElement("button");
b.id = "addcomment_" + task.id;
b.onclick = function() {addComment(task.id);};
b.innerHTML = "Add comment";
d.appendChild(b);
d.appendChild(l);
container.appendChild(d);
})
}
function addComment(taskid) {
let newcomment = prompt("Enter comment");
if (newcomment) {
let tasklist = getTasksList();
let filtered = tasklist.filter(task => task.id == taskid);
if (filtered[0]) {
let thisTask = filtered[0];
thisTask.comments.push(newcomment);
let thisIndex = taskList.findIndex((task) => task.id == taskid);
taskList[thisIndex] = thisTask;
}
saveTasksList(taskList);
displayTasks();
}
}
function addNewTask() {
let newTask = prompt("Enter task description");
let taskList = getTasksList();
let lastindex = localStorage.getItem("tasksindex");
let index = getNewIndex();
let a = {"id": index, "task": newTask, "comments": []}
taskList.push(a);
saveTasksList(taskList);
displayTasks();
}
function deleteComment(taskid, commentindex) {
let tasklist = getTasksList();
let filtered = tasklist.filter(task => task.id == taskid);
// as long as there is at least one task with the taskid value, find and delete the comment
// based on the index position of the comment in the comments array
if (filtered[0]) {
let thisTask = filtered[0];
thisTask.comments.splice(commentindex, 1);
let thisIndex = taskList.findIndex((task) => task.id == taskid);
taskList[thisIndex] = thisTask;
}
saveTasksList(taskList);
displayTasks();
}
function getTasksList() {
let tasks = localStorage.getItem("tasks");
taskList = JSON.parse(tasks);
if (!taskList) {
taskList = [];
}
return taskList;
}
function saveTasksList(taskList) {
localStorage.setItem("tasks", JSON.stringify(taskList));
}
function getNewIndex() {
let lastindex = localStorage.getItem("tasksindex");
let idx = 0;
if (!lastindex) {
idx = 1;
} else {
idx = Number(lastindex) + 1;
}
localStorage.setItem("tasksindex", idx);
return idx;
}
function removeAll() {
localStorage.removeItem("tasks");
localStorage.removeItem("tasksindex");
displayTasks();
}
window.onload = checkTasks;
</script>
<style type="text/css">
.commentdiv {
border:1px solid black;
width:1000px;
padding:5px;
border-radius:5px;
}
button {
margin-left:10px;
}
h3 {
width:100%;
border-bottom: 1px dotted black;
}
ul {
list-style-type:decimal;
}
</style>
</head>
<body>
<h2>My task list <button id="addNewTaskButton" onclick="addNewTask();">Add new task</button></h2>
<hr>
<div id="tasks">
</div>
<button id="removeAll" onclick="removeAll();">Remove all tasks</button>
</body>
</html>
I'm new at JavaScript to be patient with me. I'm trying to get this little "game" to work where you drag cards in the drop box, and when you drop the joker card in it says "victory", otherwise it says "betrayal" for the other cards. Everything works great except the part where it says "victory" when you drop the joker. I feel like I have tried everything. The joker card is $(#black_joker)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Drag and Drop</title>
<link rel="stylesheet" href="dragdrop.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
</head>
<body>
<h1>Find the Joker and eliminate him!</h1>
<br>
<input type="button" value="Deal!" id="dealDeck">
<br>
<br>
<br>
<br>
<br>
<div id='dropZone' class='dropZone'> <center>Find the joker card and drop it here to get rid of him once and for all! </center></div>
<script src="dragdrop.js"></script>
</body>
</html>
// JAVASCRIPT
$(document).ready(function () {
$(init);
function init() {
$('.dropZone').droppable({
drop: handleDropEvent
});
}
for (var a=0, all = 53; a < all; a++){
$('#dealDeck').click(function () {
dealCard(randomCard());
});
}
var cardsInDeck = new Array();
var numberOfCardsInDeck = 53;
cardsInDeck[0] = "C1";
cardsInDeck[1] = "C2";
cardsInDeck[2] = "C3";
cardsInDeck[3] = "C4";
cardsInDeck[4] = "C5";
cardsInDeck[5] = "C6";
cardsInDeck[6] = "C7";
cardsInDeck[7] = "C8";
cardsInDeck[8] = "C9";
cardsInDeck[9] = "C10";
cardsInDeck[10] = "C11";
cardsInDeck[11] = "C12";
cardsInDeck[12] = "C13";
cardsInDeck[13] = "D1";
cardsInDeck[14] = "D2";
cardsInDeck[15] = "D3";
cardsInDeck[16] = "D4";
cardsInDeck[17] = "D5";
cardsInDeck[18] = "D6";
cardsInDeck[19] = "D7";
cardsInDeck[20] = "D8";
cardsInDeck[21] = "D9";
cardsInDeck[22] = "D10";
cardsInDeck[23] = "D11";
cardsInDeck[24] = "D12";
cardsInDeck[25] = "D13";
cardsInDeck[26] = "H1";
cardsInDeck[27] = "H2";
cardsInDeck[28] = "H3";
cardsInDeck[29] = "H4";
cardsInDeck[30] = "H5";
cardsInDeck[31] = "H6";
cardsInDeck[32] = "H7";
cardsInDeck[33] = "H8";
cardsInDeck[34] = "H9";
cardsInDeck[35] = "H10";
cardsInDeck[36] = "H11";
cardsInDeck[37] = "H12";
cardsInDeck[38] = "H13";
cardsInDeck[39] = "S1";
cardsInDeck[40] = "S2";
cardsInDeck[41] = "S3";
cardsInDeck[42] = "S4";
cardsInDeck[43] = "S5";
cardsInDeck[44] = "S6";
cardsInDeck[45] = "S7";
cardsInDeck[46] = "S8";
cardsInDeck[47] = "S9";
cardsInDeck[48] = "S10";
cardsInDeck[49] = "S11";
cardsInDeck[50] = "S12";
cardsInDeck[51] = "S13";
cardsInDeck[52] = "black_joker";
function dealCard(i) {
if (numberOfCardsInDeck == 0) return false;
var img = document.createElement("img");
img.src = "http://deetito.com/images/" + cardsInDeck[i] + ".png";
img.id = cardsInDeck[i];
img.width = 100;
img.height = 125;
document.body.appendChild(img);
$('#C1').draggable();
$('#C2').draggable();
$('#C3').draggable();
$('#C4').draggable();
$('#C5').draggable();
$('#C6').draggable();
$('#C7').draggable();
$('#C8').draggable();
$('#C9').draggable();
$('#C10').draggable();
$('#C11').draggable();
$('#C12').draggable();
$('#C13').draggable();
$('#D1').draggable();
$('#D2').draggable();
$('#D3').draggable();
$('#D4').draggable();
$('#D5').draggable();
$('#D6').draggable();
$('#D7').draggable();
$('#D8').draggable();
$('#D9').draggable();
$('#D10').draggable();
$('#D11').draggable();
$('#D12').draggable();
$('#D13').draggable();
$('#H1').draggable();
$('#H2').draggable();
$('#H3').draggable();
$('#H4').draggable();
$('#H5').draggable();
$('#H6').draggable();
$('#H7').draggable();
$('#H8').draggable();
$('#H9').draggable();
$('#H10').draggable();
$('#H11').draggable();
$('#H12').draggable();
$('#H13').draggable();
$('#S1').draggable();
$('#S2').draggable();
$('#S3').draggable();
$('#S4').draggable();
$('#S5').draggable();
$('#S6').draggable();
$('#S7').draggable();
$('#S8').draggable();
$('#S9').draggable();
$('#S10').draggable();
$('#S11').draggable();
$('#S12').draggable();
$('#S13').draggable();
$('#black_joker').draggable();
removeCard(i);
}
function randomCard() {
return Math.floor(Math.random() * numberOfCardsInDeck);
}
function handleDropEvent(event, ui) {
var card = ui.draggable;
if (card == 'black_joker') {
$('#dropZone').html('victory!');}
else {
$('#dropZone').html('betrayal!');}
/*$('#dropZone').droppable({
drop: function(event, ui) {
ui.draggable.remove();
}
});*/
$("#dropZone").on('mouseover', function() {
//alert('bye draggable!');
//ui.draggable.draggable('disable');
//$(this).droppable('disable');
ui.draggable.remove();
})
}
function removeCard(c) {
// simply make every higher numbered card move down 1
for (j = c; j <= numberOfCardsInDeck - 2; j++) {
cardsInDeck[j] = cardsInDeck[j + 1];
}
numberOfCardsInDeck--;
}
});
I believe you are comparing object with string.
ui.draggable should be jQuery object
let card = ui.draggable.attr("id");
compare it with your id or other attribute you wanted to use should work
New to JS here, been struggling with this one for a few hours now.
So I created a to do list with a button that stores objects in an array inside localStorage and also creates dynamic list items with content and delete buttons. Whenever I click the delete button it removes the dynamic list item but doesn't remove it from localStorage. I can't figure out how to assign each button to the specific array index in localStorage.
https://codepen.io/jupiterisland/pen/ooPXWV
var taskList = []; //build array
if(localStorage.taskList){ //call func to recreate li's on refresh
taskList = JSON.parse(localStorage.taskList) || [];
createTasks(taskList)
}
function submitFunc() {
var task = { //build objects
desc: document.getElementsByTagName("textarea")[0].value,
date: document.getElementsByTagName("input")[0].value,
time: document.getElementsByTagName("input")[1].value,
important: document.getElementsByTagName("input")[1].checked
};
if(task.desc && task.date !== ""){
taskList[taskList.length] = task; //put objects inside array
localStorage.taskList = JSON.stringify(taskList); //store array with stringify
newTaskList = JSON.parse(localStorage.taskList); //retrieve array with parse
createTasks(newTaskList)
document.getElementById("error").style.display = "none";
return false; //prevent submit
} else {
document.getElementById("error").style.display = "block";
document.getElementById("error").innerHTML = "Please enter a task description and a date.";
return false;
}
}
function createTasks (newTaskList){
for (i = 0; i < newTaskList.length; i++) { // display objects in list items
var currentTask = newTaskList[i];
var taskIndex = newTaskList.indexOf(currentTask);
newElement();
function newElement() {
var liNode = document.createElement("li");
var titleNode = document.createElement("h3");
var dNode = document.createElement("p");
var tNode = document.createElement("p");
var delNode = document.createElement("button")
liNode.className = "liNode";
titleNode.className = "titleNode";
dNode.className = "dNode";
tNode.className = "tNode";
delNode.className = "delete";
delNode.innerText = "Delete";
var titleText = newTaskList[i].desc;
var dateText = newTaskList[i].date;
var timeText = newTaskList[i].time;
var descNode = document.createTextNode(titleText);
var dateNode = document.createTextNode(dateText);
var timeNode = document.createTextNode(timeText);
titleNode.appendChild(descNode);
dNode.appendChild(dateNode);
tNode.appendChild(timeNode);
liNode.appendChild(titleNode);
liNode.appendChild(dNode);
liNode.appendChild(tNode);
liNode.appendChild(delNode);
document.getElementById("taskBoard").appendChild(liNode);
if (taskBoard.childElementCount > newTaskList.length) { //remove excess divs
for (n = 0; taskBoard.childElementCount - 2; n++) {
taskBoard.removeChild(taskBoard.firstChild);
}
}
function deleteTasks(){
var listItem = this.parentNode;
var ul = listItem.parentNode;
ul.removeChild(listItem);
}
delNode.addEventListener("click", deleteTasks);
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>My Task Board</h1>
<div class="container">
<form onsubmit="return submitFunc()">
<div>
<label for="">Task:</label>
<textarea name="name" rows="8" cols="80"placeholder="Please enter your task description"></textarea>
</div>
<div>
<label for="">Deadline:</label>
<input type="date" placeholder="Choose a date">
<input type="time" placeholder="Set time">
</div>
<div>
<label for="">Important:</label>
<input type="checkbox" name="" value="">
</div>
<button type="submit" name="button">Add Task</button>
<div id="error"></div>
</form>
</div>
<div>
<ul id="taskBoard"></ul>
</div>
</body>
</html>
var taskList = []; //build array
if(localStorage.taskList){ //call func to recreate li's on refresh
taskList = JSON.parse(localStorage.taskList) || [];
createTasks(taskList)
}
function fakeGuid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
function submitFunc() {
var task = { //build objects
desc: document.getElementsByTagName("textarea")[0].value,
date: document.getElementsByTagName("input")[0].value,
time: document.getElementsByTagName("input")[1].value,
important: document.getElementsByTagName("input")[1].checked,
id :fakeGuid()
};
if(task.desc && task.date !== ""){
taskList[taskList.length] = task; //put objects inside array
localStorage.taskList = JSON.stringify(taskList); //store array with stringify
newTaskList = JSON.parse(localStorage.taskList); //retrieve array with parse
createTasks(newTaskList)
document.getElementById("error").style.display = "none";
return false; //prevent submit
} else {
document.getElementById("error").style.display = "block";
document.getElementById("error").innerHTML = "Please enter a task description and a date.";
return false;
}
}
function createTasks (newTaskList){
for (i = 0; i < newTaskList.length; i++) { // display objects in list items
newElement(i);
function newElement(currentIndex) {
var liNode = document.createElement("li");
var titleNode = document.createElement("h3");
var dNode = document.createElement("p");
var tNode = document.createElement("p");
var delNode = document.createElement("button")
liNode.className = "liNode";
titleNode.className = "titleNode";
dNode.className = "dNode";
tNode.className = "tNode";
delNode.className = "delete";
delNode.innerText = "Delete";
var titleText = newTaskList[i].desc;
var dateText = newTaskList[i].date;
var timeText = newTaskList[i].time;
var descNode = document.createTextNode(titleText);
var dateNode = document.createTextNode(dateText);
var timeNode = document.createTextNode(timeText);
titleNode.appendChild(descNode);
dNode.appendChild(dateNode);
tNode.appendChild(timeNode);
liNode.appendChild(titleNode);
liNode.appendChild(dNode);
liNode.appendChild(tNode);
liNode.appendChild(delNode);
document.getElementById("taskBoard").appendChild(liNode);
if (taskBoard.childElementCount > newTaskList.length) { //remove excess divs
for (n = 0; taskBoard.childElementCount - 2; n++) {
taskBoard.removeChild(taskBoard.firstChild);
}
}
function deleteTasks(node, currentTask) {
var listItem = node.parentNode;
var ul = listItem.parentNode;
ul.removeChild(listItem);
taskList = taskList.filter(function(t) {
return t.id !== currentTask.id;
});
localStorage.taskList = JSON.stringify(taskList); //store array with stringify
}
var currentTask = newTaskList[currentIndex];
delNode.addEventListener("click", () => deleteTasks(delNode, currentTask));
}
}
}
Don't try to use index to manipulate DOM element. Instead use some kind of unique ID. In this case I created a fake GUID.
Read more on closure. The reason you are not able to pass index down to the function is because the index is bound to another context.
Any reason to stringify JSON for local storage? You can simply store an array.
I am trying to detect a keypress using the jQuery keyup function, but it does not seem to work in Firefox. Though it does work in Chrome, Edge, IE and Opera.
$(".textfield").contents().keyup(function(evnt) {
document.getElementById("btn_save").style.opacity = "1";
saved = false;
});
".textfield" is an iframe with designmode = 'on' So I'm trying to detect a keyup within a editable iframe.
Here's my iframe, nothing special:
<iframe class="textfield" name="textfield" frameBorder="0"></iframe>
EDIT: (It's one of my first websites, so don't mind the bad code)
HTML
<head>
<title>Notepad - A minimalistic, free online text editor for your notes</title>
<meta charset="utf-8"/>
<meta name="description" content="Notepad is a free, minimalistic, online text editor for quickly writing down, saving and sharing your notes."/>
<link type="text/css" rel="stylesheet" href="style.css"/>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="filesaver/filesaver.js"></script>
<link href="https://fonts.googleapis.com/css?family=Khula|Roboto|Open+Sans|Barrio|Cairo|Cantarell|Heebo|Lato|Open+Sans|PT+Sans" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js"></script>
<!-- Fonts -->
<script>
WebFont.load({
google: {
families: ['Cantarell', "Open Sans"]
}
});
</script>
</head>
<body onload="enableEdit('dark'); handlePaste(); handleDrop(); retrieveNote(); createCookie();">
<!-- Facebook & Twitter Share -->
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/nl_NL/sdk.js#xfbml=1&version=v2.9";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<div id="social">
<div class="fb-share-button" data-href="https://developers.facebook.com/docs/plugins/" data-layout="button_count" data-size="small" data-mobile-iframe="true"><a class="fb-xfbml-parse-ignore" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fdevelopers.facebook.com%2Fdocs%2Fplugins%2F&src=sdkpreparse" style="vertical-align:top;zoom:1;*display:inline">Share</a></div>
<a class="twitter-share-button" href="https://twitter.com/intent/tweet"></a>
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
</div>
<!-- Page -->
<div id="page">
<!-- Textfield -->
<iframe class="textfield" name="textfield" frameBorder="0"></iframe>
<!-- Toolbar -->
<div id="toolbar">
<h1 class="button" id="btn_bold" onclick="bold();" onmouseenter="onMouseEnter('btn_bold');" onmouseleave="onMouseLeave('btn_bold');"><b>B</b></h1>
<h1 class="button" id="btn_ita" onclick="italic();" onmouseenter="onMouseEnter('btn_ita');" onmouseleave="onMouseLeave('btn_ita');"><i>I</i></h1>
<h1 class="button" id="btn_und" onclick="underline();" onmouseenter="onMouseEnter('btn_und');" onmouseleave="onMouseLeave('btn_und');"><u>U</u></h1>
<img src="img/theme_dark.png" alt="Change theme" class="button theme" id="btn_theme" onclick="changeTheme();" onmouseenter="onMouseEnter('btn_theme');" onmouseleave="onMouseLeave('btn_theme')"; alt="Change theme." title="Theme"></img>
<img src="img/save.png" type="button" id="btn_save" value="submit" onclick="post();" class="button theme" alt="Save note." onmouseenter="onMouseEnter('btn_save');" onmouseleave="onMouseLeave('btn_save')" title="Save note"/>
<img src="img/cloud.png" type="button" id="btn_down" onclick="download();" class="button theme" alt="Download note" onmouseenter="onMouseEnter('btn_down');" onmouseleave="onMouseLeave('btn_down')" title="Download note"/>
<h1 class="button" id="btn_plus" onmousedown="changeFontSize(3);" onmouseenter="onMouseEnter('btn_plus');" onmouseleave="onMouseLeave('btn_plus');">+</h1>
<h1 class="button" id="btn_minus" onmousedown="changeFontSize(-3);" onmouseenter="onMouseEnter('btn_minus');" onmouseleave="onMouseLeave('btn_minus');">-</h1>
</div>
<div id="result"></div>
</div>
<?php
require("dbconnect.php");
$id = 0;
$idvar = $_GET['id'];
if ($idvar != null) {
$sel = "SELECT text from content WHERE id = $idvar";
} else {
$sel = "SELECT text from content WHERE id = 0";
}
$result = mysqli_query($connection, $sel);
if (mysqli_num_rows($result) == 1) {
while ($r = mysqli_fetch_array($result)) {
$content = str_replace('"', '"', $r["text"]);
}
} else {
header("Location: index.html");
}
$result = mysqli_query($connection, "SELECT id FROM content ORDER BY id DESC LIMIT 1;");
if (mysqli_num_rows($result) > 0) {
$lastid = mysqli_fetch_row($result);
}
?>
<div id="hid" style="display:none;" data-info="<?php echo $content; ?>"></div>
<script type="text/javascript">
function post() {
if (!saved) {
var content = getContent();
$.post("note.php", {posttext:content}, function (data) {});
var lastid = "<?php echo $lastid[0]; ?>";
if (content != "") {
increment++;
lastid = parseInt(lastid) + increment;
alert("Note saved at:\nnotepad.com/index.html?id=" + lastid);
document.getElementById("btn_save").style.opacity = "0.3";
document.getElementById("btn_save").title = "Saved at:\nnotepad.com/index.html?id=" + lastid;
saved = true;
} else {
alert("Empty note");
}
}
}
</script>
<script type="text/javascript" src="script.js"></script>
</body>
JavaScript
var color_text;
var color_button_light;
var color_button_dark;
var color_background;
var color_hover;
var brightness;
var font_size = 32;
var saved = false;
var mouseObj;
function getContent() {
return textfield.document.body.innerHTML;
}
var increment;
function download() {
if (getContent() != "") {
var blob = new Blob([getContent()], {type: "text/plain;charset=utf-8"});
saveAs(blob, "note");
} else {
alert("Empty note");
}
}
function retrieveNote() {
var info = $("#hid").data("info");
textfield.document.body.innerHTML = info;
}
$(".textfield").contents().keyup(function(evnt) {
document.getElementById("btn_save").style.opacity = "1";
saved = false;
});
function enableEdit(theme) {
increment = 0;
// Themes
if (theme === 'dark') {
color_text = "#757575";
color_button_light = "#303030";
color_button_dark = "#646464";
color_hover = "#535353";
brightness = 125;
color_background = "#151515";
} else if (theme === 'hacker') {
color_text = "#00BB00";
color_button_light = "#202020";
color_button_dark = "#00BB00";
color_hover = "#009900";
brightness = 125;
color_background = "#000000";
} else if (theme === 'light') {
color_text = "#999";
color_button_light = "#BBBBBB";
color_button_dark = "#757575";
color_hover = "#646464";
brightness = 90;
color_background = "#EEEEEE";
}
// Background Color
document.body.style.backgroundColor = color_background;
document.getElementById("toolbar").backgroundColor = color_background;
// Textfield
textfield.document.designMode = 'on';
var tag = "<link href='https://fonts.googleapis.com/css?family=Open+Sans|Heebo|Lato' rel='stylesheet'><style>body{font-family:consolas, heebo;}</style>"
$(".textfield").contents().find("head").append(tag);
textfield.document.body.style.fontSize = font_size + "px";
textfield.document.body.style.color = color_text;
textfield.document.body.style.padding = "20px";
textfield.document.body.style.tabSize = "4";
textfield.document.body.style.whiteSpace = "pre-wrap";
textfield.document.body.style.wordWrap = "break-word";
textfield.document.body.style.lineHeight = "1.4";
textfield.focus();
// Buttons
document.getElementById("btn_bold").style.color = color_button_light;
document.getElementById("btn_ita").style.color = color_button_light;
document.getElementById("btn_und").style.color = color_button_light;
document.getElementById("btn_plus").style.color = color_button_dark;
document.getElementById("btn_minus").style.color = color_button_dark;
}
function handlePaste() {
textfield.document.addEventListener("paste", function(evnt) {
evnt.preventDefault();
var text = evnt.clipboardData.getData("text/plain");
document.getElementById("btn_save").style.opacity = "1";
saved = false;
textfield.document.execCommand("insertText", false, text);
});
}
function handleDrop() {
textfield.document.addEventListener("drop", function (evnt) {
evnt.preventDefault();
document.getElementById("btn_save").style.opacity = "1";
saved = false;
var text = evnt.dataTransfer.getData("text/plain");
textfield.document.execCommand("insertText", false, text);
});
}
var sources = ["theme_dark.png", "theme_light2.png", "theme_hacker.png"];
var sources2 = ["save_dark.png", "save.png", "save_hacker.png"];
var themes = ["dark", "light", "hacker"];
var iterator;
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function createCookie() {
if (getCookie("theme") == "") {
iterator = 0;
} else {
iterator = getCookie("theme");
}
document.getElementById('btn_theme').src = "img/" + sources[iterator];
document.getElementById('btn_save').src = "img/" + sources2[iterator];
enableEdit(themes[iterator]);
}
function changeTheme () {
createCookie();
if (iterator < sources.length-1) {
iterator++;
} else {
iterator = 0;
}
document.cookie = "theme=" + iterator + ";expires=Date.getTime() + 60 * 60 * 24 * 365 * 10;";
document.getElementById('btn_theme').src = "img/" + sources[iterator];
document.getElementById('btn_save').src = "img/" + sources2[iterator];
enableEdit(themes[iterator]);
onMouseEnter('btn_theme');
}
function bold() {
textfield.document.execCommand("bold", false, null);
}
function italic() {
textfield.document.execCommand("italic", false, null);
}
function underline() {
textfield.document.execCommand("underline", false, null);
}
function changeFontSize (amount) {
font_size += amount;
textfield.document.body.style.fontSize = font_size + "px";
}
function onMouseEnter(id) {
mouseObj = id;
if (mouseObj != 'btn_theme' && mouseObj != 'btn_save') {
document.getElementById(mouseObj).style.color = color_hover;
} else {
document.getElementById(mouseObj).style.filter = "brightness(" + brightness + "%)";
}
}
function onMouseLeave(id) {
mouseObj = null;
}
setInterval(function() {
var isBold = textfield.document.queryCommandState("Bold");
var isItalic = textfield.document.queryCommandState("Italic");
var isUnderlined = textfield.document.queryCommandState("Underline");
if (isBold == true && mouseObj == null) {
document.getElementById("btn_bold").style.color = color_button_dark;
} else if (isBold == false && mouseObj == null) {
document.getElementById("btn_bold").style.color = color_button_light;
}
if (isItalic == true && mouseObj == null) {
document.getElementById("btn_ita").style.color = color_button_dark;
} else if (isItalic == false && mouseObj == null) {
document.getElementById("btn_ita").style.color = color_button_light;
}
if (isUnderlined == true && mouseObj == null) {
document.getElementById("btn_und").style.color = color_button_dark;
} else if (isUnderlined == false && mouseObj == null) {
document.getElementById("btn_und").style.color = color_button_light;
}
if (mouseObj != 'btn_plus') {
document.getElementById("btn_plus").style.color = color_button_dark;
}
if (mouseObj != 'btn_minus') {
document.getElementById("btn_minus").style.color = color_button_dark;
}
if (mouseObj != 'btn_theme') {
document.getElementById("btn_theme").style.filter = "brightness(100%)";
}
if (mouseObj != 'btn_save') {
document.getElementById("btn_save").style.filter = "brightness(100%)";
}
},10);
PHP for saving the note
<?php
require("dbconnect.php");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL:" . mysqli_error();
}
if (isset($_POST["posttext"]) && !empty($_POST["posttext"])) {
$content = $_POST['posttext'];
$content = mysqli_real_escape_string($connection, $_POST["posttext"]);
$insert = "INSERT INTO content (text) VALUES ('$content')";
mysqli_query($connection, $insert);
$id = mysqli_insert_id($connection);
}
?>
you can use jquery ...
$(document).ready(function(){
$(".textfield").keyup(function() {
$("#btn_save").css("opacity", 1);
});
});
Okay, I fixed the problem. Apparently Firefox needs $(document).ready() to properly function for keypress events (haven't tested other events).
So your code should be:
$(document).ready(function(){
$(".textfield").contents().keyup(function(evnt) {
document.getElementById("btn_save").style.opacity = "1";
saved = false;
});
});
Instead of:
$(".textfield").contents().keyup(function(evnt) {
document.getElementById("btn_save").style.opacity = "1";
saved = false;
});
As I already said this is a problem that only occured in Firefox AFAIK.
This code works in Chrome, Firefox, Opera, Edge and Internet Explorer as of time of writing this answer.
I had a similar problem.
The mobile keyboards (in Firefox) don't emit keyup, keydown and keypress events.
So, I met the Text Composition events.
Something like this:
myInput = document.getElementById('myInput');
myInput.addEventListener('compositionupdate', (event) => {
setTimeout(() => {
applyFilter(event)
});
})
The setTimeOut was necessary to wait input value receipt the keyboard value before call my function.
I'm making a simple to-do list with WebSockets. The simple-todo is created but I only managed to create it with a click instead of the draggable option it should have. I changed the click to draggable but it didn't work. here is the code I used.
<!doctype html>
<html>
<head>
<title>Simple Todo</title>
</head>
<body>
TODO <input type="text" id="newTodoItem">
<ul id="itemsTodo">
</ul>
PROGRESS
<ul id="itemsProgress">
</ul>
DONE
<ul id="itemsDone">
</ul>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
/* statusses
0: todo
1: progress
2: done
*/
window.addEventListener('DOMContentLoaded', function () {
socket.emit("submitNewTodoItemMessage", {});
}, false);
// Checks if a new toto item is submitted
document.onkeyup = function (e) {
if (e.which === 13) {
var newTodoItem = {};
newTodoItem.id = parseFloat(new Date().getTime() + Math.random());
newTodoItem.status = 0;
newTodoItem.action = document.getElementById("newTodoItem").value;
if (newTodoItem !== '') {
socket.emit("submitNewTodoItemMessage", newTodoItem);
}
document.getElementById("newTodoItem").value = "";
}
};
socket.on("listOfAllTodoItemsMessage", function (listOfAllTodoItems) {
var itemsTodo = [], itemsProgress = [], itemsDone = [];
for (var i = 0; i < listOfAllTodoItems.length; i++) {
var item = listOfAllTodoItems[i];
var dragItem = "<li>" + item.action + " <span class='changeStatus' id='p_" + item.id + "'>^</span> <span class='changeStatus' id='n_" + item.id + "'>v</span></li>";
if (listOfAllTodoItems[i].status === 0) {
itemsTodo.push(dragItem);
} else if (listOfAllTodoItems[i].status === 1) {
itemsProgress.push(dragItem);
} else if (listOfAllTodoItems[i].status === 2) {
itemsDone.push(dragItem);
}
document.getElementById('itemsTodo').innerHTML = itemsTodo.join("");
document.getElementById('itemsProgress').innerHTML = itemsProgress.join("");
document.getElementById('itemsDone').innerHTML = itemsDone.join("");
}
$(".changeStatus").draggable(function (e) {
socket.emit("submitStatusUpdateTodoItemMessage", e.target.id);
});
$(".changeStatus").css('cursor', 'pointer');
});
</script>
</body>
</html>
the code snippet is now on the draggable state but it isn't working. I'm using jquery so the draggable function should work I guess.