I am creating a bubble sort visualiser and wanted to check value of two div and swipe them on next button click but not able to do
This is a bubble sort visualizer which check 1st and 2nd number from the first and second div and compare them. if found first one is greater just changes the div position on button click.
Example :- User enters 1,2,3,4,5 and clicks create array button. 5 divs with class "num" are created, each also have class "num-1", "num-2" and so on.
They are all inside the div "num-holder".
On clicking "sort-btn", "num-1" and "num-2" will be highlighted, since these are the first 2 comparisons in the algorithm, followed by "num-2" and "num-3" and so on.
This is a sorted array so all comparisons will show, but no element will change its position.
So if instead the array was 2,1,3,4,5.
On first comparison "num-1" and "num-2" will highlight and their order attribute will change to each other so they switch places.
let createBtn = document.getElementById('create-btn');
let numsArray = [];
var div;
let newArray = [];
createBtn.addEventListener('click', () => {
//creating array of integer.
let data = document.getElementById('numbers_input').value;
let newData = data.split(',');
newArray = newData.map(num => {
return Number(num);
})
//console.log(newArray);
let dataHolder = document.querySelector('.num-holder');
// adding div element to dom
for (let i = 0; i < newArray.length; i++) {
div = document.createElement('div');
div.innerHTML = newArray[i];
div.className = `num num-${i}`;
// div.style.order = `${newArray[i]}`;
div.setAttribute('data-val', newArray[i]);
dataHolder.appendChild(div);
console.log(div);
}
})
//swapping logic.
let sortBtn = document.getElementById('sort-btn');
for (let i = 0; i < newArray.length - 1; i++) {
for (let j = 0; j < newArray.length - i; j++) {
let sortBtn = document.getElementById('sort-btn');
sortBtn.addEventListener('click', () => {
let num1 = document.querySelector(`.num-${j}`);
let num2 = document.querySelector(`.num-${j+1}`);
console.log(num1, num2);
if (num1.innerHTML > num2.innerHTML) {
num1.style.order = `${newArray[j]}`;
num2.style.order = `${newArray[j + 1]}`;
}
})
}
}
.num-holder {
display: flex;
justify-content: space-between;
margin-top: 50px;
margin-bottom: 10px;
}
.num {
background-color: rgba(227, 130, 130, 0.53);
font-size: 30px;
}
.as-console-wrapper { height: 40px }
<label>Enter numbers seperated by comma here</label>
<input type="text" id="numbers_input">
<button type="button" id="create-btn">Create Array</button>
<div class="num-holder"></div>
<button id="sort-btn" class="sort-btn" type="button">Next</button>
<script src="index.js"></script>