Creating Uniform Heights Across Devices with Responsive Design Strategies

I am struggling with a height consistency issue that I cannot figure out. The problem can be seen in this Fiddle: FIDDLE

Here is the code snippet:

$(document).ready(function() {
    if ($(window).width() > 768) {
    $(window).ready(function() {
        var mainHeight = $('.main').height();
        $(".block-wrap").height(mainHeight);
    });
    }else{
        $('.block-wrap').css('height','auto');
        }
});

$(document).ready(function() {
    if ($(window).width() > 768) {
    $(window).resize(function() {
        var mainHeight = $('.main').height();
        $(".block-wrap").height(mainHeight);
    });
    }else{
        $('.block-wrap').css('height','auto');
        }
});

The objective is to make the 'block-wrap' div match the height of the 'main' div. It works as intended until a media query is applied. In such cases, the 'block-wrap' continues to take its height from 'main', while I would prefer to set it to auto height, as attempted in the JavaScript section.

Currently, the script functions correctly when the window width is below 768px, but only upon page refresh and not during resizing.

Answer №1

It seems like there are some issues with your JavaScript code, most notably the duplication error that occurred. To address this problem, I have made the following adjustments:

  • Eliminated the duplicate section in the code.

  • Enclosed all code within a single

    $(document).on("ready", callback);
    event handler.

  • Incorporated a resize event listener to ensure that the height of your .block-wrap div updates whenever the user resizes the window. This functionality allows for real-time adjustments rather than only updating on page load.

UPDATE:

  • Implemented a call to the resize(); function after the resize event handler to dynamically resize the .block-wrap div upon page load.

Keep in mind that it is possible to achieve these results using CSS without relying on JavaScript.

Below is the modified and functioning code:

$(document).ready(function () {
    function resize() {
        if (window.innerWidth >= 768) {
            var mainHeight = $('.main').height();
            $(".block-wrap").css({
                "height": mainHeight
            });
        } else {
            $('.block-wrap').css({
                'height': 'auto'
            });
        }
    }
    resize();
    $(window).on("resize", function () {
        resize();
    });
});

I also adjusted the media query max-width condition by one pixel:

@media only screen and (max-width: 768px) { ... }

Check out the demo here: http://jsfiddle.net/TiagoMarinho/SR5Wz/10/

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

Guide on displaying the AJAX response within an HTML or JSP element pulled from a database

description of image 1description of image 2How can I display an AJAX response from a database (map) on a JSP screen? I am able to retrieve the response in the browser console but unsure how to visually render it on the JSP page, like in a table or any ot ...

Mistaken data retrieved from a knockout observable array

My current project involves developing a web application using Asp.Net Mvc, where I am utilizing knockout Js to retrieve and send data to the Html View after manipulating the data. For instance, let's consider the data in an array called datainput: ...

``save changes to database in real time without requiring a page refresh or navigating

I have created a PHP page that includes a table displaying records from a MySQL database. One of the fields in the table, namely "housing," can have two possible values: 0 and 1. When a student is housed, the value of this field is set to 1; otherwise, it ...

Navigate to a PDF file from an HTML5 application using PhoneGap by accessing an external link

Can anyone help me figure out what I'm doing wrong here? Essentially, I am trying to open a PDF in Google Viewer: <a id="pdflink" href="https://docs.google.com/viewer?url=http://pdpdpd.pdf" target="_blank">Pdf</a> When it opens in the vi ...

What is the correct way to update an array of objects using setState in React?

I am facing an issue where I have an array of objects that generates Close buttons based on the number of items in it. When I click a Close button, my expectation is that the array should be updated (removed) and the corresponding button element should dis ...

Prevent specific fields from being saved in Node MongoDB native

When working with MongoDB and using the node mongodb native driver to insert documents, I have encountered an issue. The objects I am inserting have fields that I do not want to be saved in the database: var x = { field: 'value', _nonPersist ...

display a screen based on conditions using conditional rendering techniques

As I work on the onboarding screen, my goal is to navigate to a different screen when the last item is displayed or clicked instead of just logging "last item" on the console. Here's the code snippet: import React,{useState,useRef} from 'react&a ...

Is it better to execute a function before using useState in React?

I am currently developing a random word generator using Next.js. The state of the three randomly generated words is being managed with the help of useState. However, I encountered an error message from React when I tried to implement it in the following ma ...

Best practices for implementing localization in AngularJS 1.5.x

Visit this link When working with newer versions of the framework (>=1.4.0), it is recommended to utilize the built-in i18n tools. For older versions (<1.4.0), angular-translate is a suitable option. The documentation provides detailed steps for ...

What is the process of utilizing a <li> for a hover selector in jquery?

I've encountered an issue with a list that I am trying to modify its content when hovering over them. Despite using the id as a selector for triggering the hover function, all list items change color instead of just the intended one. The challenge lie ...

IE browser not sending ajax request with jQuery's $.getJSON method (works fine in FF and Chrome)

While using IE9's debug mode, I placed a breakpoint on the first line below and it was hit successfully. However, the breakpoint set on the first line in the callback function is never triggered. Upon checking the Network tab, I noticed that there is ...

Opening a controller in a dialog using AngularJS with dynamically loaded templates

Experimenting with AngularJS has been a fun experience for me. I've been using a controller and a templateUrl to handle everything seamlessly :) At the moment, my layout consists of just the <div ng-view></div> directive where all content ...

"Exploring the dynamic features of jQuery's mobile listview and

As I work on creating a mobile app using jQuery Mobile, I find myself facing some challenges. Despite my efforts and attempts at different methods, I have not been successful in achieving the desired functionality. Specifically, I am trying to implement a ...

The $scope in Angular doesn't seem to be working as expected in the callback function, despite using $scope

I'm currently working on converting the JSFiddle found here to AngularJS: http://jsfiddle.net/danlec/nNesx/ Here is my attempt in JSFiddle: http://jsfiddle.net/leighboone/U3pVM/11279/ var onAuthorize = function () { updateLoggedIn(); $scope. ...

Unable to pass a $scope variable into an Angular filter due to interpolation error

In my Angular application, I have a filter that takes a user ID and converts it into a user image URL. It does this by checking if the ID exists in an array and returning the corresponding image URL from the array passed to the filter. The filter is fu ...

Button styled with Bootstrap positioned at the top right corner

Currently, my Bootstrap page structure is as follows: <div class='container'> <div class='row'> <div class='col-sm-6 col-md-4 col-lg-3'> <p>column1</p> </div> ...

Error: The route configuration must include a "path" parameter when exporting imports in Vue Router

Important Information: The Index/Search/Features modules all share the same code structure, with different names. Each module consists of a path, component, name and meta as seen below. notes/routes/routes.js import Index from './index' import ...

Can you explain the variance between using querySelector() and getElementById/getElementsByClassName/getElementsByTagName()?

I'm confused about the distinction between using querySelector() and getElementById(). From what I understand, querySelector is able to retrieve an element using any selector, giving it more flexibility. Are there additional contrasts between the two ...

Using three.js to add an image onto an already existing object

I attempted to modify the appearance of an object by adding an image, but all my tests resulted in a white object... The goal is simply to apply an image to the entire object. Here is my test code: var obj = scene.getObjectByName('wall_20_118') ...

putting a division element above a image carousel

Is there a way to overlay a div tag on top of a slideshow, similar to the one shown in this link? In the example provided, a div with the title "DISCOVER THE JOY OF COOKING" is positioned over a slideshow. Any tips on how I can achieve this effect? ...