Why does the swapping function is not working with new elements?

Viewed 19

I am creting a todo list having a default list and then adding new todos to it. It is possible do drag and drop the elements to rearrenge them. That swapping function works perfectly with the default list but does not work with the new ones added. I am not sure why it is not working as it gets undefined

This is the code:

const draggableElement = document.getElementById('draggable-list');

const TodoList = [
  'Complete online Javascript course',
  'Jog around the park 3x',
  '10 minutes meditation',
  'Read for 2hr',
  'Pick up the groceries',
  'Complete todo list',
];

//store items
const listItems = [];
let dragStartIndex;

createList();

//insert items into dom
function createList() {
  [...TodoList] //copies array
  .forEach((todo, index) => {
    const listItem = document.createElement('li');
    // listItem.setAttribute('id','draggable');
    listItem.setAttribute('data-index', index + 1);
    listItem.setAttribute('className', 'draggable');
    listItem.innerHTML = `
            <label for="showRatings${index + 1}" class="circle${index + 1} check">
            <input type="checkbox" class="checkbox input" name="showRatings${index + 1}" id="showRatings${index + 1}">
            </label>
            <span class="number">${index + 1+"-"}</span>
            <div class="draggable" draggable="true">
            <p class="todo-name" >${todo}</p>
            </div>`;
    listItems.push(listItem);
    draggableElement.appendChild(listItem);
  });
}
addEventListeners();

function dragStart() {
  dragStartIndex = +this.closest('li').getAttribute('data-index');
  // console.log('index',dragStartIndex)
}

function dragEnter() {
  this.classList.add('over');
}

function dragLeave() {
  this.classList.remove('over');
}

function dragOver(e) {
  e.preventDefault();
  // console.log('over')
}

///////////////////////////////////////////////////////

function dragDrop() {
  const dragEndIndex = +this.getAttribute('data-index');
  swapItems(dragStartIndex - 1, dragEndIndex - 1);
  this.classList.remove('over');
}


function swapItems(fromIndex, toIndex) {
  const itemOne = listItems[fromIndex].querySelector('.draggable');
  const itemTwo = listItems[toIndex].querySelector('.draggable');

  // console.log(itemOne,itemTwo);
  // console.log(listItems[fromIndex])
  listItems[fromIndex].appendChild(itemTwo);
  listItems[toIndex].appendChild(itemOne);
}

function addEventListeners() {
  const draggables = document.querySelectorAll('.draggable');
  const dragListItems = document.querySelectorAll('.draggable-list li');

  draggables.forEach(draggable => {
    draggable.addEventListener('dragstart', dragStart);
  });

  dragListItems.forEach(item => {
    item.addEventListener('dragover', dragOver);
    item.addEventListener('drop', dragDrop);
    item.addEventListener('dragenter', dragEnter);

    item.addEventListener('dragleave', dragLeave);
  });

}

const todoInput = document.querySelector('#todo-input');
const todos = [];
var index2 = 6;

todoInput.addEventListener('keyup', function(e) {
  if (e.key == 'Enter' || e.keyCode == 13) {
    // index2++;
    // todos.push(e.target.value);
    newTodo(e.target.value);
    todoInput.value = '';
  }
})

function newTodo(value) {
  const todo = document.createElement('div');
  const todoText = document.createElement('p');
  todoText.classList.add('todo-name')
  const todoCheckbox = document.createElement('input');
  const todoCheckBoxLabel = document.createElement('label');
  todo.setAttribute('draggable', true);
  todo.classList.add('draggable')
  const numberSpan = document.createElement('span');
  numberSpan.classList.add('number')
  const todoLi = document.createElement('li');
  todoLi.setAttribute('className', 'draggable');
  todoLi.classList.add('list-item', 'not-crossed')
  const toDosContainer = document.querySelector('.draggable-list')
  const Container = document.querySelector('.container-todo')
  todoCross = document.createElement('span');
  todoCross.classList.add('cross')

  todoLi.setAttribute('data-index', index2);

  //   let content =[index2+ "-" + ' ' +  value ];
  //   var arrayValue = content.toString().replace(/,/g, "")

  numberSpan.textContent = "-";

  todoText.textContent = value;

  todoCheckbox.type = "checkbox";
  todoCheckbox.name = "checkbox";
  todoCheckBoxLabel.htmlFor = "checkbox";

  todoCheckBoxLabel.addEventListener('click', function(e) {
    if (todoCheckbox.checked) {
      todoCheckbox.checked = false;
      todoText.style.textDecoration = 'none';
      todoCheckBoxLabel.classList.remove('active');
      todoLi.classList.add('not-crossed')
      todoLi.classList.remove('thick-crossed')

    } else {
      todoCheckbox.checked = true;
      todoText.style.textDecoration = "line-through";
      todoCheckBoxLabel.classList.add('active');
      todoLi.classList.remove('not-crossed')
      todoLi.classList.add('thick-crossed')
    }
  });

  TodoList.push(todoText.textContent);
  listItems.push(todoText.textContent);
  console.log('lista', listItems);

  todoCross.textContent = 'X';
  todoCross.addEventListener('click', function(e) {
    e.target.parentElement.remove();
  });

  Container.classList.add('todos-container');
  todo.classList.add('todo');
  todoCheckbox.classList.add('checkbox')
  todoCheckBoxLabel.classList.add('circle', 'chk');
  // todoCross.classList.add('cross');

  todo.appendChild(todoCheckbox);
  todo.appendChild(todoCheckBoxLabel);
  todo.appendChild(numberSpan)
  todo.appendChild(todoText);
  todo.appendChild(todoCross);
  todoLi.appendChild(todo);
  toDosContainer.appendChild(todoLi)
}
<body>

  <main>
    <div class="header">
      <h1 class="title">TODO</h1>
      <div onclick="changeTheme()" class="tgl-btn"></div>
    </div>
    <div class="type-todo">
      <div class="circle"></div>
      <input type="text" value="" id="todo-input">
    </div>
    <div class="container-todo">
      <ul class="draggable-list" id="draggable-list">
      </ul>
      <div class="footer-div" id="footer-div"></div>
    </div>

    <p class="note">Drag and drop to reorder list</p>
  </main>

  <script src="./index.js"></script>
</body>

Thank you in advance and I hope you can help me

0 Answers
Related