animation will not affect the auto scroll when using $('html,body').animate

Currently, I am in the process of creating a welcome page where I want users to be able to navigate to specific sections with just one click, and also have a smooth scrolling effect when moving between sections. While my JavaScript skills are not exceptional, I attempted to create something that looks like this:

$(".skippage").click(function() {
  $('html, body').animate({
    scrollTop: $("#content").offset().top
  }, 300);
});

(function() {
  var delay = false;
  $(document).on('mousewheel DOMMouseScroll', function(event) {
    event.preventDefault();
    if (delay)
      return;

    delay = true;
    setTimeout(function() {
      delay = false
    }, 200)
    var wd = event.originalEvent.wheelDelta || -event.originalEvent.detail;
    var a = document.getElementsByClassName('.IndexSection');

    if (wd < 0) {
      for (var i = 0; i < a.length; i++) {
        var t = a[i].getClientRects()[0].top;
        if (t >= 40) break;
      }
    } else {
      for (var i = a.length - 1; i >= 0; i--) {
        var t = a[i].getClientRects()[0].top;
        if (t < -20) break;
      }
    }
    $('html,body').animate({
      scrollTop: a[i].offsetTop
    });
  });
})();
html,
body {
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
}
.IndexSection {
  font-size: 6em;
  color: #ccc;
  width: 100%;
}
div#welcome {
  height: 100vh;
  background: white;
  text-align: center;
  margin: 0;
  position: relative;
}
.welcometext {
  background-color: red;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  height: 70%;
  width: 80%;
  float: none;
  margin: 0 auto;
  text-align: center;
  position: absolute;
}
.skippage {
  font-size: 12px;
  color: red;
  position: absolute;
  bottom: 2%;
  left: 50%;
  transform: translate(-50%, -2%);
}
div.navigation {
  background: #9C0;
  font-size: 12px;
  height: 10%;
}
div#content {
  height: 100vh;
  background: yellow;
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
  <title>Home</title>
  <link rel="stylesheet" type="text/css" href="style/bootstrap/css/bootstrap.min.css"> <!-- Bootstrap -->  
  <link rel="stylesheet" type="text/css" href="style/main.css"> <!-- custom -->
</head>
<body>
  <div id="welcome" class="IndexSection row">
    <div class=" welcometext">
      welcome
    </div>
    <a href="#" class="skippage">Go Down</a>
  </div>
  <div id="content" class="IndexSection">
    <div class="navigation">
      option
    </div>
    Content
  </div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="style/bootstrap/js/bootstrap.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="style/main.js"></script> <!-- custom -->
</html>

While I was successful in implementing the click function, the auto-scroll feature to move to the next div based on scrolling up or down is proving challenging.

  1. Could there be an issue with the animate method with $('html,body') at the end of the JavaScript code?
  2. The intended logic should be such that the section would scroll down when the user scrolls more than or equal to 40 pixels down, and scroll up when they scroll more than or equal to -20 pixels up,
  3. I discovered that changing

    var a= document.getElementsByClassName('.IndexSection'); to

    var a= document.getElementsByTagName('div'); made it work almost as I wanted.. But why can't I use getElementsByClassName?

I feel like I'm missing something crucial here. It should ideally work perfectly. Any help or guidance would be greatly appreciated.

Answer №1

modify

let elements= document.getElementsByClassName('.IndexSection');

to

let elements= $('.IndexSection');

and update offsetTop to offset().top

 $('html,body').animate({
      scrollTop: elements.eq(i).offset().top
    });

The complete revised code will be:

(function() {
  let delay = false;

  $(document).on('mousewheel DOMMouseScroll', function(event) {
    event.preventDefault();
    if(delay) return;

    delay = true;
    setTimeout(function(){delay = false},200)

    let wd = event.originalEvent.wheelDelta || -event.originalEvent.detail;

    let elements= $('.IndexSection');

    if(wd < 0) {
     elements.each(function(){
     const pos = $(this).position()[0].top;
        if(pos >= 40) return false;
});
    }
    else {
      for(let i = elements.length-1 ; i >= 0 ; i--) {
        const pos = elements[i].getClientRects()[0].top;
        if(pos < -20) break;
      }
    }
    $('html,body').animate({
      scrollTop: elements.eq(i).offset().top
    });
  });
})();

