Decrease the height of a div element from the top with the use of jQuery

My goal is to manipulate the height of the div #target when a specific event is triggered, either by reducing/increasing its height from the top or by hiding/showing its content. However, I'm struggling to find a solution to achieve this.

The current code adjusts the height from the bottom, but I need it to adjust the height from the top instead.

$(function() {

  $("button:first").on("click", function() {
    $("#target").css("height", "+=50px");
  });

  $("button:last").on("click", function() {
    $("#target").css("height", "-=50px");
  });
});
#target {
  background: purple;
  color: white;
  height: 300px;
  width: 200px;
}

div {
  float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <button>PLUS</button>
  <button>MINUS</button>
</div>
<div id="target">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
    dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
    dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

</div>

Answer №1

To modify the height of an element, you first need to obtain its current height, perform any necessary mathematical operations, and then update the CSS value accordingly.

Additionally, keep in mind that any adjustments made will impact the element from the bottom due to the default rendering behavior of browsers (top left to bottom right). Therefore, increasing or decreasing the height will affect the bottom of the element.

Give this code a try for adjusting the height:

$("button:first").on("click", function() {
    var target = $("#target"),
          targetHeight = target.height(),
          newTargetHeight = targetHeight + 50;

    target.height(newTargetHeight);
});

$("button:last").on("click", function() {
    var target = $("#target"),
          targetHeight = target.height(),
          newTargetHeight = targetHeight - 50;

    target.height(newTargetHeight);
});

Answer №2

Take a look at this bin: https://jsbin.com/wiqapadeza/edit?html,js,output I've utilized the margin property to address your problem:

$(function() {
 var top=0;
 $("button:first").on("click", function() {
    top=top+50;
    $("#target").css("height", "+=50px");
    $("p").css("margin-top", top);
  });
 $("button:last").on("click", function() {
  top=top-50;
    $("#target").css("height", "-=50px");
  $("p").css("margin-top", top);
 });
});

I hope this solution proves helpful for you:

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

The operation to set a nickname in Discord.js was unsuccessful due to insufficient permissions

Recently, I started using discord.js to create a simple bot. Whenever I try to change the nickname by calling message.member.setNickname("Another Nickname").then(console.log, console.log); I receive the following error message: { name: ' ...

Unable to reset disabled styling for CSS select box

My Windows 8 app consists of two pages: Page1.html and Page2.html. Page1 references ui-light.css and page1.css, while Page2 references ui-light.css and page2.css. In the ui-light.css file, there is a rule defined for the disabled state of select boxes. I ...

Finding the correct path for ts-loader with webpack version 2.2.1 within a script

When running the gulp task below, I encounter an error: Module not found: Error: Can't resolve 'app.ts' in 'wwwroot/js/admin' gulp.task("admin:js", function (done) { module.exports = { context: "wwwroot/js/admin", ...

Retrieving Information from JSON File Using a Variable (JavaScript/Discord.js)

While I was coding my Discord bot, I encountered an unexpected issue. Normally, after linking a JSON file, you can access data by using jsonFile.path to retrieve specific information. However, I faced a challenge where I needed to replace the path with a ...

Refresh text displayed on a button with the help of setInterval

I need help updating the text on a button with the id fixed-button at regular intervals. Here is the code I am currently using: <script type="text/javascript"> $(function() { $('#fixed-button').setInterval(function() { ...

Tailored NodeJS compilation incorporating JavaScript modules

Can NodeJS be built together with specific JavaScript modules? I am aware that for native modules, node-gyp can assist with this, but I am unsure about how to accomplish this with JavaScript modules. My goal is to use a custom application without needing t ...

Why isn't the show/hide feature in Jquery functioning properly?

I have a div that needs to be displayed after hovering over another element. These elements are not within the same div. The popup info should appear when an icon with the class .option_36_124 is hovered over. $(".option_36_124").hover(function(){ $(& ...

Why am I receiving an undefined value when I try to log the createdAnimal?

My main goal with this code is to successfully console.log(createdAnimal) and have the objectAnimal with specific parameters printed out. The following code snippet demonstrates the desired parameters: animalMaker('cat','flying',true); ...

While attempting to import modules in Visual Studio Code, an error message appears stating "Unexpected token {"

Greetings! I am currently using Visual Code to run my project and would like to share my code with you. In the file external.js: export let keyValue=1000; In the file script.js: import {keyValue} from './external.js'; console.log(keyValue); ...

What is the best way to continuously verify login and password credentials?

I am a newcomer to this industry and am facing a challenge with testing the process of entering the correct username and password using Selenium Webdriver. The current method of creating this process without a loop is extremely lengthy and monotonous. Here ...

Using Laravel to Transfer Information to a Controller through AJAX without a Form

I am facing an issue with sending data via JS to a Laravel controller on button click. I cannot use a form as the data is being generated dynamically. When attempting to send the data, I keep receiving an Internal Server Error (500), but I am unable to cat ...

Tips for transmitting form information in a fetch call

As I was developing a nodejs server, I encountered an issue with the POST call that involves sending form input data to a remote server. Despite everything else working fine, the form data was not being received by the server. Below is the code snippet in ...

A guide on coding the source tag script for a payment form in CodeIgniter, specifically for a JavaScript form

Scenario: I have a variable called $data['tabdata'] that I am passing from controller C to view V. This variable includes a script element pointing to http://example.com/1.js. Problem: The script in 1.js is not running properly in the view. This ...

Engage with React JS arrays of objects

I have a specific object structure that looks like the following: [ { "periodname": "Test", "periodtime": "" }, { "periodname": "", "periodtime&quo ...

Struggling to make even the most basic example work with TypeScript and npm modules

After stumbling upon this repository that made using npm modules within a Typescript program look easy, I decided to give it a try by forking it and making some changes. My goal was to add another package to get a better understanding of the process. So, I ...

Some elements in the DOM appear to not be rendering even though they are present in the HTML source code

As a newcomer to web development, I have stumbled upon a perplexing issue. In my usage of d3.js (specifically the script found here), I have been attempting to incorporate additional features. I modified my JavaScript code to include a simple <p> ele ...

Retrieve solely the text content from a JavaScript object

Is there a way to extract only the values associated with each key in the following object? const params = [{"title":"How to code","author":"samuel","category":"categoery","body":"this is the body"}] I'm struggling to figure out how to achieve this. ...

Can you transform text with accents into plain ASCII characters?

I am seeking a solution in Javascript to convert accented letters and various encodings into plain English ASCII characters. The goal is to achieve the following transformations: éclair ~becomes~ eclair bär ~becomes~ bar привет ~becomes~ privet ...

Reorganizing Bootstrap 5 columns as the screen size changes

I need to change the display order of columns in bootstrap Currently I have two columns side by side in one row like this: Col A - Col B (on all screens except mobile devices) However, when the screen size is reduced or viewed on a mobile device, I want ...

Customizing the DatePicker with a unique button in material-ui

For my current project, I am utilizing a Datepicker component. I am looking to incorporate a custom information button in the upper right corner of the calendar layout, similar to the example image provided below: https://i.stack.imgur.com/fHMbn.png Unfo ...