jQuery to Vanilla JS - Smooth scroll to #href

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});
});

Thank you

Still stuck on this, any suggestions?

My understanding is that Jquery is a library of JS functions, the JS code is calling on one particular function called animate

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.

Can’t help you there, still grasping the basics of JS

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 :slight_smile:

Looking into “matches” for the selector of the href with prop #

I am not sure what you are trying to do with:

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)
  });
});
1 Like

Ah, this helps tremendously. I wasn’t using querySelectorAll, just querySelector… That solves it. Thanks!