Reputation: 1782
I'm having a strange bug that I cannot uncover. I found a similar question but it wasn't similar to my bug.
I have a simple JS function that will animate a scroll when clicking a href link. It works totally fine within this js fiddle, but it doesn't seem to work on this page (even though it's identical) and I cannot find the underlying issue.
https://www.wolfandgrizzly.com/pages/instructions
It occurs when you select a language.
var e = window.innerWidth;
$(document).on("click", 'a[href^="#"]', function(s) {
console.log($.attr(this, "href"));
s.preventDefault(), e >= 770 ? $("html, body").animate({
scrollTop: $($.attr(this, "href")).offset().top - 48
}, 500) : $("html, body").animate({
scrollTop: $($.attr(this, "href")).offset().top - 100
}, 500)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="height:1000px;"><a href="#clickMe">ClickMe</a></div>
<div id="clickMe">
Upvotes: 1
Views: 67
Reputation: 1892
On that page there is nothing with id="German". When you click on a[href="#German"] the browser by default scrolls (ugly, non animated) to the element with ID = whatever_comes_after_hash. Your function overrides that behaviour with a nice smooth scroll down... But it still looks after an element with id="whatever_comes_after_hash"
in a href="#whatever_comes_after_hash"
Therefore the solution you need, is to add IDs to the elements on that page, and it should work perfectly fine.
var e = window.innerWidth;
$(document).on("click", 'a[href^="#"]', function(s) {
console.log($.attr(this, "href"));
s.preventDefault(), e >= 770 ? $("html, body").animate({
scrollTop: $($.attr(this, "href")).offset().top - 48
}, 500) : $("html, body").animate({
scrollTop: $($.attr(this, "href")).offset().top - 100
}, 500)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#id_of_target_element">ClickMe</a>
<div style='height: 1000px; background-color: red;'></div>
<div id="id_of_target_element">target element</div>
<div style='height: 1000px; background-color: blue;'></div>
Upvotes: 2
Reputation: 2948
In your example, you are using #clickMe
and id="clickMe"
on your actual webpage, you are using #French
and name="French"
. The #
selector looks for elements with the id
attribute. You are not using id
on your page.
You can change your html to use id
, or you can change your scrollTop
logic to select by name="French"
Upvotes: 1