Expanding the footer dynamically using jQuery and CSS

Currently, I am working on a webpage where the footer expands based on a specific event. My challenge is to ensure that the footer grows in proportion to the available space on the page. You can take a look at my code snippet or the corresponding jsFiddle link. What I want is for the grey footer to stretch all the way up to the colored elements with variable height instead of being fixed at 20% as it currently appears. One approach could involve calculating the combined height of the elements above, but that doesn't seem like an optimal solution.

Check out the live demonstration on jsFiddle here

            <html>
            <head>
                <style type="text/css">
                    body #pagePlaceHolderOuter {
                        background: #FFFFFF;
                        height: 100%;
                        left: 0;
                        position: absolute;
                        top: 0;
                        width: 100%;
                    }

                        body #pagePlaceHolderOuter #pagePlaceHolderInner {
                            height: 100%;
                            margin: 0 auto;
                            max-width: 1000px;
                            min-width: 700px;
                            width: 70%;
                            position: relative;
                        }

                            body #pagePlaceHolderOuter #pagePlaceHolderInner .div1 {
                                width: 100%;
                                height: 100px;
                                background: blue;
                            }

                            body #pagePlaceHolderOuter #pagePlaceHolderInner .div2 {
                                width: 100%;
                                height: 120px;
                                background: green;
                            }

                            body #pagePlaceHolderOuter #pagePlaceHolderInner .div3 {
                                width: 100%;
                                height: 60px;
                                background: red;
                            }

                            body #pagePlaceHolderOuter #pagePlaceHolderInner .footer {
                                background: gray;
                                bottom: 0;
                                height: 10%;
                                position: absolute;
                                width: 100%;
                            }
                </style>
            </head>
            <body>

                <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
                <script>
                    $("#btn").click(function () {
                        $('body #pagePlaceHolderOuter #pagePlaceHolderInner .footer').css('height', '20%');
                    });
                </script>

                <div id="pagePlaceHolderOuter">
                    <div id="pagePlaceHolderInner">
                        <button type="button" id="btn">Click Me!</button>
                        <div class="div1">I have a dynamic height</div>
                        <div class="div2">I have a dynamic height</div>
                        <div class="div3">I have a dynamic height</div>

                        <div class="footer">Footer</div>
                    </div>
                </div>

            </body>
            </html>

Answer №1

Instead of computing the total space occupied by all elements beforehand, a more efficient approach is to calculate the height of the element directly preceding the target one and determine its offset().top. By adopting this method, I was able to determine the spacing required (ensuring that the footer in the HTML is positioned right after the preceding element or adjusting the jQuery code accordingly). This allows for a seamless toggle between the default value and the addition of the calculated space. Check out the Updated jsFiddle for reference.

$("#btn").click(function (e) {
    var prev = $('.footer').prev(),
        winHeight = $(window).height(),
        calcTop = $('.footer').height() == Math.round(winHeight / 10) ? 
            (winHeight - prev.offset().top - prev.height()) : "10%";
    $('body #pagePlaceHolderOuter #pagePlaceHolderInner .footer').css({
        'height': calcTop
    });
});

It's worth mentioning that CSS transitions were employed for smooth transition effects instead of using jQuery, both to enhance performance and facilitate future modifications.

If you only need to adjust the position without affecting the element's height, toggling the bottom value can achieve the desired outcome. View a demonstration of this in action here.

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

Leveraging ng-options with various objects in AngularJS

I have an array called 'things' that contains different objects. For example, two different objects are as follows: {name: 'book', value: '5', color: 'blue'} and {name:'pen', length: '10'} ...

Filtering multiple rows in a table using Javascript

I'm currently working on creating a filter that can filter based on multiple inputs, with each input filtering in a separate column. Here is the JavaScript & code I am using: function myFunction(column, input) { var filter, table, tr, td, i, t ...

Determine whether a specific property value within an array, which is nested within an object, actually exists using Javascript

I am attempting to verify the existence of a property in the given object: var objects = { '1': [ 'A-TheA', 'B-TheB' ], '2': [ 'A-TheA', 'B-TheB' ] } I am seeking to confirm whether &apo ...

Transform the look of an inactive hyperlink

