I have this working exactly how I want in jQuery but can anyone convert this to vanilla JS for me and explain it a bit?
$(document).on('click', 'a[href^="#"]', function(e) {
// target element id
var id = $(this).attr('href');
// target element
var $id = $(id);
if ($id.length === 0) {
return;
}
e.preventDefault();
// top position relative to the document, offset by menuheight
var pos = $id.offset().top-50;
// animated top scrolling
$('html').animate({scrollTop: pos});
});
Huh? Iâm trying to get the vanilla javascript version of this jquery mate. I know what jquery does, sometimes using vanilla JS is a little bit more work but I want to move away from jQuery.
I started doing this and understand most of it except $(document).on(âclickâ, âa[href^=â#â]â
obviously its listening for a click on the document with an anchor where the href is #? But doesnât seem to be a clear cut way of writing this is vanilla.
Ill continue to look
Looking into âmatchesâ for the selector of the href with prop #
var $id = $(id);
if ($id.length === 0) {
return;
}
but ignoring the case where the jQuery on method in itself is doing a lot of heavy-lifting for you (e.g you did not have to worry about new anchor elements being added dynamically), then you could do something like the following to replace the first part to get the id.
const anchors = document.querySelectorAll('a[href^="#"]');
anchors.forEach(function(anchor) {
anchor.addEventListener('click', function(e) {
e.preventDefault();
var id = this.getAttribute('href');
console.log(id)
});
});