Answer №2

My apologies everyone, I made a silly mistake with a typo in the code and had a good laugh about it... no harm done though, everything is working perfectly now.

The mistake was here:

    var a= document.getElementsByClassName('.IndexSection');

I realized I didn't actually need to include a dot before 'IndexSection' so I corrected it like this:

var a= document.getElementsByClassName('IndexSection');

After making that adjustment, all of the code is now edited and functioning as intended. Thanks to those who helped out!

Answer №3

Maybe consider implementing a solution like this:

var lastScrollPos=0, scrollDirection='down', scrollMonitor=true;
$(function(){
$(".skippage").click(function() {
  $('html, body').animate({
scrollTop: $("#content").offset().top
  }, 300);
});
$(window).scroll(function(){
currScrollPos = $(window).scrollTop();
scrollDirection = (currScrollPos>lastScrollPos) ? 'down' : 'up';

if (scrollDirection=='down' && scrollMonitor){
scrollDelta = currScrollPos - lastScrollPos;
if (scrollDelta > 40){
scrollMonitor = false;
$('html, body').animate({
scrollTop: $("#content").offset().top
}, 900, function(){
scrollMonitor = true;
lastScrollPos = currScrollPos;
});
}
}else if (scrollDirection=='up' && scrollMonitor){
scrollDelta = lastScrollPos - currScrollPos;
if (scrollDelta > 40){
scrollMonitor = false;
$('html, body').animate({
scrollTop: $("#welcome").offset().top
}, 900, function(){
scrollMonitor = true;
lastScrollPos = currScrollPos;
});
}
}
}); //END window.scroll
}); //END document.ready
html,body {width:100%;height:100%;padding:0;margin:0;}
.IndexSection {font-size:6em;color:#ccc;width:100%;}
div#welcome {height:100vh;background:white;text-align:center;margin:0;position:relative;}
.welcometext {background-color:red;top:50%;left:50%;transform:translate(-50%, -50%);height:70%;width:80%;float:none;margin:0 auto;text-align:center;position:absolute;}
.skippage {font-size:12px;color:red;position:absolute;bottom:2%;left:50%;transform:translate(-50%, -2%);}
div.navigation {background:#9C0;font-size:12px;height:10%;}
div#content {height:100vh;background:yellow;}
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
  <div id="welcome" class="IndexSection row">
    <div class=" welcometext">
      welcome
    </div>
    <a href="#" class="skippage">Go Down</a>
  </div>
  <div id="content" class="IndexSection">
    <div class="navigation">
      option
    </div>
    Content
  </div>

Answer №4

     Move to the following question automatically
    return nothing
    
    create a function for selecting and scrolling to the next question
 
         Skip scrolling if it's the last question on a page with an explanation to display
        if the variable auto scroll next blockpage is set, adjust the scroll to show the explanation 
            'html bodyanimate 
                scrollTop to the next question Selector position plus 35 pixels as the top offset
             set the scrolling speed

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Delivering create-react-app's build files through an express server

I am trying to serve the build files of my React app on another Express application. I have copied all the static files from the build folder to the public folder inside my Express application and have set up the following code: app.use(express.static(pat ...

ExpressJs "window.location.href" causing the page to not refresh

Currently, I am working on a Node.js project using ExpressJs with view files having a .ejs extension. Within the project, I have implemented JavaScript code to reload the page when an option is selected from a select box. Here is the code snippet for rel ...

Determine the parent nodes of an item in an array tree

My array represents different groups, structured like so: Company Name IT Finance Global Finance Financial Department Tax and Co. My goal is to select a specific node (such as Financial Department) and create a new array containing that node and it ...

Performing a cross-domain POST request in Internet Explorer using jQuery and sending data

My application is currently functioning with CORS in Chrome and Firefox thanks to the plugin found at https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest I was able to enable CORS requests in IE by using this code: $.ajax({ url: url, ...

Using AngularJS to manage cookies along with arrays

I am passing my data in this way $cookies.putObject("currentLocation,values,allLocList", obj, vm.tempData, vm.allLocationList); The objects obj and vm.tempData are being sent as objects, while vm.allLocationList is an array that contains a JSON object. W ...

The words overlaid on the image spill out beyond its edges

I want to create a design where the text flows outside of the image and continues into another container. After some trial and error, I managed to achieve a layout where the text seamlessly extends beyond the image and into a separate section. Ideally, the ...

Place <h1> and <span> side by side on the same line for proper alignment

I am currently utilizing Bootstrap 5 to construct a webpage. The html code I have written is displayed below: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA- ...

How can parameters be passed to a JavaScript or jQuery function?

I am currently utilizing a JS/JQ function to convert values into currency by adding commas. Although the function is running smoothly, I am encountering an issue when attempting to pass parameters to it. Kindly provide assistance on how to successfully pas ...

Is there a javascript function that performs the reverse action of indexof()?

Is there a JavaScript function that is the opposite of indexOf()? In my code, when you press the button it will display 3 [from indexOf(".")]. However, I am looking for a function that is the opposite of indexOf(), which would show me 2 [decimal]. http: ...

Embedding an Angular function within a JavaScript function

My AngularJS dialog is defined in the angular-app.js file like this: angular.module('myAPP', ['ngMaterial']).controller('AppCtrl', function($scope, $mdDialog) { $scope.status = ' '; $scope.showAdvanced = fu ...

Change the state within the click event handler

One issue I'm facing is dealing with 2 submit buttons in my react form. To differentiate between the two buttons, I need to extract the `id` of the one that was clicked using the `onClick` function. Currently, when trying to set the state with this ` ...

`Why setRequestHeader is essential for Ajax and XMLHttpRequest`

Should I ever manually specify the setRequestHeader as 'application/x-www-form-urlencoded' for an ajax POST request? Is it necessary to manually define the setRequestHeader as 'multipart/form-data' when uploading files via ajax? Do XMLH ...

Achieving Image Center Alignment in Bootstrap for Responsive Designs

My code snippet appears fine in full-width view, but when I resize the browser, the images (cards) are not centered and lean towards the left side. How can I correct this issue? This is the HTML code I am using: <div class="container-fluid"> ...

Exploring the depths of JSON with the power of jQuery

Struggling to create a JSON structure that is multi-level deep and encountering issues at two points. The primary challenge lies in formatting the data correctly, along with the intention to introduce a "level_two" within the dataset. The secondary hurdle ...

Exploring logfile usage in JavaScript. What is the best way to structure the log?

Currently, I am developing a Python program that parses a file and records the changes made to it. However, I am facing a dilemma regarding the format in which this information should be saved for easy usage with JavaScript on the local machine. My objecti ...

Playing around with adjusting the size of a div that is positioned absolutely on the right side

Snippet: http://jsfiddle.net/scottbeeson/TU6Zw/ HTML Code: <div id="itemMap" class="shadow"> <div class="mapHeader">List of Items</div> <div class="mapItem">Item 1</div> <div class="mapItem">Item 2</div& ...

Providing CSS through PHP file on IIS Server

When attempting to output CSS using PHP in order to increase its dynamism with WordPress settings, I encountered a 500 internal server error. Despite setting the header to text/css and trying to add handlers in IIS, the issue persists. Interestingly, there ...

Hover to reveal stunning visuals

Can anyone help me figure out how to change the color of an image when hovered over using HTML or CSS? I have a set of social network icons that I want to incorporate into my website, and I'd like the icon colors to change when the mouse moves over th ...

Choose a checkbox by targeting a specific column value with XPath

While automating the testing with Selenium, I encountered an issue related to selecting a checkbox in a table row. To resolve this problem, I turned to XPath for assistance. Specifically, I needed to choose the row based on the file name. Below is the rele ...

The Flex-Direction property set to column is not applying correctly within a @media query

I'm still in the process of learning how to code, so please bear with me. I am attempting to create a navigation bar that, on desktop, will be displayed horizontally on the right side of the screen. However, when viewing on a device smaller than 800px ...