I am trying to build a piece of javascript that take the url from the web page looks to see if there was an anchor included in the address then it will scroll down the page to the anchor, I have to do this because bootstraps sticky-top nav blocks the view of the element I am trying to view.
My js looks like
findLink = function(){
link = document.location.href
parseLink(link)
}
parseLink = function(link) {
if (link.split('').includes('#')) {
post_id = link.split('#')[1];
moveLink(post_id)
}
}
moveLink = function(post_id){
element = $('#+post_id').get()
}
$(document).on('turbolinks:load', findLink()) ||
$(document).on('page:load', findLink())
my issue is that even if I try to find
console.log($('#my_id')) # returns jQuery.fn.init {}
console.log($('#my_id').get()) # returns an empty []
I get two empty arrays. I am not sure why this is happening or how to fix it.
I ended up writing some JS its not perfect but it gets the job done.
document.addEventListener('turbolinks:load', function(){
link = document.location.href
parseLink(link)
});
parseLink = function(link) {
if (link.split('').includes('#')) {
post_id = link.split('#')[1];
moveLink(post_id)
}
}
moveLink = function(post_id){
element = document.getElementById(post_id)
$('html,body').animate({
scrollTop: $(element).position().top -= 200
});
}