Is there a way to use jQuery to centrally align the accordion item that I have chosen?

My attempts to use `this.scrollIntoView({behavior: "smooth"}) were yielding inconsistent results in terms of where the selected item would land on the page. I believe I might need to utilize scrollTop(), but as someone who is new to jQuery, I am feeling a bit overwhelmed by the various potential solutions.

If you would like to view a working example, please see the following Codepen link: https://codepen.io/boingloings33/pen/JjwWQpE

Thank you for any assistance you can provide.

Script.js


        jQuery(function () {
            $(".head").on("click", function () {
                let isActive = $(this).hasClass("active");

                $(".head").removeClass("active");
                $(".head").parent().find(".content").slideUp(280);
                $(".head").parent().find(".arrow").removeClass("arrow-animate");
                if (isActive === false) {
                    $(this).addClass("active");
                    $(this).parent().find(".arrow").addClass("arrow-animate");
                    $(this).parent().find(".content").slideDown(280);
                }
            });
        });
    

index.html


        <div class="container">
            <div class="accordion" id="accordion-1">
                <div class="head">
                    <h2>Number 1</h2>
                </div>
                <div class="content">
                    <p>
                        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua... (content continues)
                    </p>
                </div>
            </div>
            <br />
            (additional accordion items omitted for brevity)
        </div>
    

styles.css


        body {
            font-family: Lato;
            background: rgb(142, 215, 213);
            overflow-y: scroll;
        }
        (CSS styles continue...)
    

Answer №1

Attempting to execute this task while the elements are in the process of opening or closing may not yield reliable results. It could be challenging to consistently pinpoint a specific position under those circumstances. A better approach would be to implement the functionality within the callback function of the slideDown animation:

$(this).parent().find(".content").slideDown(280, function() {
  this.closest('.accordion').scrollIntoView({
    behavior: "smooth",
    block: "center"
  });
})

Answer №2

I made a modification to your slideDown function and incorporated a scrollTop animation to bring the selected item to the center of your screen. It is recommended to add more items for thorough testing.

const selectedItem = $(this)
$(this).parent().find(".content").slideDown(280, function () {
    $('html, body').stop().animate({
        scrollTop: selectedItem.offset().top + selectedItem.parent().height() / 2 - $(window).height() / 2
    })
});

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

JavaScript can be used to deactivate the onclick attribute

Is there a way to deactivate one onclick event once the other has been activated? Both divs are initially hidden in the CSS. I'm new to programming, so any help is appreciated. Markup <a id="leftbutton" href="#" onclick="showDiv(this.id); return ...

Adjusting the color of an HTML slider button as it moves

In my setup, I have a straightforward slider that I plan to use for controlling the movement of a stepper motor based on the slider's position. I wanted to give the website where this will be hosted a professional look, so I've spent quite some t ...

Error message occurred in Express/React application when Node was unable to locate the "error" view

My app was functioning properly a few hours ago, but now I am encountering an error upon starting it. The issue lies in the absence of a /views directory in /lib, which is present in my src/ directory, containing error.jade. Despite trying various soluti ...

Utilizing JQuery's hasClass method in conjunction with an If statement

I need the loadContent function to specifically target a certain div only when the clicked link has a particular class. This is my current implementation: function loadContent(targetDiv, sourceURL) { if ( $(this).hasClass("done") ) { $(""+targetDiv+"").lo ...

Common reasons why you may encounter the error "Uncaught TypeError: $(...).DataTable is not a function"

I recently started working with DataTable.js, and when I tried to integrate it into my ASP.NET Core MVC 5.0 project, I encountered an error: Uncaught TypeError: $(...).DataTable is not a function After doing some research on Google, I discovered that this ...

Looking for a way to transform form values into objects once they have been added to FormData?

Facing an issue with submitting a form using formgroup. Initially, the form value was an object, but after appending it to formdata, the value turns into a string, making it difficult to parse the data in the query. After submitting, the form value of us ...

Can IE Conditional Comments have a negative impact on page speed?

Debates between "CSS hacks" and "Conditional Comments" have become a regular occurrence for me lately, so I wanted to hear the thoughts of the Stack Overflow community on this topic. <!--[if IE]> <link type="text/css" rel="stylesheet" href="ie-s ...

What is the reason behind the cautionary note associated with Vue's provide and inject functionality?

Considering incorporating Vue's new provide/inject feature into a project, I came across a warning in the official Vue documentation: The documentation states that provide and inject are primarily intended for advanced plugin/component library usage ...

The variable in Angular stopped working after the addition of a dependent component

Currently, I am working with Angular and have implemented two components. The first component is a navigation bar that includes a search bar. To enable the search functionality in my second component (home), I have added the following code: HTML for the n ...

The promise from the angular $http function is being duplicated

As I work on evaluating an expression within an if statement to return either true or false, I am utilizing $http promises. Despite the abundance of documentation available on this topic, I am confident in my ability to resolve any issues that may arise. ...

Ways to retrieve a designated object linked to a specific value within a JavaScript structure

I am facing a challenge where I need to set a javascript property object with values from another property object within the same instance. Currently, I have the following object: var PLAYER = { slides: { { slide_id: 60, slide_content: 'c ...

Waiting for text change in Selenium elements: A comprehensive guide

One of my elements changes its status in text form based on a context menu that is associated with it. Here is the particular element: td id="A" name="status"> StatusStart </td> Under certain circumstances, this can transform into ...

Welcome Message using Discord.js V13

As a newcomer to bot creation, I am facing an issue with my welcome message in discord.js v13. Previously working in v12, I am now encountering difficulties sending a message to a specific channel when a user joins the server. After some investigation, I r ...

Having trouble with positioning divs on top of each other? Struggling to get position absolute to work correctly?

Currently, I am utilizing flexbox to construct a grid layout. However, I have hit a roadblock when attempting to make the divs stack on top of each other. The overflow:auto is hidden and position relative has been added to the carddiv. While the divs are s ...

Using webpack to bundle node_modules into your application

I am facing an issue while trying to load some modules like: moment echarts In my package.json file, I have the following versions specified: "echarts": "^3.1.10" "moment": "^2.14.1" However, I am encountering the errors below: VM2282:1 Uncaught Ref ...

"Utilizing Bootstrap to create a space-saving table layout with an

Using Bootstrap on a table causes an unexpected empty column to appear on the right side (as shown in the screenshot). This issue is strange because it works fine with another table using the same setup... but this particular table seems to have a mind of ...

Row in Internet Explorer 7

I have a function that reveals hidden rows in a table, which works perfectly in all tested browsers except for IE7. The function is written using Prototype.js. function showInactives(){ var row_list = $$('tr.inactive'); var ck =$('inactive_ ...

Having difficulty retrieving precise HTML information for data scraping purposes

I'm a beginner in python and exploring web scraping for a project on . Currently, I'm using selenium to automate the search for a CUSIP and then extract specific details about it. Although I've successfully automated navigation from EMMA&a ...

code for handling window.location.href error

Continuing from the previous question, I am facing an issue with redirecting a form to an action while using Ajax. Despite my attempts to add a redirect in the Ajax function, I keep encountering errors and getting the wrong URL. The desired redirection is ...

From jQuery to Vanilla JavaScript: Implementing a simple click event listener

I've been attempting to translate the following jQuery code into vanilla JavaScript, however, I can't get it to function properly. jQuery: $(document).ready(function() { $("button").click(function() { var char = "0123456789abcdefghijklmno ...