Maintaining an element's vertical position in relation to the screen with jQuery

I'm very close to achieving what I want, but my goal is a bit unconventional.

My setup includes several panels divided into 2 columns, with each panel capable of triggering an expand/compress toggle.

My challenge is maintaining the vertical positioning of the element that triggered the toggle, so users can easily keep track of the panel they want to see in expanded mode.

Unfortunately, I haven't been able to figure out how to make the scroll position of lower panels move up when the expand button is clicked.

$('button').click(function () {
    var id = $(this).closest('div').attr('id');
    var target = $('#' + id);
    $('html,body').animate({
        scrollTop: target.offset().top
    }, 1000);

    $('.fa-compress').toggle();
    $('.fa-expand').toggle();
    $('.row > div').toggleClass('col-xs-6').toggleClass('col-xs-12');
});

You can view my progress on JS Fiddle

**UPDATE

For clarity, users will initially see the compressed view (2 column layout), and if they choose to view a specific panel, they can click the expand button. I want the expand animation to happen without affecting the vertical positioning of the triggered panel. This is what I mean by keeping vertical positioning intact.

Answer №1

It's a bit unclear what you're looking for, but I'll give it a shot.

$('button').click(function(){
    // Put your code here first

    var container = $(this).closest('panel');

    // Calculate the distance to the top of the viewable screen
    var viewableOffset = $(container).offset().top - $(window).scrollTop(); 

   // Fix the panel at the current position when clicked       
   $(container).css('position', 'fixed');
   $(container).css('top', viewableOffset + 'px');

}

Edit: Apologies for not mentioning how to maintain the left-position, but you should be able to work it out from here :)


Edit 1

I think I understand now. If you want the panel to remain in place on the screen as it expands to full width without scrolling: You'll need to move (append) the element in the dom.

The concept involves calculating the number of preceding elements, then appending the selected panel after half that number, rounded down to the closest even number.

For example, if you expand panel 5:

Number of siblings before #5 is 4

4 / 2 = 2

Placing 5 after #2 in expanded view will keep #5 at its original height in the small view.

If you save the original position of #5 and revert it back when minimizing, everything should return to its initial state.

Answer №2

Here is a suggestion to improve your code:

When a 'button' is clicked, find the closest '.panel' element and calculate its index within all '.panel' elements. 
Then, determine the total height by multiplying the single height of the target with its index.

Animate the scrolling of the 'html' element to the total height over a duration of 500 milliseconds.

Toggle the visibility of two font awesome icons ('fa-compress' and 'fa-expand') and toggle the classes of all direct children of '.row'.

<a href="http://jsfiddle.net/dekkard/puye3ode/2/" rel="nofollow">View the example on JSFiddle</a>

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

The hovering of the mouse over a dropdown menu causes a division on the page to shift

Creating a website with a dropdown menu and slider division can be tricky. When hovering over the menu, the submenu displays but causes the slider division to shift down. Does anyone have suggestions on how to fix this issue? Below is the code: <html& ...

Display tab content by clicking on a link from an external source

How can I make a link, <a href="#" class="link-one">Link</a>, outside of nav-tabs activate a tab-panel/tab-content in Bootstrap 5? Can someone simplify this for me? // Show relevant Bootstrap tab based on an outside link cl ...

Vertically arrange the table for better visibility

I need help with changing the table layout from horizontal to vertical. Currently, all fields are displayed horizontally and I want them to be displayed vertically. Also, I'm trying to add a functionality where the current date is added to the databas ...

The not:first-child selector targets all elements except for the first one in the sequence

This is a simple js gallery. I am using not:first-child to display only one photo when the page is loaded. However, it does not hide the other photos. You can view the gallery at this link: (please note that some photos are +18). My objective is to hide ...

Tips for maintaining DataTables filters after navigating Back/Forward or refreshing the page

We are currently utilizing DataTables for our table, and we are encountering difficulties in retaining the history of filters that were previously applied to the table. This would allow users to navigate back and forth and refresh through these filters. O ...

