Adjust the height of a div using jQuery once the AJAX call retrieves the data

There is a div that always matches the height of the adjacent div, depending on the content loaded in it. This setup was functioning properly until I implemented a search feature using jQuery. Now, when I perform a search, the element used in the jQuery calculation gets reloaded. I attempted to move the jQuery code inside the AJAX callback but that didn't resolve the issue either. What steps should I take next?

This is my current code:

$(window).resize(function() {
  var contentHeight = $(".news-content").height();
  $(".adjusted-content-height").css("height", contentHeight);
}).resize();

Here is my HTML structure:

  <div class="col-sm-4 padding-zero adjusted-content-height">
        <form action="ajax/result.php" id="search-form">
            <div class="search-field">
                <input class="search-input" type="text" placeholder="Search..." name="search-value">
                <input class="submit-button" type="submit" value="Search">
            </div>
        </form>
        <div class="downloads">
            <h4>Downloads</h4>
                <ul>
                    <li>
                        <a href="#">- PDF Example 1</a>
                    </li>
                    <li>
                        <a href="#">- PDF Example 2</a>
                    </li>
                    <li>
                        <a href="#">- PDF Example 3</a>
                    </li>
                </ul>
        </div>
    </div>
    <div class="col-sm-8 padding-zero" id="result"></div>

I also tried implementing AJAX with the following code:

$( "#search-form" ).submit(function( event ) {
  event.preventDefault();
  var $form = $( this ),
    searchValue = $form.find( 'input[name="search-value"]' ).val(),
    url = $form.attr( "action" );
  var posting = $.post( url, { searchValue: zoekvalue } );
  posting.done(function( data ) {
    $(window).resize(function() {
      var contentHeight = $(".news-content").height();
      $(".adjusted-content-height").css("height", contentHeight);
    }).resize();
    $("#result").html(data);

  });
});

I attempted moving the resize function outside to trigger changes without screen resizing, but unfortunately, this didn't have any effect either.

Answer №1

First and foremost, it's not advisable to mix different languages in your programming. Even as a native speaker of Dutch, I find it quite confusing to read code that combines multiple languages. To make things clearer, I've replaced all Dutch words with their English equivalents.

As A. Wolff rightly pointed out, mixing events is generally considered bad practice. Let's streamline some aspects of the code.

Initially, I removed the window resize function and instead implemented a call to resizeContainer. This function takes care of adjusting the size of your container and is also invoked during the window resize event.

function resizeContainer() {
  var contentheight = $(".news-content").height();
  $(".contentheightaltered").css("height", contentheight);
}

$(window).resize(function() {
  resizeContainer()
}).resize();

$( "#search" ).submit(function( event ) {
  // Prevent the form from submitting normally
  event.preventDefault();
  // Retrieve values from page elements:
  var $form = $( this ),
    searchvalue = $form.find( 'input[name="searchval"]' ).val(),
    url = $form.attr( "action" );
  // Send data using POST method
  var posting = $.post( url, { searchval: searchvalue } );
  // Display results in a div
  posting.done(function( data ) {
    $("#result").html(data);
    // Resize the companion container AFTER updating the data
    resizeContainer();
  });
});

This coding approach prevents code duplication by encapsulating it within a function that can be called repeatedly.

Answer №2

This code snippet was successful for me:

$( "#contenthoogteaangepast" ).on( "changeHeight", function() {
    $( this ).height($("#.news-content").height());
});

//execute the code inside the callback of the request: 
$( "#contenthoogteaangepast" ).trigger( "changeHeight" );

Alternatively, you can try:

function adjustHeight() {
    $( this ).height($("#.news-content").height());
}

//invoke the function inside the callback of the request: 
adjustHeight();

I have not tested the second option myself, but it is expected to work.

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

When clicking the button in ASP.NET MVC 5, the model is not defined

I have been struggling with an issue where a dropdownlist in a partial view, loaded via ajax into another view, is causing the Model to be null when trying to select an option and click a button. Despite the Model being populated for the dropdown, an error ...

Flashing background colors on a website

Can anyone explain why this code won't alternate the background color of my website between two different colors? <script type="text/javascript"> function blinkit() { intrvl = 0; for (nTimes = 0; nTimes < 3; nTimes++) { intrv ...

Tips for managing submitted data to a server in express?

In the process of sending a post request from my index.js to app.js upon a click event, I have the following code snippet: var data = { name: "Sarah", age: "21" }; var xhr = new XMLHttpRequest(); xhr.open("POST", "/", true); xhr.setRequestHe ...

