I am working on a script to move list elements up and down with a button click.
I can make it work with jQuery, but I have troubles writing this in pure (vanilla) JavaScript.
$(function() {
$('.up').on('click', function(e) {
var wrapper = $(this).closest('li')
wrapper.insertBefore(wrapper.prev())
})
$('.down').on('click', function(e) {
var wrapper = $(this).closest('li')
wrapper.insertAfter(wrapper.next())
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>1 <a class='up' href='#'>up</a> <a class='down' href='#'>down</a></li>
<li>2 <a class='up' href='#'>up</a> <a class='down' href='#'>down</a></li>
<li>3 <a class='up' href='#'>up</a> <a class='down' href='#'>down</a></li>
<li>4 <a class='up' href='#'>up</a> <a class='down' href='#'>down</a></li>
<li>5 <a class='up' href='#'>up</a> <a class='down' href='#'>down</a></li>
<li>6 <a class='up' href='#'>up</a> <a class='down' href='#'>down</a></li>
</ul>
How can I do the same in plain JavaScript?
{} is called an object and in your declaration: var my = {}; you are just creating an empty object to which you can then add properties to. Both arrays and objects can be accessed with the [x] syntax.
Hope this helps:
window.onload = function () {
var upLink = document.querySelectorAll(".up");
for (var i = 0; i < upLink.length; i++) {
upLink[i].addEventListener('click', function () {
var wrapper = this.parentElement;
if (wrapper.previousElementSibling)
wrapper.parentNode.insertBefore(wrapper, wrapper.previousElementSibling);
});
}
var downLink = document.querySelectorAll(".down");
for (var i = 0; i < downLink.length; i++) {
downLink[i].addEventListener('click', function () {
var wrapper = this.parentElement;
if (wrapper.nextElementSibling)
wrapper.parentNode.insertBefore(wrapper.nextElementSibling, wrapper);
});
}
}
<ul>
<li>1 <a class='up' href='#'>up</a> <a class='down' href='#'>down</a></li>
<li>2 <a class='up' href='#'>up</a> <a class='down' href='#'>down</a></li>
<li>3 <a class='up' href='#'>up</a> <a class='down' href='#'>down</a></li>
<li>4 <a class='up' href='#'>up</a> <a class='down' href='#'>down</a></li>
<li>5 <a class='up' href='#'>up</a> <a class='down' href='#'>down</a></li>
<li>6 <a class='up' href='#'>up</a> <a class='down' href='#'>down</a></li>
</ul>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With