Adjustable div height: reduce until reaching a certain point and then begin expanding once more

Incorporating a hero section to display content is my current approach. The design adapts responsively utilizing the padding-bottom percentage strategy, along with an inner container that is absolutely positioned for central alignment of the content.

The challenge emerges when I aim to restore growth to the box upon reaching a specific breakpoint, let's assume 768px, especially on smaller window sizes.

Experiments with various snippets of js/jQuery code sourced online eventually yielded results. However, there is a limitation – the functionality only kicks in if the page loads within a window dimension of <768px. Should the page be loaded in a larger window, this resizing feature below 768px fails to activate.

This snippet showcases the HTML structure:

<div class="row row-home-hero" id="hero">
    <div class="cont">
        <h1>Title</h1>
        <h2>Subtitle</h2>
        <div class="cta-hero-home">
            <a href="#" class="cta-hero-link">» CTA1</a>
            <span class="cta-hero-spacer">or</span>
            <a href="#" class="cta-hero-link">» CTA2</a>
        </div>
    </div>
</div>

As for the JS implementation, it appears somewhat convoluted due to amalgamation from disparate sources. Furthermore, since Wordpress integration is in play, certain instances of $ had to be substituted with jQuery.

function screenClass() {
    if(jQuery(window).innerWidth() < 768) {
        jQuery('.row-home-hero').addClass('small-hero');
    } else {
        jQuery('.row-home-hero').removeClass('small-hero');
        jQuery('.row-home-hero').css("height", "");
    }
}

// Initiate the function.
screenClass();

// Reassessment upon window resize.
jQuery(window).bind('resize',function(){
    screenClass();
});
if (document.documentElement.clientWidth < 768) {
    var $li = jQuery('.small-hero'),         // Element caching
    startW = $li.width();  // Variable assignment
    function setMarginDiff() {
    area = 500000;
    width = jQuery('.small-hero').width();
    jQuery('.small-hero').height(Math.ceil(area/width/1.7));
    }
    setMarginDiff();                 // Execute post DOM load
    jQuery(window).resize(setMarginDiff); // Continuation during resize
}

The CSS element specifics are outlined below:

.row-home-hero {
    background-position: center;
    -webkit-background-size: cover;
    background-size: cover;
    background-repeat: no-repeat;
    position: relative;
    background-color: red;

}
.row-home-hero:before {
    display: block;
    content: "";
    width: 100%;
    padding-top: 46%;
}
.row-home-hero .cont {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 40%;
    text-align: center;
}
...
@media screen and (max-width: 768px) {
    ...
    .row-home-hero.small-hero {
        height: 500px;
    }
    .row-home-hero:before {
        display: block;
        content: "";
        width: 100%;
        padding-top: 0;
    }
}

Feel free to check out a functional demo via this link.

Your understanding is deeply appreciated!

Answer №1

I made a change by moving the block of code

