I am trying to push my JS knowledge, hence I am trying to convert JQuery code to JavaScript. This is jQuery code
$('a[href*="#"]')// Select all links with hashes
// Remove links that don't actually link to anything
.not('[href="#"]')
.not('[href="#0"]')
.click(function(event) {
// On-page links
if (
location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
&&
location.hostname == this.hostname
) {
// Figure out element to scroll to
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
// Does a scroll target exist?
if (target.length) {
// Only prevent default if animation is actually going to happen
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 850, function() {
// Callback after animation
// Must change focus!
var $target = $(target);
$target.focus();
if ($target.is(":focus")) { // Checking if the target was focused
return false;
} else {
$target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
$target.focus(); // Set focus again
};
});
}
}
});
And this is something that I have changed, but I'm not sure how to continue, I'm a beginner so I am facing some struggles.I try my level best to convert that JQuery code to "vanilla" JS but did some mistakes. Can you please tell me where I went wrong??
document.querySelectorAll('a[href*="#"]')// Select all links with hashes
// Remove links that don't actually link to anything
.not('[href="#"]')
.not('[href="#0"]')
.addEventListener(function(event) {
// On-page links
if (
location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
&&
location.hostname == this.hostname
) {
// Figure out element to scroll to
var target =document.querySelector(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
// Does a scroll target exist?
if (target.length) {
// Only prevent default if animation is actually going to happen
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 850, function() {
// Callback after animation
// Must change focus!
var $target = $(target);
$target.focus();
if ($target.is(":focus")) { // Checking if the target was focused
return false;
} else {
$target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
$target.focus(); // Set focus again
};
});
}
}
});
.not(since that doesn't exist in standard DOM.