You are given the following HTML code (with CSS styles), intended to draw a list of items:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>List Items: Up / Down</title> <style>button { margin: 3px 0 3px 8px }</style> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> </head> <body> <div id="main"></div> <script> function listBuilder(selector) { // TODO: return the list builder } </script> <script> $(function() { let builder = listBuilder("#main"); builder.createNewList(); builder.addItem("Sofia"); builder.addItem("Varna"); builder.addItem("Sofia <new>"); builder.addItem("Pleven"); }); </script> </body> </html>
The function listBuilder(selector) takes as input a DOM selector (string) and returns an object holding the
functions createNewList() and addItem(text).
createNewList clears the contents of the selector and appends an empty <ul> element to it:
addItem appends the specified string item into the previously created <ul> as a <li> element, along with two
buttons for moving the item:
Implement functionality to move each item in the list: when the buttons are clicked, the corresponding item should
move up or down, relative to the rest of the items (reordered in the DOM tree).
Your task is to write the body of the listBuilder(selector) function to get the above page working as
expected (see the screenshots). Do not modify the HTML code and CSS styles, just write the missing JS function.
Examples:
When the missing JS function listBuilder(selector) is implemented correctly, the page should look as follows
(after the page loading is completed):
Here is the solution:
function listBuilder(selector) { return { createNewList: function() { let ul = $("<ul>"); $(selector).empty(); $(selector).append(ul); }, addItem: function(text) { let li = $("<li>").text(text); li.append($("<button>Up</button>").click(this.buttonUp)); li.append($("<button>Down</button>").click(this.buttonDown)); $(selector + " ul").append(li); }, buttonUp: function() { let li = $(this).parent(); li.insertBefore(li.prev()); }, buttonDown: function() { let li = $(this).parent(); li.insertAfter(li.next()); } } }