Trying to create a simple one page scroll.
In WordPress, I have navigation a tags like this.
<a href="#contact">Contact</a>
<a href="#about">About</a>
The Corresponding divs for both links are this.
<div id="about-View" class="bg-1-wrapper"> #content </div>
<div id="contact-View" class="contact-us-section"> #content </div
This is the problem (I think). My script isn't selecting the anchor links id.
Script.js
/* ONE PAGE NAVIGATION FUNCTION */
function setBindings() {
jQuery('a[href^="#"]').click(function(e) {
// prevent anchor tags for working (?)
e.preventDefault();
var sectionID = e.currentTarget.id + "-View";
jQuery("html, body").animate({
scrollTop: jQuery("#" + sectionID).offset().top
}, 1000)
})
}
Any ideas, what am I doing wrong here? This is the website
UPDATE **Here is the amendments I've made after looking at the answers. Script still not work?!
jQuery(document).ready(function() {
// add a click listener to each <a> tags
setBindings();
// burger nav
jQuery(".burger-nav").on("click", function() {
jQuery(".header-nav").toggleClass("open");
});
});
/* ONE PAGE NAVIGATION FUNCTION */
function setBindings() {
jQuery('a[href^="#"]').on('click', function(e) {
e.preventDefault();
// Get the href attribute, which includes '#' already
var sectionID = $(this).attr('href') + "-View";
jQuery("html, body").animate({
// Find target element
scrollTop: jQuery(sectionID).offset().top
}, 1000)
});
}
As per my comment, there are several syntax errors in your code, where the function calls are not closed properly:
function(e)
has an extra trailing)
.on()
method properly. You used}
instead of})
.These errors should be pretty apparent when you check your browser console—that's why it's very imperative that you create a minimal, concrete and verifiable example in your question, because you will already solve half of your issues by fixing syntactic errors with the code.
That aside,
e.currentTarget.id
does not refer to the ID of the target element.e.currentTarget
simply refers to "the current DOM element within the event bubbling phase", which is still the<a>
element. Since it does not have an ID, it will return an empty string and your selector will eventually be-View
... andjQuery('-view')
does not match anything on the page, so no scrolling will happen.What you can do instead is to simply read from the
href
attribute of the anchor element, append-View
to it and simply pass it to the jQuery selector, i.e.:See proof-of-concept example below:
Use the proper id like :
You can use below for the page scroll