Picture in the form of a radio button

Is there a way to use an image instead of a radio button in my AngularJS form? I have managed to hide the radio button using CSS, but it disables the checked event. How can I make the image clickable? position: absolute; left: -9999px; Here is the code s ...

At what stage of the Angular JS application life cycle is this code being loaded?

I am facing a difficult issue with the timing of Angular JS life cycle in relation to the code snippet below. There seems to be a random occurrence where controllers dependent on this code are loaded before it, leading to errors. Even after multiple atte ...

Is there a way to automatically mute the sound on a parallax website homepage video when I navigate back to the homepage from another page?

Is there a way to automatically mute the sound of the homepage video on a parallax website when navigating back to it from a separate page? If I click on the enter button and navigate to the "Our DNA" page, then click on the events link in the menu from t ...

Utilize GetXmlHttpObject for an AJAX request to interact with a PHP script

I am currently attempting to call a PHP file using the GetXmlHttpObject object and so far, I have had some progress. However, it seems that there is an issue with the URL variable. Do I need to handle the URL string in a different way? Here is the releva ...

Updating the value of each preceding sibling of every checked checkbox using jQuery upon form submission

After extensive research, I discovered that the most effective approach involves using a clever workaround to capture every tick and untick on a dynamic input row with multiple checkbox arrays. However, none of the solutions provided a viable method. I th ...

SmartCollection in Meteor generating unpredictable outcomes

When executing News.insert({name: 'Test'}) in the browser JS console, it caused {{count}} to increase from 0 to 1. Checking in mongo console using mrt mongo, db.news.find().count() also returns 1. However, after adding a record through the mongo ...

Displaying a pop-up window containing information retrieved from the console output

Upon user input in the form on my web application, an scp and ftp process is initiated that takes around 2-3 minutes to complete. The result page consequently experiences a similar delay in loading. To enhance user experience and provide real-time updates ...

Proportional fluid image grid with responsive design

After implementing various media queries, I've managed to create an image grid using Bootstrap 4+ that looks great on specific devices and layouts. Here's the reference code: .cmd-three-img-container { position: relative; margi ...

Utilizing ReactJS for Web Development with Enhanced Data Insights from Google

Utilizing Google Analytics and various tools, I've encountered an issue with the development of ReactJS. My goal was to collect analytics data from my website by using react-helmet to dynamically change the title and the HTML lang parameter based on t ...

Restricting JSON output using date and time values within the JSON object

Currently, I'm in the process of creating a play data reporting tool specifically designed for a radio station. The main concept involves retrieving play history from the playout software's API and manually adding tracks that were played outside ...

Determine the height of an image using JavaScript

How can I retrieve the height of an image in a JavaScript function? When I use the code: var image_height = $(image).height(); The value of image_height is 0, even though my image definitely has non-zero height. Is there a different method to accurately ...

Iterate over a collection of JSON objects and dynamically populate a table with statistical data

In JavaScript, I am trying to dynamically generate a table with statistical data from an API that contains an array of JSON objects. The JSON data has a property called "score" which is interpreted as follows: score: 5 (excellent); score: 4 (very good); ...

Tips on how to retrieve the current value of a scope variable in jQuery

When making a $http request to save data on the server and receiving a json response, I want to show an Android-style message using Toast for either success or failure based on the response. Initially, I set a scope variable to false $scope.showSuccessToa ...

Ajax request for username verification fails

I am currently working with Codeigniter 4 and ajax to validate the existence of a username, but I am encountering issues. Below is the code snippet that I used to check the availability of the username. My intention was to display a popup message (availab ...

Exploring the world of CouchDB through jQuery and AJAX POST requests while navigating

I am in the process of building a simple web application. Today, I installed Couch 1.3.1 and set up a database. I am currently trying to save a document to my local Couch (localhost:5984) using a POST request from a client browser that is also on localhost ...

What are the steps to create two frames using Twitter Bootstrap?

I'm just starting to work with Twitter Bootstrap and I need some help. Can someone assist me in creating a two-column layout inside the HTML, where the menu in the header stays visible even when scrolled down? I've included my HTML code below. Th ...

Transferring document using ajax technology

Attempted to upload a file using AJAX. form enctype="myltipart/form-data" id="pastTest-form" method="POST" action="upload.php"> <div class="feedback-form-inputs col-5"> <div class="input-field"> ...