Zeon
Zeon

Reputation: 338

JQUERY "Click to scroll" keeps going back to the top when clicking on anything

if I click on "CV" it will scroll to the page. If I click on a link or photo it will keep scrolling back to the top of the page.

    // When the Document Object Model is ready
jQuery(document).ready(function(){
    // 'thisCVTopPosition' is the amount of pixels #thisCV
    // is from the top of the document
    var thisCVTopPosition = jQuery('#thisCV').offset().top;
    // When #scroll is clicked
    jQuery('#cv').click(function(){
        // Scroll down to 'thisCVTopPosition'
        jQuery('html, body').animate({scrollTop:thisCVTopPosition}, 'fast');
        // This stops the anchor link from acting like a normal anchor link
        return false;
    });
    jQuery('#thisCV').parent().click(function(){
        jQuery('html, body').animate({scrollTop:1}, 'fast');
        return false;
    })
});

My navigation bar:

<div id="sidebar-wrapper">
      <center>
        <ul class="sidebar-nav">
          <li class="logo"><a href="#Home" class="scroll"><img src="img/logo2.png" alt=
          "Portfollio" /></a></li>

          <li style="list-style: none; display: inline">
            <div class="animation">
              <div class="hoverImages" align="center"><img src="img/photo.jpeg" alt=
              "Photo" style="width:auto;height:auto;" /></div>
            </div>
          </li>

          <li><a href="#Home" id = "home">Home</a></li>

          <li><a href="#CV" id="cv">CV</a></li>

          <li><a href="#Projects" id="projects">My Projects</a></li>

          <li><a href="#Github" id="github">GitHub</a></li>

          <li><a href="contact.php">Contact Me</a></li>
        </ul>
      </center>
    </div>

CV

`   <div id="page-content-wrapper">
        <div class="container-fluid">
        <div id="thisCV" style="height: 1000px; width 100px">

              <h1>My CV</h1>
        [...]

` Is it my divs or the jquery? Update: Fixed my divs but it's still not working.

Upvotes: 1

Views: 1633

Answers (1)

&#193;ngela
&#193;ngela

Reputation: 1425

Anchor elements have a default action: going to their href url. When the href attribute is not set (or valid, I believe), the default action is refreshing the page (and going to the top).

It is possible that this is what is happening to you. You can use jQuery's event.preventDefault() to prevent any event from triggering its default action (jQuery docs):

jQuery('#cv').click(function(event){
    // Prevent the click from loading href
    event.preventDefault();

    // Scroll down to 'thisCVTopPosition'
    jQuery('html, body').animate({scrollTop:thisCVTopPosition}, 'fast');
    // This stops the anchor link from acting like a normal anchor link
    return false;
});

Upvotes: 1

Related Questions