[Solved] Move Towns Up / Down (Simple DOM Interaction)

  

3
Topic starter

You are given the following HTML code:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Move Up / Down</title>
<style>
select { width: 70px }
.block { display: inline-block; vertical-align: top }
#btnUp { display: block; margin-top: 18px }
#btnDown { display: block; margin-top: 10px }
</style>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
<div class="block">
<select id="towns" size="5">
<option>Sofia</option>
<option>Varna</option>
<option>Plovdiv</option>
<option>Ruse</option>
</select>
</div>
<div class="block">
<button id="btnUp" onclick="move(-1)">&uparrow;</button>
<button id="btnDown" onclick="move(+1)">&downarrow;</button>
</div>
<script>
function move(direction) {
// TODO: …
}
</script>
</body>
</html>

Your Task:
Write the missing JavaScript code to make the arrow buttons work as expected.

  • The [↑] button move the selected item up in the list. If no item is selected, it should do nothing.
  • The [↓] button should move the selected item down in the list. If no item is selected, it should do nothing.

Note: When an item is selected, it has the property selected.

Examples:

move town task 1

move town task 2

1 Answer
2

Here is the JavaScript function solution:

function move(direction) {
    let townToMove = $('#towns option:selected');
    if (direction == -1) {
        townToMove.insertBefore(townToMove.prev());
    }
    if (direction == +1) {
        townToMove.insertAfter(townToMove.next());
    }
}
Share: