Ensure the container is scrolled down to reach the element positioned at the bottom of the container

Is there a way to make an element positioned at the bottom of a container appear at the top of the page when clicked? You can see an example of what I mean in this jsfiddle:

http://jsfiddle.net/scientiffic/v7CBu/5/

I have a scrollable container ("container") that contains different elements. When clicking on links, the container scrolls to these elements within it. However, if one of the elements like "3" is at the bottom of the container, it cannot be brought to the top when clicked. How can I achieve this?

HTML:

<div class="container">
    <div class="subcontainer 1"><h1>1</h1></div>
    <div class="subcontainer 2"><h1>2</h1></div>
    <div class="subcontainer 3"><h1>3</h1></div>
</div>

<div class="controllers">
    <div class="controller" id="1">jump to 1</div>
    <div class="controller" id="2">jump to 2</div>
    <div class="controller" id="3">jump to 3</div>
</div>

Javascript:

$(document).ready(function(){
    $('#1').click(function(){
        $('.container').animate({
            scrollTop: $('.subcontainer.1').position().top + $('.container').scrollTop()
        }, 500);
    });

    $('#2').click(function(){
        console.log('go to 2');
        $('.container').animate({
            scrollTop: $('.subcontainer.2').position().top + $('.container').scrollTop()
        }, 500);
    });

    $('#3').click(function(){
        console.log('go to 3');
        $('.container').animate({
            scrollTop: $('.subcontainer.3').position().top + $('.container').scrollTop()
        }, 500);
    });
});

Answer №1

To dynamically adjust the height based on the clicked element, you can insert a shim below with varying heights. Although it may seem like a workaround, this method proves effective:

http://jsfiddle.net/v7CBu/12/

Here is the HTML structure:

<div class="container">
    <div class="subcontainer 1">
        <h1>1</h1>
    </div>
    <div class="subcontainer 2">
        <h1>2</h1>
    </div>
    <div class="subcontainer 3">
        <h1>3</h1>
    </div>
    <div class="shim"></div>
</div>
<div class="controllers">
    <div class="controller" id="1">go to 1</div>
    <div class="controller" id="2">go to 2</div>
    <div class="controller" id="3">go to 3</div>
</div>

And here is the corresponding JavaScript:

$(document).ready(function () {
    $('#1').click(function () {
        $('.shim').height(0);
        $('.container').animate({
            scrollTop: $('.subcontainer.1').position().top + $('.container').scrollTop()
        }, 1000);
    });

    $('#2').click(function () {
        console.log('go to 2');
        $('.shim').height(0);
        $('.container').animate({
            scrollTop: $('.subcontainer.2').position().top + $('.container').scrollTop()
        }, 1000);
    });

    $('#3').click(function () {
        console.log('go to 3');
        var newHeight = $('.container').height() - $('.subcontainer.3').outerHeight();
        $('.shim').height(newHeight);
        $('.container').animate({
            scrollTop: $('.subcontainer.3').position().top + $('.container').scrollTop()
        }, 1000);
    });
});

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

Using HTML to execute a JavaScript function that transforms images

The script cutImageUp has been previously discussed on SE in a thread about Shattering image using canvas. However, I have encountered a different issue while attempting to use it. The HTML code I implemented seems to be ineffective, and despite my efforts ...

What are some techniques for styling a field when the div id is not specified?

I need to customize a data field within a table, but I am unable to locate or identify its div ID. Here is the page source: <tbody> <tr> <td style="font-size:12px; text-align:center;" name=""> <div sty ...

Incorporate sweetalert2 into your node.js and express.js project

Trying to incorporate sweetalert2 into my Node.js and Express.js project has not been successful so far. The error message I keep encountering is: swal is not defined ReferenceError: swal is not defined Here are my configurations index.js var express ...

Using AngularJS to bind to the 'src' property of an <img> tag

There is a table on my website with numerous rows, and each row contains a preview image that should appear in the top right corner when the mouse hovers over it. I attempted to insert an image tag with AngularJS binding for the URL in the src attribute l ...

Validating forms using Ajax, Jquery, and PHP, with a focus on addressing

I am currently working on processing a form using AJAX, jQuery, and PHP. However, I have encountered a 404 error while doing so. I tried searching for a solution before posting here but unfortunately couldn't find one. Below is the content of my .js f ...

Comparing Django forms to conventional forms

As I work on my Django website, I find myself torn between utilizing Django-Forms and sticking with the traditional hand-coded HTML forms. While HTML forms offer certain benefits that align with my needs, I must admit that I have also experienced advanta ...

Revise the Event Handlers as the DOM structure evolves

Similar Question: Tracking DOM changes in JavaScript I am working with backbone.js and dynamically generated templates. In addition, I am utilizing multiple jQuery UI plugins that interact with specific classes, such as slimScroll: $(function(){ $(& ...

How can I utilize Bootstrap to organize multiple div layers on top of each other?

I am trying to accomplish the following: layered div The rows are displaying correctly, but I'm having trouble positioning the top layer div (the one with the class map) in the correct place. It keeps pushing some of the rows to the side. How can I a ...

Is it acceptable to add customized (personalized) properties to DOM objects?

<div id="customDiv"></div> document.getElementByid('customDiv').myAttribute='customValue'; if('undefined'!==typeof document.getElementById('customDiv').myAttribute){ Would it be acceptable and compatib ...

Unusual challenge encountered when trying to switch colors and erase canvas content with button click

I am working on a code that utilizes a canvas for drawing purposes. My objective is to allow users to change the color of their drawings by clicking on specific buttons. The default color is black, but I have buttons set up for changing it to red or gree ...

Adding a JavaScript global variable into a <div> element within the HTML body

Here is an example HTML tag: <div data-dojo-type="dojox.data.XmlStore" data-dojo-props="url:'http://135.250.70.162:8081/eqmWS/services/eq/Equipment/All/6204/2', label:'text'" data-dojo-id="bookStore3"></div> In ...

increasing the size of a picture without resorting to a pop-up window

Struggling to implement a product details tab within a table that features a clickable image. When the image is clicked, it should enlarge but the width doesn't adjust accordingly. I'm using bootstrap 5.3 and can't seem to identify the root ...

Issues with datepicker functionality in forms

I have tested multiple datepicker plugins, such as the jQuery UI datepicker and others, but none of them seem to work with my current code. I am in need of a datepicker that can be added to this form of mine. Any suggestions or help would be greatly appr ...

Can you tell me the standard CSS easing curves?

When working with css, we have the option to incorporate easing for transitions, like this: transition: all .5s ease-in-out CSS provides predefined easings such as ease, ease-in, ease-out, and ease-in-out. We can also create a customized easing using a ...

Browser fails to recognize z-index settings for overlay elements

Within the structure of my webpage, there exists a navigation bar that includes a button. By clicking this button, users can toggle a full-screen overlay on and off. The button itself transforms from displaying three bars to a cross icon when activated. Fo ...

JavaScript - Validation Tool for Bootstrap

Currently utilizing a plugin called Plugin Link Attempting to validate whether at least one checkbox from a group has been selected. Unfortunately, the plugin does not offer this feature. After some research, came across a discussion by the plugin author ...

Show the JSON data on the table

Upon receiving a JSON String from the server as a response, I am presented with the following data: {"json":[{"title":"Example Title 1","description":"Morbi leo risus, porta ac consectetur ac"},{"title":"Example Title 2","description":"Morbi leo risus, po ...

Ways to attach JQuery UI Sortable widget to html content fetched through Ajax requests?

Here's a straightforward question for you. Take a look at my JavaScript/jQuery code snippet below: $('body .combo-table').sortable({ handle: '.grabber', opacity: 0.9, axis: 'y', start: function (e, ui) { ...

Achieving a layout of three columns and two rows (1 x 2 x 2) using flexbox

I am looking to achieve a specific layout using Flexbox. While I am comfortable with CSS, I want to challenge myself by learning how to implement this design using Flexbox for more concise and maintainable code. https://i.stack.imgur.com/QDVfT.png .ban ...

The website covers the entire page, but I prefer it not to

During the development of my website, I encountered a challenge: How to confine it within a wrapper or container set at 1000px rather than occupying the entire webpage. Below is the HTML code: <!DOCTYPE html> <div class="wrap"> <html> & ...