Time for action – moving tasks within the list
While we're at it, let's add buttons to move tasks up and down in the list. For this we'll add some more code to the addTaskElement()
method. First we need to create move-up
and move-down
buttons, and then add them to the list element along with the delete
button.
function addTaskElement(taskName) { var $task = $("<li></li>"); var $delete = $("<button class='delete'>X</button>"); var $moveUp = $("<button class='move-up'>^</button>"); var $moveDown = $("<button class='move-up'>v</button>"); $task.append($delete) .append($moveUp) .append($moveDown) .append("<span class='task-name'>" + taskName + "</span>"); $("#task-list").append($task); $delete.click(function() { $task.remove(); }); $moveUp.click(function() { $task.insertBefore($task.prev()); }); $moveDown.click(function() { $task.insertAfter($task.next()); }); }
When the move up or move down button is clicked, it finds the previous or next task element using the prev()
and next()
methods. Then it uses the jQuery insertBefore()
and insertAfter()
methods to move the task element up or down in the tasklist.
What just happened?
We added buttons to each task element so that we can delete them or move them up and down in the order of the list. We learned how to use the jQuery remove()
, insertBefore()
, and insertAfter()
methods to modify the DOM.