Can the visual style of an HTML link be modified when it is disabled? For instance, by implementing something like this: a.disabled { color:#050; } <a class="disabled" disabled="disabled" href="#">Testing</a> The code snippet above appears ...

Exploring nested objects in Javascript through iterating and extracting all properties in a continuous loop (Updated)

In my code, I created an object with two sub-objects structured like this: var testObject = { "page":{ "type": "ePurchase", "title":"Purchase confirmation" }, "user": { "name": ...

Challenges with implementing @Html.EditorForModel

Currently, I am developing a web application using asp.net's mvc-5 framework. In this project, I have implemented the following model class: public class Details4 { [HiddenInput(DisplayValue=false)] public string RESOURCENAME { se ...

Guide on creating a dual range slider with native HTML range input and Vue.js?

Seeking assistance in creating a double range slider with two handles for the native HTML input=range and Vue.js. Current progress: https://jsfiddle.net/ Javascript (Vue.js) var vm = new Vue({ el: '#app', data: { minAngle: 10, maxA ...

What does dist entail?

I am currently utilizing gulp to create a distribution folder (dist) for my Angular application. After consolidating all the controllers/services JS files and CSS, I am now faced with handling the contents of the bower folder. In an attempt to concatenat ...

`Can you please explain how to retrieve the current state in React?`

PROGRAMMING ISSUE: initializeState: function() { return { title: "", description: "" } }, submitForm: function() { var newTask = { title: this.state.title, description: this.state. ...

Query a MongoDB collection by applying filters using data from a separate collection

Being new to MongoDB, I have created the following schemas: const postSchema = new mongoose.Schema( { content: { type: String, required: true, index: "text" }, author: { type: ObjectId, ref: "User", required: true, i ...

Retrieve the parent document for every item within a Firebase collection group

Transitioning from an SQL background to document storage, I am currently navigating through a Firebase database structure that looks like this: John (doc) Restaurant Reviews (collection) Review 1 (doc) Review 2 (doc) Paul (doc) Restaurant Reviews ...

Working with high-resolution images on HTML5 canvas

I am faced with a challenge of incorporating a 15000x15000 px vector image as the backdrop for my canvas project. It is essential to crop specific sections of this image swiftly and consistently, especially within requestAnimationFrame. My current method ...

Resize a circle upon hovering while keeping the same thickness of the border

I'm working on creating a circle with just a border (no background) that scales on hover. Here's the code I have so far: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <link type="text/css" rel="stylesh ...

Guide to fetching JSON data following an AJAX submission of a form to the database

I am having trouble with my code that inserts data into a database using Ajax. I want the client side to automatically retrieve a callback JSON after saving the data to the database. However, the JSON is not showing in the console. Can anyone help me? Thi ...

Transform tree-like JSON array with nested arrays into flat JSON array

I have an array tree in JSON format with potentially unlimited nesting: const namesArrayTree = [ { "name": "Peter" }, { "name": "folder1", "isArray": true, " ...

Unable to display the column data labels in Highcharts due to the incorrect formatting being presented

I'm having trouble displaying the datetime format at the top of a column in my chart. Although the tooltip shows the correct data when hovering over the columns, the labels are not formatted properly. Received output - 86340000 Expected output - 23: ...

Button group malfunctions on smaller screens

After integrating a button group into my new website, I noticed that the first two buttons stop functioning properly on smaller screens. Surprisingly, if I remove the text-center div, all buttons cease to work entirely. Despite attempting various solution ...

Node.js process becomes unresponsive while attempting to read from a FUSE file that is causing

Operating a nodejs webserver where files are read and content served. Certain files are FUSE virtual files that can cause reads to block for extended periods as their supporting services await data delivery. An issue arises when 5 of these read requests a ...

The CSS Validator does not recognize the CSS pointer-events and appearance properties

I'm a CSS beginner who recently created an app. I've encountered some errors and warnings when validating my CSS code: https://i.stack.imgur.com/g4MUz.png https://i.stack.imgur.com/Es1DE.png Could someone kindly explain these errors and warnin ...

Finding the length of a filter in an AngularJS directive

I'm trying to figure out how to retrieve the value of filtered.length within my custom directive called my-dir. <li my-dir ng-repeat="result in filtered = (results | filter:query | orderBy: 'title')"> <h1>{{ result.title }}& ...