WordPress: One-page scroll JQuery script not worki

2020-04-12 16:57发布

问题:

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

回答1:

Use the proper id like :

<a href="#contact-View">Contact</a>
for 
<div id="contact-View" class="contact-us-section"> #content </div
AND
<a href="#about-View">About</a>

<div  id="about-View" class="bg-1-wrapper"> #content </div>

 

 jQuery(document).ready(function(){
  jQuery("a").on('click', function(event) {
	if (this.hash !== "") {
    // Prevent default anchor click behavior
      event.preventDefault();
	var hash = this.hash;
	// Using jQuery's animate() method to add smooth page scroll
      // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
      jQuery('html, body').animate({
        scrollTop: jQuery(hash).offset().top
      }, 1500, function(){
	  
	  // Add hash (#) to URL when done scrolling (default click behavior)
        window.location.hash = hash;
      });
    } 
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

   

 <a href="#contact-View">Contact</a>
    <a href="#about-View">About</a>

    <div id="about-View" class="bg-1-wrapper">
      <h2>About</h2>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas nisl est, malesuada nec dolor vel, bibendum congue nunc. Aliquam efficitur nulla ac tortor pharetra, id posuere sapien blandit. Fusce ultrices hendrerit diam. Ut quis mi in sapien elementum
        egestas vitae in purus. Donec nec ex a justo laoreet placerat eu ut lectus. Quisque placerat turpis tincidunt odio blandit, sed posuere ipsum imperdiet. Vestibulum porttitor et sapien vitae pretium. .</p>
      <p>Sed scelerisque vulputate ligula, eu blandit enim congue vel. Quisque risus sapien, pellentesque nec est vitae, elementum interdum metus. Fusce sagittis turpis nec tortor lacinia rutrum. Ut sodales blandit tellus a auctor. Vestibulum ante ipsum
        
      </p>
    </div>
    <div id="contact-View" class="contact-us-section">
      <h2>Contact</h2>
      <p>Proin posuere porta magna efficitur tincidunt. Duis tincidunt nulla vel elit sagittis, eu ornare quam vehicula. Sed ut urna a purus imperdiet ultrices. Sed non ipsum vitae nisl dapibus volutpat. In sed interdum mauris. Curabitur ipsum sapien, dapibus
        at purus ut, elementum tempus urna. Nullam dignissim volutpat velit. Duis mi est, eleifend sed ante dolor.</p>
      <p>ondimentum et purus. Nunc convallis elit purus, ut tempus ipsum sodales et. Sed vulputate nec massa non viverra. Mauris tempus efficitur efficitur. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Morbi nulla lectus, dictum non sollicitudin
        ac, tincidunt nec eros. Quisque posuere tellus in lacinia pharetra. Aliquam pellentesque, lacus quis finibus finibus, ipsum ante aliquet felis, a euismod diam urna nec tortor. Integer vitae tempor nunc, quis auctor mauris.</p>
    </div>



回答2:

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 )
  • You are not closing the jQuery .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... and jQuery('-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.:

var sectionID = $(this).attr('href') + "-View";

See proof-of-concept example below:

jQuery(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)
    });
  }
  setBindings();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#contact">Contact</a>
<a href="#about">About</a>

<div id="about-View" class="bg-1-wrapper">
  <h2>About</h2>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas nisl est, malesuada nec dolor vel, bibendum congue nunc. Aliquam efficitur nulla ac tortor pharetra, id posuere sapien blandit. Fusce ultrices hendrerit diam. Ut quis mi in sapien elementum
    egestas vitae in purus. Donec nec ex a justo laoreet placerat eu ut lectus. Quisque placerat turpis tincidunt odio blandit, sed posuere ipsum imperdiet. Vestibulum porttitor et sapien vitae pretium. Cras id nisl enim. Class aptent taciti sociosqu
    ad litora torquent per conubia nostra, per inceptos himenaeos. Aenean in nulla porttitor, tincidunt nulla id, vestibulum enim. Etiam ante justo, congue eu diam consequat, fringilla tempus orci.</p>
  <p>Duis magna ipsum, venenatis et massa eget, dignissim imperdiet felis. Quisque vel ultrices purus. Cras ante nulla, auctor quis purus et, finibus congue massa. Fusce eleifend tristique ipsum non tempor. Vivamus eget leo dignissim, efficitur urna a, dignissim
    metus. Sed scelerisque vulputate ligula, eu blandit enim congue vel. Quisque risus sapien, pellentesque nec est vitae, elementum interdum metus. Fusce sagittis turpis nec tortor lacinia rutrum. Ut sodales blandit tellus a auctor. Vestibulum ante ipsum
    primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aenean placerat massa nisl, semper varius neque vehicula a. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae.
  </p>
</div>
<div id="contact-View" class="contact-us-section">
  <h2>Contact</h2>
  <p>Proin posuere porta magna efficitur tincidunt. Duis tincidunt nulla vel elit sagittis, eu ornare quam vehicula. Sed ut urna a purus imperdiet ultrices. Sed non ipsum vitae nisl dapibus volutpat. In sed interdum mauris. Curabitur ipsum sapien, dapibus
    at purus ut, elementum tempus urna. Nullam dignissim volutpat velit. Duis mi est, eleifend sed ante ac, malesuada lacinia sem. Quisque facilisis elit ultricies, scelerisque orci in, tempor purus. Nam dapibus eros at risus tincidunt laoreet. Donec
    facilisis sed erat interdum aliquet. Integer feugiat lorem id odio eleifend, eget eleifend sapien dapibus. Sed posuere mi vitae metus malesuada mollis. Mauris ac felis fringilla, euismod tellus sed, dictum nunc. In vel gravida dolor.</p>
  <p>Curabitur laoreet facilisis massa ac tristique. Suspendisse tortor nisl, faucibus non nunc eu, feugiat dictum ligula. Donec ipsum ipsum, volutpat a maximus nec, sagittis quis ipsum. Praesent arcu lectus, rhoncus quis lacinia a, condimentum et purus.
    Nunc convallis elit purus, ut tempus ipsum sodales et. Sed vulputate nec massa non viverra. Mauris tempus efficitur efficitur. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Morbi nulla lectus, dictum non sollicitudin
    ac, tincidunt nec eros. Quisque posuere tellus in lacinia pharetra. Aliquam pellentesque, lacus quis finibus finibus, ipsum ante aliquet felis, a euismod diam urna nec tortor. Integer vitae tempor nunc, quis auctor mauris.</p>
</div>



回答3:

You can use below for the page scroll

$(document).ready(function() {

  jQuery('a[href^="#"]').on('click', function(e) {
    e.preventDefault();

    var sectionID = $(this).attr('href') + "-View";

    jQuery("html, body").animate({
      scrollTop: jQuery(sectionID).offset().top
    }, 1000)
  });
});