What I want to happen is when I click the x button, the item will be removed when the slideUp() method is done. But with the code below, it will remove all the items at once and when I refresh the page, it has undefined on it.
HTML
<!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">
<title>Simple Todo List</title>
<!-- CSS -->
<link rel="stylesheet" href="styles.css">
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="index.js"></script>
</head>
<body>
<div class="container">
<h1>Things I've Gotta Get Done</h1>
<ul id="list-items">
<!-- Here's where out todo list items will go! -->
</ul>
<form class="add-items">
<input type="text" class="form-control" id="todo-list-item" placeholder="What do you need to do today?">
<button class="add" type="submit">Add to List</button>
</form>
</div>
</body>
</html>
CSS
.container {
margin: 0 auto;
min-width: 500px;
width: 45%;
text-align: left;
color: #3b3b3b;
font-weight: bold;
font-family: 'Helvetica', 'Arial', sans-serif;
}
form {
outline: 0;
height: 36px;
margin-top: 5%;
border: 3px solid #3b3b3b;
}
input[type="text"] {
outline: 0;
width: 55%;
height: 32px;
border: none;
font-size: 18px;
font-weight: normal;
padding-left: 10px;
}
.add {
outline: 0;
float: right;
width: 34%;
height: 36px;
color: #fff;
font-size: 18px;
border: none;
cursor: pointer;
background-color: #3b3b3b;
}
ul {
padding: 0;
text-align: left;
list-style: none;
}
hr {
border-bottom: 0;
margin: 15px 0;
}
input[type="checkbox"] {
width: 30px;
}
.remove {
float: right;
cursor: pointer;
}
.completed {
text-decoration: line-through;
}
JS
$(document).ready(function () {
$("#list-items").html(localStorage.getItem("listItems"));
$(".add-items").submit(function(event) {
event.preventDefault();
var item = $.trim( $("#todo-list-item").val() );
if (item.length > 0) {
if (item === "exercise" || item === "EXERCISE" || item === "Exercise"){
$("#list-items").append("<li><input class='checkbox' type='checkbox' /><img src='assets/images/exercise.gif' alt='exercise'><a class='remove'>x</a><hr></li>");
localStorage.setItem("listItems", $("#list-items").html());
$("#todo-list-item").val("");
} else {
$("#list-items").append("<li><input class='checkbox' type='checkbox' />" + item + "<a class='remove'>x</a><hr></li>");
localStorage.setItem("listItems", $("#list-items").html());
$("#todo-list-item").val("");
}
}
});
$(document).on("change", ".checkbox", function() {
if ($(this).attr("checked")) {
$(this).removeAttr("checked");
} else {
$(this).attr("checked", "checked");
}
$(this).parent().toggleClass("completed");
localStorage.setItem("listItems", $("#list-items").html());
});
$(document).on("click", ".remove", function() {
$(this).parent().slideUp("slow", function() {
$(this).parent().remove();
localStorage.setItem("listItems", $("#list-items").html());
});
});
});
Since you are calling slideUp() on the li element, Inside the callback, this refers to the the li element, so when you say $(this).parent().remove() it is removing the ul element that is why all the elements are removed.
So you can remove the element referred by this, no need to call .parent()
$(document).on("click", ".remove", function() {
$(this).parent().slideUp("slow", function() {
$(this).remove();
localStorage.setItem("listItems", $("#list-items").html());
});
});
Related
I'm a new javascript, i have heard that declaring global variables it's pretty much bad idea in javascript, we have to less or avoid as much as we can.
I have found page https://www.w3.org/wiki/JavaScript_best_practices#Avoid_globals and i saw module pattern it seems a good way to go.
So, i've been practicing about toggle function my first code it works fine
function toggle() {
var mainTopics = document.querySelector("#maintopics"); // target the li
mainTopics.addEventListener("click", function (e) { // passed "e" to get the event
e.preventDefault(); // prevent anchor to navigate
mainTopics.classList.toggle("show"); // changed to toggle for the
// the purpose of this demo
});
}
toggle();
body {
margin: 0;
}
li, a{
text-decoration: none;
list-style-type: none;
text-decoration-line: none;
color: black;
}
/*main-menu*/
#mainmenu {
position: relative;
}
#mainmenu ul {
margin: 0;
padding: 0;
}
#mainmenu li {
display: inline-block;
}
#mainmenu a {
display: block;
width: 100px;
padding: 10px;
border: 1px solid;
text-align: center;
}
/*sub-topics*/
#subtopics {
position: absolute;
display: none;
margin-top: 10px;
width: 100%;
left: 0;
}
#maintopics.show #subtopics {
display: block;
}
#subtopics ul {
margin: 0;
padding: 0;
}
#subtopics li {
display: block;
}
#subTopics a {
text-align: left;
}
/*columns*/
#column1, #column2, #column3 {
position: relative;
float: left;
left: 125px;
margin: 0px 5px 0px 0px;
}
/*hover underline*/
#mainmenu li:hover {
text-decoration: underline;
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" type="text/css" href="index2.css" />
</head>
<body>
<div id="mainmenu">
<ul>
<li>Logo</li>
<li>Home</li>
<li id="maintopics">Topics
<div id="subtopics">
<div id="column1" class="columns">
<ul>
<li>example1</li>
<li>example2</li>
<li>example3</li>
</ul>
</div>
</div>
</li>
</ul>
</div>
<script src="index2.js"></script>
</body>
</html>
I changed code javascript to module pattern.However it didn't work, im not sure if my code is wrong or there is some important rule that i don't know.
If anyone would like to give me some advices i will appreciate it thank you very much.
var toggle = (function() {
var mainTopics = document.getElementById("maintopics");
mainTopics.addEventListener("click", function(e) {
e.preventDefault();
mainTopics.classList.toggle("show");
});
return {
toggle()
}
})();
Hi, everyone i suddenly found the solution for my case. i just need to specific the function that i want to return to object again for example in my case return toggle function it would be toggle: toggle()
var toggle = (function () {
var mainTopics = document.getElementById("maintopics");
mainTopics.addEventListener("click", function (e) {
e.preventDefault();
mainTopics.classList.toggle("show");
});
return {
toggle: toggle()
}
})();
So if I want to save all the To-Do items in Local storage and retrieve when I restart the computer or refresh the page all the items come up on the page in their original order.?
//check of spec
$("ol").on("click", "li", function(){
$(this).toggleClass("completed");
});
//click on X to delete To-DO
$("ol").on("click", "span", function(event){
$(this).parent().fadeOut(500,function(){
$(this).remove();
});
event.stopPropagation();
});
$("input[type='text'").keypress(function(event){
if(event.which === 13) {
//grabbing the text typed
var todoText = $(this).val();
$(this).val("");
//create a new LI and add to UL
$("ol").append("<li><span><i class='fa fa-trash'></i></span> " + todoText +"</li>")
}
});
$(".fa-plus").click(function(){
$("input[type='text'").fadeToggle();
});
h1 {
background: #2980b9;
color: white;
margin: 0;
padding: 10px 15px;
text-transform: uppercase;
font-size: 24px;
font-weight: normal;
}
iframe {
float: left;
}
ol {
/* THE BULLET POINTS
list-style: none;
*/
margin: 0;
padding: 0;
font-size: 18px;
}
body {
background-color: rgb(13, 168, 108);
}
li {
background: #fff;
height: 30px;
line-height: 30px;
color: #666;
}
li:nth-child(2n){
background: #d3d3d3;
}
span {
height: 30px;
width: 0px;
margin-right: 20px;
text-align: center;
color:white;
display: inline-block;
transition: 0.2s linear;
opacity:0;
background: #e74c3c
}
li:hover span {
width: 30px;
opacity: 1.0;
}
input {
font-size: 18px;
width: 100%;
padding: 13px 13px 13px 20px;
box-sizing: border-box;
border: 3px solid rgba(0,0,0,0);
color: #2980b9;
background-color: #e4e4e4;
}
input:focus {
background: white;
border: 3px solid green;
/*OUTLINE OF INPUT BOX
outlin: none; */
}
.fa-plus {
float: right;
}
#container {
width: 360px;
margin: 60px auto;
background: #d3d3d3;
box-shadow: 0 0 3px rgba(0,0,0,0.1);
}
.completed {
color: red;
text-decoration: line-through;
}
<!DOCTYPE html>
<html>
<head>
<title>ToDo List</title>
<link rel="stylesheet" type="text/css" href="utd.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
} );
</script>
</head>
<body>
<iframe src="http://free.timeanddate.com/clock/i5zr5d5i/n1991/szw110/szh110/hoc09f/hbw0/hfc09f/cf100/hnce1ead6/fas30/fdi66/mqc000/mql15/mqw4/mqd98/mhc000/mhl15/mhw4/mhd98/mmc000/mml10/mmw1/mmd98/hhc00f/hhs2/hmcf00/hms2/hsv0" frameborder="0" width="110" height="110"></iframe>
<div id="container">
<h1>To-do List <i class="fa fa-plus"></i></h1>
<form id="task-list">
<input type="text" placeholder="Add a To-Do" id="task">
</form>
<ol id="sortable">
<li><span><i class="fa fa-trash"></i></span> EXAMPLE</li>
</ol>
</div>
<script type="text/javascript" src="Utd.js"></script>
</body>
</html>
Happy Holidays!
Your coding wishes are granted. This is a gift, to you, and you will have to be a good person and post better examples and remember that people are not here to write code for you.
There was a LOT of stuff lacking from your example.
Add items to a list
Update local storage when items are added to a list
Allow list to be sorted
Update local storage when list is updated
Allow task items to be marked completed
Update local storage when items are completed
Allow task items to be deleted
Update local storage when tasks are deleted
Load locally stored tasks
I think that covers everything you wanted this script to do. Is it becoming more clear now?
Working Example: https://jsfiddle.net/Twisty/ae6oLr47/12/
HTML
<iframe src="https://free.timeanddate.com/clock/i5zr5d5i/n1991/szw110/szh110/hoc09f/hbw0/hfc09f/cf100/hnce1ead6/fas30/fdi66/mqc000/mql15/mqw4/mqd98/mhc000/mhl15/mhw4/mhd98/mmc000/mml10/mmw1/mmd98/hhc00f/hhs2/hmcf00/hms2/hsv0" frameborder="0" width="110"
height="110"></iframe>
<div id="container">
<h1>To-do List <i class="fa fa-plus"></i></h1>
<form id="task-list">
<input type="text" placeholder="Add a To-Do" id="task">
<button type="submit"></button>
</form>
<ol id="sortable">
<li id="task-EXAMPLE"><span><i class="fa fa-trash"></i></span>
<label>EXAMPLE</label>
</li>
</ol>
</div>
The first time this loads, there will be no storage, so we can read an examples from the HTML. As you will see, once you make an update, this will no longer be the case.
Q: Why the <button>?
A: <form> likes to have a submit button. It does not need it, yet having it will help a lot in ways I do not want to go into for this question.
JavaScript
$(function() {
$("#sortable").on("click", function(event) {
console.log(event.target);
var $thatItem = $(event.target).parents("li");
switch (event.target.nodeName) {
case "SPAN":
case "I":
$thatItem.fadeOut(500, function() {
$thatItem.remove();
$("#sortable").sortable("refresh");
});
break;
case "LABEL":
$thatItem.toggleClass("completed");
break;
}
setTimeout(function() {
updateLocalStorage($("#sortable"));
}, 500);
event.stopPropagation();
});
$("#task-list").submit(function(event) {
event.preventDefault();
// Grabbing the text typed
var todoText = $("#task").val();
addListItem($("#sortable"), todoText, false);
// Clear the text field
$("#task").val("");
updateLocalStorage($("#sortable"));
});
$(".fa-plus").click(function() {
$("#task-list").fadeToggle();
});
$("#sortable").sortable({
update: function(e, ui) {
updateLocalStorage($(this));
}
}).disableSelection();
function addListItem($t, s, c) {
//create a new LI
var $li = $("<li>", {
id: "task-" + s.replace(" ", "_")
});
if (c) {
$li.addClass("completed");
}
var $wrap = $("<span>").appendTo($li);
$wrap.append($("<i>", {
class: "fa fa-trash"
}));
$li.append($("<label>").html(s));
$li.appendTo($t);
$t.sortable("refresh");
}
function updateLocalStorage($list) {
var tasks = {};
$list.find("li").each(function(ind, elem) {
var task = $(elem).text().trim();
var completed = $(elem).hasClass("completed");
tasks[task] = completed;
if (typeof(Storage) !== "undefined") {
localStorage.setItem("tasks", JSON.stringify(tasks));
}
});
}
if (typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
if (localStorage.getItem("tasks") !== "undefined") {
var localTasks = JSON.parse(localStorage.getItem("tasks"));
// Grab stored tasks
$("#sortable").find("li").remove();
$.each(localTasks, function(task, status) {
addListItem($("#sortable"), task, status);
});
}
} else {
// Sorry! No Web Storage support..
}
});
You might see that there is very little of your original code left in here. There was just a lot of places to improve the code. I will discuss a bit briefly.
Click Events
Since we're basically listening for click events on the same parent, but want to do different things when specific elements are clicked, that are going to be dynamically created, we can make use of the event.target from the click event. If it's the span or the i that's clicked, we do one thing, if it's the label, another.
The setTimeout is just a way to create a delay in the operations from switch to updating. Otherwise the update will execute almost on top of the switch and will not see the changes to the list, this record no changes.
Submit Event
When you hit Enter or Return you're essentially submitting the form. Part of the reason to add a submit button. Instead of catching the keypress and trying to prevent this, why not just use the submit event to our advantage. This method will help on mobile browsers and such.
Sortable Update Event
When the list is sorted, and updated, we need to update that order in the local storage. Now is the time to do that.
Functions
I think these are pretty clear. You have an operation you will repeat many times, write a function.
Get Item
The last bit of code will load when the page is all ready. It will check for localStorage and check if there are tasks stored within. It will then populate the list with them.
Q: What's with the JSON.stringify()?
A: Yes, you can store stuff locally... only as String. This creates a string version of our object for storage.
Comment if you have other questions.
//check of spec
$("ol").on("click", "li", function(){
$(this).toggleClass("completed");
});
//click on X to delete To-DO
$("ol").on("click", "span", function(event){
$(this).parent().fadeOut(500,function(){
$(this).remove();
});
event.stopPropagation();
});
$("input[type='text'").keypress(function(event){
if(event.which === 13) {
//grabbing the text typed
var todoText = $(this).val();
$(this).val("");
//create a new LI and add to UL
$("ol").append("<li><span><i class='fa fa-trash'></i></span> " + todoText +"</li>")
}
});
$(".fa-plus").click(function(){
$("input[type='text'").fadeToggle();
});
h1 {
background: #2980b9;
color: white;
margin: 0;
padding: 10px 15px;
text-transform: uppercase;
font-size: 24px;
font-weight: normal;
}
iframe {
float: left;
}
ol {
/* THE BULLET POINTS
list-style: none;
*/
margin: 0;
padding: 0;
font-size: 18px;
}
body {
background-color: rgb(13, 168, 108);
}
li {
background: #fff;
height: 30px;
line-height: 30px;
color: #666;
}
li:nth-child(2n){
background: #d3d3d3;
}
span {
height: 30px;
width: 0px;
margin-right: 20px;
text-align: center;
color:white;
display: inline-block;
transition: 0.2s linear;
opacity:0;
background: #e74c3c
}
li:hover span {
width: 30px;
opacity: 1.0;
}
input {
font-size: 18px;
width: 100%;
padding: 13px 13px 13px 20px;
box-sizing: border-box;
border: 3px solid rgba(0,0,0,0);
color: #2980b9;
background-color: #e4e4e4;
}
input:focus {
background: white;
border: 3px solid green;
/*OUTLINE OF INPUT BOX
outlin: none; */
}
.fa-plus {
float: right;
}
#container {
width: 360px;
margin: 60px auto;
background: #d3d3d3;
box-shadow: 0 0 3px rgba(0,0,0,0.1);
}
.completed {
color: red;
text-decoration: line-through;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>ToDo List</title>
<link rel="stylesheet" type="text/css" href="utd.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
} );
</script>
</head>
<body>
<iframe src="http://free.timeanddate.com/clock/i5zr5d5i/n1991/szw110/szh110/hoc09f/hbw0/hfc09f/cf100/hnce1ead6/fas30/fdi66/mqc000/mql15/mqw4/mqd98/mhc000/mhl15/mhw4/mhd98/mmc000/mml10/mmw1/mmd98/hhc00f/hhs2/hmcf00/hms2/hsv0" frameborder="0" width="110" height="110"></iframe>
<div id="container">
<h1>To-do List <i class="fa fa-plus"></i></h1>
<form id="task-list">
<input type="text" placeholder="Add a To-Do" id="task">
</form>
<ol id="sortable">
<li><span><i class="fa fa-trash"></i></span> EXAMPLE</li>
</ol>
</div>
<script type="text/javascript" src="Utd.js"></script>
</body>
</html>
//check of spec
$("ol").on("click", "li", function(){
$(this).toggleClass("completed");
});
//click on X to delete To-DO
$("ol").on("click", "span", function(event){
$(this).parent().fadeOut(500,function(){
// $(this).remove();
});
//event.stopPropagation();
});
$("input[type='text'").keypress(function(event){
if(event.which === 13) {
//grabbing the text typed
var todoText = $(this).val();
$(this).val("");
//create a new LI and add to UL
$("ol").append("<li><span><i class='fa fa-trash'></i></span> " + todoText +"</li>")
}
});
$(".fa-plus").click(function(){
$("input[type='text'").fadeToggle();
});
h1 {
background: #2980b9;
color: white;
margin: 0;
padding: 10px 15px;
text-transform: uppercase;
font-size: 24px;
font-weight: normal;
}
iframe {
float: left;
}
ol {
/* THE BULLET POINTS
list-style: none;
*/
margin: 0;
padding: 0;
font-size: 18px;
}
body {
background-color: rgb(13, 168, 108);
}
li {
background: #fff;
height: 30px;
line-height: 30px;
color: #666;
}
li:nth-child(2n){
background: #d3d3d3;
}
span {
height: 30px;
width: 0px;
margin-right: 20px;
text-align: center;
color:white;
display: inline-block;
transition: 0.2s linear;
opacity:0;
background: #e74c3c
}
li:hover span {
width: 30px;
opacity: 1.0;
}
input {
font-size: 18px;
width: 100%;
padding: 13px 13px 13px 20px;
box-sizing: border-box;
border: 3px solid rgba(0,0,0,0);
color: #2980b9;
background-color: #e4e4e4;
}
input:focus {
background: white;
border: 3px solid green;
/*OUTLINE OF INPUT BOX
outlin: none; */
}
.fa-plus {
float: right;
}
#container {
width: 360px;
margin: 60px auto;
background: #d3d3d3;
box-shadow: 0 0 3px rgba(0,0,0,0.1);
}
.completed {
color: red;
text-decoration: line-through;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>ToDo List</title>
<link rel="stylesheet" type="text/css" href="utd.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
} );
</script>
</head>
<body>
<div id="container">
<h1>To-do List <i class="fa fa-plus"></i></h1>
<input type="text" placeholder="Add a To-Do" id="task">
<ol id="sortable">
<li><span><i class="fa fa-trash"></i></span> EXAMPLE</li>
</ol>
</div>
<script type="text/javascript" src="Utd.js"></script>
</body>
</html>
After making edits in browser, simply save the page as HTML with different file name. Your selected values will be saved.
I'm trying to add a class to dynamically generated <li> elements, but it has a very strange behavior. With a single <li> it works perfectly, but after adding an another element, the class attribute will be added without value. After adding the third <li> it will work again (basically it works only if the number of the <li> elements is odd).
var JSTasker = {
updateTaskCounter: function() {
var taskCount = $('div#tasks ul').children().not('li.completed').size();
$('span#task_counter').text(taskCount);
},
sortTasks: function() {
var taskList = $('div#tasks ul');
var allCompleted = $(taskList).children('.completed');
allCompleted.detach();
allCompleted.appendTo(taskList);
},
updatePage: function() {
this.updateTaskCounter();
this.sortTasks();
}
};
$(document).ready(function() {
$('input#task_text').focus();
$('form#add_task').on('submit', function(event) {
event.preventDefault();
var taskText = $('input#task_text').val();
var taskItem = "<li>" + taskText + "</li>";
$('div#tasks ul').append(taskItem);
$('input#task_text').val(null);
JSTasker.updatePage();
$('div#tasks ul').on('click', 'li', function(event) {
event.preventDefault();
$(this).toggleClass('completed');
JSTasker.updatePage();
});
});
});
h1,
h2,
ul,
li {
margin: 0px;
padding: 0px;
}
html {
background: #333;
font-family: 'Gill Sans Light', 'Helvetica', 'Arial';
font-size: 90%;
}
body {
width: 400px;
margin: 10px auto;
border: 1px solid #EEE;
background: #F6F6F6;
padding: 10px 20px;
}
fieldset {
border: 2px solid #CCC;
padding: 10px;
margin: 10px 0px 0px 0px;
}
input[type=text] {
width: 300px;
padding-right: 20px;
}
input[type=submit] {} #tasks {
margin: 20px 0px 0px 0px;
}
h2 {
margin-bottom: 10px;
}
h2 span#task_counter {
font-size: 80%;
color: #999;
}
#tasks ul {
list-style-type: none;
}
#tasks ul li {
padding: 6px 10px 3px 20px;
height: 1.6em;
}
#tasks ul li:hover {
background: #FFF8DC;
text-decoration: underline;
}
#tasks ul li.completed {
background: url('icons/accept.png') no-repeat 0px 5px;
text-decoration: line-through;
color: #999;
}
.trash {
float: right;
padding: 2px;
}
.trash:hover {
background: #F99;
cursor: pointer;
}
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>Tasker</title>
<link rel='stylesheet' type="text/css" href='JSTasker.css' />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script src="JSTasker.js"></script>
</head>
<body>
<h1>JSTasker</h1>
<form id='add_task'>
<fieldset>
<legend>Add a Task</legend>
<input type='text' name='task_text' id='task_text' />
<input type='submit' name='add_button' value='Add' />
</fieldset>
</form>
<div id='tasks'>
<h2>Your Tasks <span id='task_counter'></span></h2>
<ul>
</ul>
</div>
</body>
</html>
This is the problematic part:
$('div#tasks ul').on('click', 'li', function(event) {
event.preventDefault();
$(this).toggleClass('completed');
JSTasker.updatePage();
});
The application is based on this tutorial.
add onclick handler outside form submit, right now your onclick event is being initialized every time you submit the form. but $().on() is for dynamic binding and you need to call it only once
$(document).ready(function() {
$('input#task_text').focus();
$('form#add_task').on('submit', function(event) {
event.preventDefault();
var taskText = $('input#task_text').val();
var taskItem = "<li>" + taskText + "</li>";
$('div#tasks ul').append(taskItem);
$('input#task_text').val("");
JSTasker.updatePage();
});
$('div#tasks ul').on('click', "li", function(event) {
event.preventDefault();
$(this).toggleClass('completed');
JSTasker.updatePage();
});
});
You are binding click event to li for every click of add button. Take this code out and it will work. It was working for odd number of elements because it will bind event odd times. lets say you added 3 lis and hence it will call click event 3 times. first time add class, then remove and then add class again. But it will fail for even number of lis as it will first add class and then remove it.
var JSTasker = {
updateTaskCounter: function() {
var taskCount = $('div#tasks ul').children().not('li.completed').size();
$('span#task_counter').text(taskCount);
},
sortTasks: function() {
var taskList = $('div#tasks ul');
var allCompleted = $(taskList).children('.completed');
allCompleted.detach();
allCompleted.appendTo(taskList);
},
updatePage: function() {
this.updateTaskCounter();
this.sortTasks();
}
};
$(document).ready(function() {
$('input#task_text').focus();
$('form#add_task').on('submit', function(event) {
event.preventDefault();
var taskText = $('input#task_text').val();
var taskItem = "<li>" + taskText + "</li>";
$('div#tasks ul').append(taskItem);
$('input#task_text').val(null);
JSTasker.updatePage();
});
$('div#tasks ul').on('click', 'li', function(event) {
event.preventDefault();
$(this).toggleClass('completed');
JSTasker.updatePage();
});
});
h1,
h2,
ul,
li {
margin: 0px;
padding: 0px;
}
html {
background: #333;
font-family: 'Gill Sans Light', 'Helvetica', 'Arial';
font-size: 90%;
}
body {
width: 400px;
margin: 10px auto;
border: 1px solid #EEE;
background: #F6F6F6;
padding: 10px 20px;
}
fieldset {
border: 2px solid #CCC;
padding: 10px;
margin: 10px 0px 0px 0px;
}
input[type=text] {
width: 300px;
padding-right: 20px;
}
input[type=submit] {} #tasks {
margin: 20px 0px 0px 0px;
}
h2 {
margin-bottom: 10px;
}
h2 span#task_counter {
font-size: 80%;
color: #999;
}
#tasks ul {
list-style-type: none;
}
#tasks ul li {
padding: 6px 10px 3px 20px;
height: 1.6em;
}
#tasks ul li:hover {
background: #FFF8DC;
text-decoration: underline;
}
#tasks ul li.completed {
background: url('icons/accept.png') no-repeat 0px 5px;
text-decoration: line-through;
color: #999;
}
.trash {
float: right;
padding: 2px;
}
.trash:hover {
background: #F99;
cursor: pointer;
}
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>Tasker</title>
<link rel='stylesheet' type="text/css" href='JSTasker.css' />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script src="JSTasker.js"></script>
</head>
<body>
<h1>JSTasker</h1>
<form id='add_task'>
<fieldset>
<legend>Add a Task</legend>
<input type='text' name='task_text' id='task_text' />
<input type='submit' name='add_button' value='Add' />
</fieldset>
</form>
<div id='tasks'>
<h2>Your Tasks <span id='task_counter'></span></h2>
<ul>
</ul>
</div>
</body>
</html>
Your code works with only odd numbers of tasks because you add a new click handler to every <li> each time you submit the form. That means that when you have two <li>s, you call toggleClass twice, and get nowhere. You can confirm this by adding alert("hi") to your current code after the toggleClass call.
When i click on the text from the OL "firstlist" i want the exact text to be moved to the other OL "seclist". It is not necessary to remove that text from the firstlist. The thing i lack is how to get the selected element from the firstlist. I think others will work if we pass the selected item from the first list to "var text" in click function. Please help me out. Thanks in advance.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">
<script type = "text/javascript" src = "js/jquery.js"></script>
<script type = "text/javascript" src = "js/jquery_ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<style>
#feedback { font-size: 1.4em; }
#firstlist .ui-selecting { background: #FECA40; }
#firstlist .ui-selected { background: #F39814; color: white; }
#firstlist { list-style-type: none; margin: 0; padding: 0; width: 20%; }
#firstlist li { margin: 3px; padding: 0.4em; font-size: 1.4em; height: 18px; }
#firstlist li:hover img { display: block; }
#seclist .ui-selecting { background: #FECA40; }
#seclist .ui-selected { background: #F39814; color: white; }
#seclist { list-style-type: none; margin: 0; padding: 0; width: 20%; }
#seclist li { margin: 3px; padding: 0.4em; font-size: 1.4em; height: 18px; }
img
{
position:relative;
left:232px;
top:-25px;
display:none;
}
</style>
</head>
<body>
<table id="myTable">
<td>
<tr>
<ol id="firstlist">
<li>Item 1 <img src="next.jpg" id="next1"></li>
<li>Item 2 <img src="next.jpg" id="next2"></li>
<li>Item 3 <img src="next.jpg" id="next3"></li>
<li>Item 4 <img src="next.jpg" id="next4"></li>
<li>Item 5 <img src="next.jpg" id="next5"></li>
</ol>
</tr>
<tr>
<ul class = "seclist" id = "seclist">
</ul>
</tr>
</td>
</table>
<!--
<input type="test" id="inputName" />
<button id="btnName">Click me!</button>
-->
<script language="javascript">
//function to display the immage
function show(id,disp) {
if (disp == true) {
id.style.display = "block";
}
if (disp == false) {
id.style.display = "none";
}
}
</script>
<script>
$(function(){
$( "#firstlist" ).selectable();
});
$(function() {
$( "#seclist" ).selectable();
});
$('#firstlist').click(function(){
//alert('To check it works');
//var text = $('#inputName').val();
//if(text.length){
// $('<li />', {html: text}).appendTo('ul.seclist')
//}
});
</script>
</body>
</html>
http://jsfiddle.net/WfKbk/1/
you can just re-append item
$('#firstlist li').click(function () {
$("#seclist").append($(this));
});
JSFiddle for copying the text.
$('#firstlist').on( 'click', 'li' , function(){
var $this = $(this),
text = $this.text();
$("#seclist").append('<li>' + text + '</li>');
})
I using jQuery-UI sortable which works fine. The problem that I am having is that the message "New order saved!" or "Save failed" is not displaying in the < p > area. The function is either not executing or something.
Below is the code for the .aspx page
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<link href="jQuery/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="jQuery/jquery.min.js" type="text/javascript"></script>
<script src="jQuery/jquery-ui.min.js" type="text/javascript"></script>
<script src="jQuery/json2.js" type="text/javascript"></script>
<script src="jQuery/jquery-ui-i18n.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#sortable").sortable({ placeholder: "vacant" });
$("#sortable").disableSelection();
$("#sortable input[type=text]").width($("#sortable img").width() - 10);
$("#sortable label").mouseover(function () {
$(this).parent().children("input[type=text]").show().val($(this).html());
$(this).hide();
});
$("#sortable input[type=text]").mouseout(function () {
$(this).parent().children("label").show().html($(this).val());
$(this).hide();
});
$(".ContainerDiv").hover(
function () {
$(this).find(".deleteClass").show();
},
function () {
$(this).find(".deleteClass").hide();
});
$(".deleteClass").click(function () {
$(this).closest("li").remove();
});
$("#orderPhoto").click(function () {
var photos = $.map($("li.ui-state-default"), function (item, index) {
var imgDetail = new Object();
imgDetail.Id = $(item).find("img").attr("id");
imgDetail.Caption = $(item).find("label").html();
imgDetail.Order = index + 1;
return imgDetail;
});
var jsonPhotos = JSON.stringify(photos);
$.ajax({
type: "POST",
contentType: "application/json",
data: "{photos:" + jsonPhotos + "}",
url: "WebService.asmx/updatePhoto",
dataType: "json",
success: function (data) {
if (data.d === "saved") {
$("<p>").text("New order saved!")
.addClass("success").appendTo("#left");
} else {
$("<p>").text("Save failed")
.addClass("failure").appendTo("#left");
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
debugger;
}
});
});
});
</script>
<style type="text/css">
#sortable
{
list-style-type: none;
margin: 0;
padding: 0;
}
#sortable li
{
position: relative;
margin: 3px 3px 3px 0;
padding: 1px;
float: left;
text-align: left;
}
#sortable .vacant
{
border: 3px dotted #66d164;
width: 150px;
height: 175px;
background-color: #fff;
}
#outerWrap
{
width: 1004px;
margin: auto;
position: relative;
background-color: #eee;
border: 1px solid #999;
}
#outerWrap:after
{
content: ".";
display: block;
visibility: hidden;
clear: both;
}
#left
{
width: 218px;
float: left;
}
#images
{
margin: 0;
padding: 0;
float: left;
width: 786px;
}
h1
{
font: italic normal 24px Georgia, Serif;
text-align: center;
margin: 10px 0;
}
p
{
margin: 0;
font: 12px Arial, Sans-serif;
padding: 0 10px;
}
.deleteClass
{
/* PhotoListItem is relative so relative to it */
position: absolute;
top: 1px;
right: 3px;
background: black;
color: Red;
font-weight: bold;
font-size: 12px;
padding: 5px;
opacity: 0.60;
filter: alpha(opacity="60");
margin-top: 3px;
display: none;
cursor: pointer;
}
.deleteClass:hover
{
opacity: 0.90;
filter: alpha(opacity="90");
}
.image_resize
{
width: 150px;
height: 150px;
border: 0;
}
.success, .failure
{
margin: 0 0 0 10px;
padding: 4px 0 4px 26px;
position: absolute;
bottom: 18px;
font-weight: bold;
}
.success
{
background: url('../img/tick.png') no-repeat 0 1px;
color: #12751c;
}
.failure
{
background: url('../img/cross.png') no-repeat 0 0;
color: #861b16;
}
</style>
</head>
<body>
<form id="form2" runat="server">
<div id="outerWrap">
<div id="left">
<h1>
Image Organiser</h1>
<p>
Re-order the images by dragging an image to a new location. Your changes will be
saved automatically.</p>
</div>
<div id="images">
<asp:ListView ID="ListViewAlbumPhotoView" runat="server" GroupItemCount="15">
<LayoutTemplate>
<ul id="sortable">
<li id="groupPlaceholder" runat="server">1</li>
</ul>
</LayoutTemplate>
<GroupTemplate>
<tr id="itemPlaceholderContainer" runat="server">
<td id="itemPlaceholder" runat="server">
</td>
</tr>
</GroupTemplate>
<ItemTemplate>
<li class="ui-state-default">
<div class="ContainerDiv">
<div class="deleteClass">
X</div>
<img id='<%#Eval("photo_id")%>' src='<%# "uploads/" + Eval("photo_file_name")%>'
alt="" class="image_resize" />
<div style="height: 25px; margin-top: 3px">
<label>
<%# Eval("photo_title")%></label>
<input type="text" style="display: none" />
</div>
</div>
</li>
</ItemTemplate>
</asp:ListView>
<input type="button" id="orderPhoto" value="Save change" />
</div>
</div>
</form>
</body>
</html>
The problem is with
success: function (data) {
if (data.d === "saved") {
$("<p>").text("New order saved!")
.addClass("success").appendTo("#left");
} else {
$("<p>").text("Save failed")
.addClass("failure").appendTo("#left");
}
},
Could someone tell me how to message display in the < p > area?
Any help would be greatly appreciated.
Thanks
Be sure to add the closing tag as well:
$("<p></p>").text("Save failed").addClass("failure").appendTo("#left");
Update: Also make sure the success function is even being called--Use a tool like Firebug (Firefox) or Developer tools in Chrome or Safari to inspect net traffic to see what the result of your call is.
You don't use brackets around the p inside the jquery function
try $('p')
Are you trying to update the single paragraph element already there? Or do you want to insert
a new paragraph element every single time. If you want the second case, just combine everything at once.
if (data.d === "saved") {
$("<p class='success'>New order saved!</p>").appendTo("#left");
}
else {
$("<p class='failure'>Save failed!</p>").appendTo("#left");
}