What is the best way to switch the CSS style of a button that has been mapped

I'm currently working on toggling the CSS class for an individual button that is created from a mapped array. Although my code is functional, it toggles the CSS class for all buttons in the mapped array instead of just the one selected. ...

Set a click listener on a button within Ext.window.MessageBox

Currently, I am dynamically generating a message box using Ext.window.MessageBox. var msgBox = Ext.create('Ext.window.MessageBox', { title: '', //message in window msg: 'message text', icon: ' ...

Is the JQuery UI Loaded Event Triggered?

Is there a way to detect when the jQuery UI has loaded and also trigger an event upon its successful loading? Currently, I have my code enclosed within a $(document).ready() function. However, there are instances where the UI library fails to fully load, r ...

Methods for generating arrays using jquery and modifying session data

How can I create arrays with jquery and modify the session? I am looking to store a list of songs with titles, mp3 URLs, and authors in $ _SESSION ["playlist"] Below is an example of my HTML code <a class="add-music" data-title="Title of the litt ...

Is there a way to incorporate a responsive side menu using JQuery or CSS3 that can shift the entire page layout?

Hey there, I'm currently trying to incorporate a responsive side menu into my website using either JQuery or CSS3. What I need is a side menu that will smoothly shift the page content when a link is clicked, and also adds a close button (X) to the men ...

Add a div element only if there is a background image present

I am facing a situation where I need to display an image as the background of a div only if it is available. If the image is not present, I do not want the div to be visible at all. I am working with django templates and here is my current approach: {% if ...

Manipulating anchor links with jQuery by adding and removing classes

I am struggling to understand why I cannot remove a class from an element and then add a new one. Changing the CSS using .css(...) works, but for some reason .removeClass and .addClass are not functioning. Interestingly, I am able to successfully add and ...

Incorporating jQuery ajax requests into divs seamlessly to avoid any page disruptions

When loading numerous ajax calls on a page, the timing of each call varies, resulting in some content loading before the user reaches the top of the page. This may cause the user to miss viewing certain data unless they scroll back up to the top. Below is ...

Bringing elements into perfect harmony in Angular

Seeking guidance on HTML alignment using bootstrap for prebuilt components like buttons. Struggling with aligning divs and looking to learn more about grouping them together for proper alignment. Goal is to center elements on screen one above the other. ...

Dynamic scrolling text for overflowing text display

Here's a scenario I'm facing: Let's say I have three div tags, each 100 pixels wide: <--- DIV WIDTH ---> Text in div 1 Text in div two, it overflows Text in div three <--- DIV WIDTH ---> Currently, I've set the following C ...

Populate the dropdown menu with data from a JSON file

Recently, I created a custom JSON file and wanted to populate a select>option using this data. However, I encountered an error message saying: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///C:/.../p ...

Exploring the functionality differences between mouse wheel tilt and scroll in JavaScript with scrollTop

Did you know that some computer mice come equipped with a scroll wheel that can tilt both left and right? This feature allows users to navigate through Google's piano roll app, which can be accessed here (source code available here). I am working to ...

No modifications to the CSS can be made within the "alterations" section of the Console drawer in Chrome

Is there a way to easily track and summarize all of my live CSS changes in the Chrome browser? I've searched on Stack Overflow, but haven't found a solution that works for me. This specific answer seems like it could be the most helpful for achie ...

Implement a jQuery slider that pauses on hovering

Currently, I am grappling with the clearInterval function in a small jQuery project. To better illustrate the issue, I have created a jsFiddle example: http://jsfiddle.net/eWTSu/ While the rotation works smoothly, I encountered an obstacle when hovering ...

What is the best way to target the nth-child() of a slotted element within a web component that utilizes multiple uniquely named slots?

I am struggling to select the second slotted item in a specific slot using slot[name=foo]::slotted(:nth-child(2)){, but it's not behaving as I anticipated. Even though the first foo slot is styled with green, the second one doesn't follow suit. ...