Like most things in CSS, there are ways that work, and there are the right ways. Unfortunately, I'm not so much of a CSS guru.
I set '#' I my hrefs for a number of things - for things like opening menus etc.
However, I recently found a need to scroll smoothly to a place on the page. After some investigation, I came up with this code:
$('a[href^="#"]').click(function (e) {
e.preventDefault();
$(".body-wrap").animate({
scrollTop: $(this.hash).offset().top
}, 300);
});
Nothing wrong with it - it works.
However, it also causes conflict with every other '#' based href on the page that I use for other javascript triggers - specifically a[href^="#"].
The question I have is, is there a better way to approach this that is still as generic? For instance, you might say - don't need to assign # to all hrefs - I'm not sure what the impact might be, or there might be ways of adding to the selector above to make it more specific - such as, starts with #,but has other characters following.
This kind of thing must challenge developers every day, so there must be preferred techniques, or patterns to deal with this cleanly.
My preferred solution is to give them a class
$(".scrollLink").on("click",function (e) {
e.preventDefault();
$(".body-wrap").animate({
scrollTop: $(this.hash).offset().top
}, 300);
});
The best practice is prefixing javascript specific classes with js-.
$(document).on('click', '.js-scroll-link', function(e) {
e.preventDefault();
$('.body-wrap').animate({
scrollTop: $(this.hash).offset().top
}, 300);
});
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