if (document.documentElement.clientWidth < 768) {
inside the resize event. This ensures that it will be executed whenever the window is resized.

In its original state, the code would only run when the page loaded and if the screen size was less than 768 pixels. By adjusting it this way, it now dynamically adjusts whenever the window is resized.

Additionally, I consolidated all your code into a single, more concise function.

var breakpoint = 768;
var area = 500000;
var target = $('.row-home-hero');

$(window).on('resize', function() {
    if(window.innerWidth < breakpoint) {
        var width = target.width();
        target.addClass('small-hero');
        target.height(Math.ceil(area / width / 1.7));
    } else {
        target.removeClass('small-hero');
        target.css('height', '');
    }
})
.trigger('resize');

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

What is the best way to fetch the title property from my Campaign Contract for displaying it in the render method?

I'm currently working on a unique crowdfunding DApp that requires constant access to contract variables through function calls for retrieval purposes. The getDeployedCampaigns function is responsible for returning an array of deployed campaign addres ...

What is React.js's approach to managing CSS files?

Currently, I am enrolled in Bootcamp at Scrimba where they utilize an online platform for teaching various courses. One of the topics covered is React and involves working with CSS files. When working on my local machine, I typically use the index.css file ...

Utilizing CakePHP 3.0 with jQuery UI for an autocomplete feature

Seeking assistance on why the current code isn't functioning. The objective is to retrieve data from the index controller to search and obtain JSON data. No requests are being made, and there are no visible results. New to CakePHP 3.0, I am attemptin ...

Add an input element to a form fieldset by employing vue

In my form, I have a staged approach with 3 fieldsets that only appear when the "Next" button is clicked. Now, in the third fieldset, I need to add input elements based on keys extracted from an external json object. Data: data: () => ({ c ...

including a code snippet within a dropdown menu or embedding it in a clickable button

Hey there, my name is Wouter Sanders and I am currently learning to code! I recently finished creating a RAL color picker for a project I'm working on. The only issue I've run into is trying to embed the code in a menu or button so that it doesn ...

Convert object to JSON format using AJAX request to a PHP file

Despite receiving a 200 green response, my data is still not getting written to the json file and it remains blank. The JavaScript: $(function() { $('form#saveTemp').submit(function() { let savdAta = JSON.stringify($('form#save ...

The Angular filter is waiting for the ng-repeat to be populated

I have a filtering system that includes dropdown options to filter the displayed content. The content is fetched from a database and takes a few milliseconds to display. During this time, I encounter several errors related to the filtering system. Does any ...

Show a success message, clear the post data, and redirect back to the current page

I have a single web page with a contact form. When the form is submitted, I want it to redirect to the same page and display a success message that fades out after a few seconds. Additionally, I want the post data of the form to be cleared. The form also i ...

The jQuery toggleClass() function is not being applied successfully to content that is dynamically generated from

I've created an awesome collection of CSS-generated cards containing icons and text with a cool animation that expands upon tapping to reveal more icons and options. I carefully crafted the list to look and behave exactly how I wanted it to. But now, ...

Is there a way to activate a Superfish jQuery Menu with a click instead of a hover?

After doing some research on the internet, I came across an implementation of Superfish menu by Joel Birch that functions based on onclick instead of hover. I found a link on Github by Karl Swedberg which seems to be what I need. https://gist.github.com/ ...

Tips for ensuring that the click event function properly for numerous elements sharing the same class

I'm currently working on adding a flip effect to multiple tiles whenever a user clicks on them as part of building a dashboard-style webpage. I am having trouble making the click event work for all tiles with the same class name. Even though all the ...

Only IE7 seems to be experiencing a z-index problem with CSS that is not present on any

I’ve encountered a perplexing problem with CSS z-index in IE7 that I just can’t seem to solve. #screen { display: none; background-image: url('/images/bg.png'); background-repeat: repeat; position: fixed; top: 0px; le ...

Retrieve binary data of an image from an API and render it on an HTML page

I have been working on storing images in a MongoDB database and trying to display the response I receive from an Express API as an image on the client side. The image source URL looks like this: src="/image/data/5a44dde172aa021d107e7d33" When I try to wr ...

When using Owl Carousel in Chrome, the carousel unexpectedly stops after switching tabs

Hi there, I'm currently testing out the auto play feature in owl carousel. One issue I've encountered is that when I switch to another tab in Chrome and then return to my webpage with the carousel, it stops functioning unless I manually drag the ...

Achieving a Transparent Flash overlay on a website without hindering its usability (attention, interaction, form submissions, etc.)

Currently, we are attempting to overlay a transparent flash on top of an iframe which loads external websites. Is there a method to configure the page in a way that allows the transparent flash to be displayed while still allowing interaction with the und ...

Is it possible to receive a unique value error even when providing the correct key value in a map?

I encountered an issue while using a map function with an array in my application. Even though I have provided a unique key, Google Chrome console is still showing an error related to the unique key. Error Each child in a list should have a unique "ke ...

Enhance Form within React Calendar

I have developed a calendar using React and Redux. When I click on an empty date, a modal pops up allowing me to add an event. However, I am struggling to implement the functionality to edit that event by clicking on it later. Can someone guide me on the c ...

Extracting information from within Ajax's Jsonp

How can I retrieve data from the Ajax function(result)? Why isn't this app working? Please assist me. function star(a) { var res; $.ajax({ url: 'https://api-metrica.yandex.com/analytics/v3/data/ga?end-date=today&ids=ga%3A35 ...

Altering the context of Javascript script execution

I needed to switch the JavaScript execution context from the parent window to the child window. I was able to successfully load my script objects and functions into the child window context, however, I encountered difficulty in making third party libraries ...

NextJS: encountered an error with fallback enabled

I have my NextJS setup on Vercel and here is how I configured getStaticPaths: const paths = posts.map((post) => ({ params: { player: post.player, id: post.id }, })) return { paths, fallback: true } However, when I set the fallback to true, I ...