Scrolling to the next div will automatically align it in the center of the screen for the user

I am in the process of creating a single-page website and I would like to stack multiple divs on top of each other, all approximately 400px in size (with variations). Instead of using a smooth scroll, I want the page to jump to the next div and have it centered on the screen. At the same time, I want the opacity of the content above and below to adjust in order to draw attention to the center div.

I have experimented with various scrolling plugins, but I have not found anything that achieves the effect I am looking for. Most of the plugins are designed for full-page divs, rather than divs that are only a fraction of the height of the page.

Can anyone recommend a solution or point me in the right direction on how I can modify an existing plugin to achieve this desired effect?

Answer №1

  1. Implement an event listener on the document that scans for elements with the class .next
  2. Calculate the distance from the top of the viewport to the top of the specified element
  3. Subtract half of the viewport height minus the element's height
  4. If the element exceeds the viewport size, scroll to the top of the element
  5. Alternatively, scroll the element to the center of the viewport
  6. Adjust the opacity of the inactive elements

(Check out the demo here)

(function(){
    "use strict";
    document.addEventListener('click', function(e) {
        if(e.target.className.indexOf('next') >= 0) {
            var current = e.target.parentElement
            var next = current.nextElementSibling || false;
            if(next) {
                var nextNext = next.nextElementSibling;

                var height = next.offsetHeight;
                var top = next.offsetTop;
                var viewHeight = window.innerHeight;
                if(viewHeight - height > 0) {
                    var scrollTo = top - ((viewHeight - height) / 2);
                } else {
                    var scrollTo = top;
                }
                window.scroll(0, scrollTo);

                current.style.opacity = '0.5';
                next.style.opacity = '1';
                if(nextNext) nextNext.style.opacity = '0.5';
            }
        }
    }, false);
})();

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

Display the header on every single page using puppeteer

            Whenever I enable displayHeaderFooter, the header does not display. It only works if I add margin to @page in my CSS, but this causes the page height to increase by the margin value and content to overflow beyond the page boundaries. Is ...

Angular 6 TypeScript allows for efficient comparison and updating of keys within arrays of objects. By leveraging this feature

arrayOne: [ { id: 1, compId: 11, active: false, }, { id: 2, compId: 22, active: false, }, { id: 3, compId: 33, active: false, }, ] arrayTwo: [ { id: 1, compId: 11, active: true, }, { id: 2, compId: 33, active: false, ...

Spring Security does not generate an error if the authorization header is missing following a login using AngularJS

Working on implementing HTTP Basic Authentication using Spring Security and Angular JS by including the Authorization header in $http headers: const headers = { authorization: "Basic " + btoa(this.login + ":" + this.password) }; this._$http.get("user ...

Leveraging AJAX to transmit a JavaScript variable to PHP within the same webpage

I have a webpage where I want to update a PHP variable based on the value of a name attribute when a user clicks on a link. Here is an example of what I am attempting to accomplish: // PHP <?php $jsVar = $_POST['jsVar']; echo $jsVar; ...

Struggling to find the right alignment for my Bootstrap card design

I'm attempting to center a card in the middle of the screen. While I was able to horizontally center it using mx-auto, I'm facing difficulties with vertical centering. I tried using mt-3 to add margin-top to the card, but it only gives me about ...

Unexpected outcomes when generating jQuery pages using CSS

I have created a piece of JavaScript code that populates 3 divs with icons in even rows. However, I am facing an issue where my first two rows align as expected, but the third row starts aligned with .col-5. Can you help me troubleshoot this? function row ...

Serialization of select value in Ajax/PHP form submission

Currently, the form is sending the correct information but it is missing the state field. The issue arises because the value of the state field is not fixed and depends on the selected state. How can I address this? JS: $('#sendFormBtn').live(& ...

Issue with overflow:scroll displaying incomplete div contents

I am attempting to create a sidebar with a fixed position, featuring a small header and a scrollable content area below it. The issue I am facing is that I am unable to scroll through the entire content within the div, resulting in some parts being cut of ...

The jQuery code runs successfully on jsFiddle, but fails to execute on my website

I've created a login script that generates a username by combining the first and last names (on blur), eliminating spaces, and removing special characters. While everything functions correctly in jsFiddle, I encounter an error on my website indicatin ...

The Harp server generates excessive white space within HTML documents

Running a blog on Harp has been smooth sailing, except for one issue that I can't seem to figure out. The project utilizes EJS and the problem lies in the outputted HTML containing excessive whitespace. I've attempted to minimize it, especially w ...

Animate the jQuery element to fade in after it has been hidden with the slide effect

I am trying to create a div that slides out of the viewport and then fades in at the same spot with a different background image. However, currently it only slides out and does not fadeIn: $('#myDiv').hide('slide').queue(function() { ...

Parsley JS - Personalized Validation for Ensuring selected Items meet Minimum Value Requirements

Is it possible to validate a form so that at least 5 select boxes are set to Yes? If there are fewer than 5, the form should not submit and display an error message. I believe a custom validator is needed for this task. To see a complete example, check ou ...

Retrieve the following element by using the absolute xpath

I am currently working on my dashboard and there is a specific value that I need to retrieve. After some trial and error, I managed to use the following code https://i.sstatic.net/2lnzk.png Here is the code snippet used to obtain the xpath: driver.find_e ...

Need help aligning content with flexbox? Having trouble with align-content and justify-content not working correctly?

First and foremost, I want to express my gratitude in advance for any assistance you can provide. My goal was to neatly align three pieces of content within each row, similar to the image displayed here: https://i.sstatic.net/vtsRj.png To achieve this lay ...

What are some effective ways of using the parent, before, and children selectors?

<table> <tr><td><input type="text" value="123"></td><td><input class="here" type="text"></td></tr> <tr><td><input type="text" value="333"></td><td><input class=" ...

I am looking to implement a feature that will disable unchecked checkboxes based on certain conditions in a

Upon selection of an option from a dataset, an API call is triggered. The API response includes an object with a nested array, whose values are listed as checkboxes. Additionally, the API returns a key named choose(const name primaryMax) indicating the max ...

Error in Node.js Socket.io: The disconnect event is being triggered before the connect event

When the client reconnects after a network drop, the disconnect event is triggered on the server. Client code: var url ='192.168.1.101', port = '80', socket = io.connect('http://' + url + ':' + port, { &apo ...

Tips on creating a persistent form element that remains fixed as you input data into an array contained in the

I am a student in my final quarter of school working on a project that involves utilizing JQuery to dynamically add form fields. To achieve this, I need to use arrays for the name field to collect information from potentially multiple identical fields. Add ...

Tips for inserting an HTML element within an exported constant

I need help formatting an email hyperlink within a big block of text. Here is the code snippet: const myEmail = '<a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2e4b564f435e424b6e4b564f435e424b004d41 ...

Jquery cannot be used to set a value for an ASP .net hidden field

Having trouble setting the value of a hidden field using jQuery in ASP .NET. The hidden field is defined as follows: <asp:HiddenField runat="server" ID="hdnSelectedTicket" /> This is how I am attempting to set the value: alert(ticketI ...