Dynamically adjust the height of a parent div to match its child div's height upon clicking using JavaScript

Within my div element (divChatContainer), there is a top div (divChatContainerTop) containing a "span" element. When this "span" element is clicked, I want the container div to resize to the height of the "divChatContainerTop" (essentially minimizing the chat window to only show the top section).

Here is the HTML code:

<div id="divChatContainer" runat="server" style="overflow-y: scroll; box-sizing: border-box; word-wrap: break-word; width: 20%; max-height: 35%; position: fixed; right: 0px; bottom: 0%; box-sizing: border-box; background-color: #EBECEF; border: solid #3A5896; border-width: 1px 0px 0px 1px; border-radius: 1px;">
  <div id="divChatContainerTop" style="text-align: right; box-sizing: border-box; width: 100%; padding: 3px;">
                <span style="float: left; box-sizing:border-box;width:50%;overflow:hidden;">Left</span><span id="spanChatMinimize" style="float: right">X</span>
            </div>
</div>

Here is the code from the external .js file:

document.getElementById('spanChatMinimize').addEventListener('click', function () {
     document.getElementById('divChatContainer').style.height = document.getElementById('divChatContainerTop').style.height + 'px';
});

During debugging, I observed that the function was not being executed. This might be due to an issue with the eventListener syntax or the naming of the "span" element (on MasterPage, they sometimes have names like "ctl00_elementName"). However, since the container element is statically placed in HTML outside the ContentPlaceHolder, this should not be the case.

EDIT: The following code successfully minimizes the chat window:

document.getElementById('spanChatMinimize').addEventListener('click', function () {
   document.getElementById('divChatContainer').style.height = '10px';
});

However, the following code does not have any effect:

document.getElementById('spanChatMinimize').addEventListener('click', function () {
  document.getElementById('divChatContainer').style.height = document.getElementById('spanChatMinimize').style.height + 'px';
});

It seems that I am unable to retrieve the height of "divChatContainerTop" or the "span" element. Is there a way to get the screen height instead of the height property?

Answer №1

Upon reflection, it appears that I misinterpreted the question last night. If you wish to determine the height of the div element without initially setting the height property, you can utilize one of the following methods:

document.getElementById('divChatContainerTop').clientHeight
document.getElementById('divChatContainerTop').offsetHeight
document.getElementById('divChatContainerTop').scrollHeight

Revised jsfiddle showcases three values and demonstrates a change in height upon clicking the span element.

For further information, please refer to:

Answer №2

It's simple! Ensure that you add your scripts at the end, just before the closing body tag. This way, the DOM will be able to find the elements you are referencing in the scripts, as they need to be parsed before. By following this, you can solve the issue of events not triggering. However, to achieve a chat-like function, you may need to make further adjustments to your code.

<html>
<body>
<div>
etc etc
<div>
<script>
// your script or external file
</script>
</body>
</html>

Sample

</head>
<body>
<div id="divChatContainer" runat="server" style="overflow-y: scroll; box-sizing: border-box; word-wrap: break-word; width: 

20%; max-height: 35%; position: fixed; right: 0px; bottom: 0%; box-sizing: border-box; background-color: #EBECEF; border: 

solid #3A5896; border-width: 1px 0px 0px 1px; border-radius: 1px;">
  <div id="divChatContainerTop" style="text-align: right; box-sizing: border-box; width: 100%; padding: 3px;">
                <span style="float: left; box-sizing:border-box;width:50%;overflow:hidden;">Left</span><span 

id="spanChatMinimize" style="float: right">X</span>
            </div>
</div>
<script>
document.getElementById("spanChatMinimize").addEventListener('click', function () {
alert('hi');
     document.getElementById('divChatContainer').style.height = document.getElementById('divChatContainerTop').style.height 

+ 'px';
});
</script>
</body>
</html>

EDIT:

To get the height of the div, you should use

document.getElementById('spanChatMinimize').clientHeight;

or document.getElementById('spanChatMinimize').offsetHeight;

This method works!

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

Oops! Looks like we have encountered an error: X is not recognized

As I navigate through the WebOS enyo framework, frustration starts to set in. The error message displayed in my log is causing me a headache. Despite examining samples within the framework, pinpointing the source of the error has proven to be a challenge. ...

Modifying a section of the source name using jQuery continues to occur repeatedly when the window is resized

I have written a piece of code that is designed to identify the src attribute of all images within a specific div and modify the src name when the window width is less than 900 pixels. The code works perfectly when the page is refreshed, but I encounter an ...

The source code in VS Code was not accurately linked

I'm currently facing an issue with running my angular2 project from vs code. Below are the contents of my tsconfig and launch.json files. tsconfig.json { "compilerOptions": { "declaration": false, "emitDecoratorMetadata": true, "experi ...

Each time the page is refreshed, the most recent form data submitted is continually appended to an array

I have implemented a post request to add input data from a form. The entered data is stored in an array variable burg and then displayed on my index.handlebars view. Everything works as intended, but when the page is refreshed without any input in the form ...

Setting the default value of a multi-select dropdown in AngularJS from the controller

Currently, I have implemented AngularJS multi select drop down functionality on my website. The code for this can be found at the following source: MultiSelectDropDown In my HTML page, I have included the same drop down twice and I want to customize the ...

Using the mt-downloader module in a Node application is a straightforward process

Hey there, I'm looking to incorporate the Multi downloader module into my project. I've checked out the GitHub link, but unfortunately, there are no examples provided on how to actually use this module. I came across this example and tried implem ...

Preventing further onClick events from occurring ensures that any new onClick events will not be triggered as well. To achieve

In the process of developing a script, I've encountered a situation where the original developers may have implemented event prevention or some other mechanism to block any additional clicks on certain table td elements. Even though their click trigge ...

Adjust the height of the second column in Bootstrap 4 textarea to fill the remaining space

I am facing an issue with my layout where I have 2 columns, one containing some inputs and the other only a textarea. The problem is that I want the textarea in the second column to extend and fill the remaining height of the first column, but so far I hav ...

Is it frowned upon or considered incorrect to achieve a horizontally centered page by adjusting the CSS properties of the html tag?

Is it considered wrong or frowned upon to center a webpage horizontally by adjusting CSS properties of the HTML tag? Sample CSS code: <style type="text/css"> html { width: 1200px; margin: 0px auto; background-color: ...

JavaScript hard-coded object functions as an argument, however it does not reference the global object

Recently, I encountered a strange issue while working with JQuery Flot. Initially, my code looked like this: var plot = null; function initPlot () { plot = $.plot("#graph", myData, { /* my options here */ }); } and everything was functioning correc ...

Attempting to extract tabular information from a script function housed within a webpage

I'm attempting to extract data from a table on the following website: When using BeautifulSoup to 'find' the 'table', I encountered a NoneType error since the table appears to be generated by a script function that fetches 90 rand ...

Struggling to get the findAndModify or Update functions to work properly in MongoDB. Despite fetching the desired data from my ajax call, I am unable to make any changes in the database

Here is the ajax code snippet: $(function () { $("#upvoteClick").click(function () { $.ajax({ type:"POST", data: {upvote: 2}, dataType: 'json', url:"http://localhost:9000/api/upvote" }).success(functi ...

Regular expression for precise numerical values of a specific magnitude (any programming language)

I have been searching for a solution to what I thought was a common problem but haven't found one yet. What I need is a regular expression that will fail on a specific number of significant figures (a Max), but pass for fewer than the Max. It should ...

Fade-In Effect for CSS Background Image

I'm currently learning CSS and I am trying to create an effect where, on hover over some text, the text disappears and an image fades in. I have been experimenting with different methods but haven't quite achieved the desired outcome. The text i ...

Is there a way to transfer the data from a `HtmlService.createHtmlOutput()` to a variable after clicking the `submit` button event?

The code snippet below is encountering an issue where arrayStored is not defined in the submit function. I attempted to retrieve the value of arrayStored using the e.parameter method, but it did not work as expected. As a newcomer to HtmlService, I am cu ...

What are the possibilities of utilizing a variable that is stated within composition to enable dynamic rendering?

I'm working on a Vue.js v3 project using the composition API. I have defined a variable in my setup like this: setup() { const showInvoiceItemForm = true; return { showInvoiceItemForm }; }, Now, I want to show a form when a button is click ...

Dealing with React Native: Navigating App Store Rejections and Embracing IPv6

In my react-native client for a website, the login page offers two options: manually enter the login code or scan it using a barcode scanner. I have extensively tested the app on real devices and emulators, and it's functioning correctly. However, all ...

When a td element is clicked, the Textbox will also be clicked

Similar Question: Dealing with jQuery on() when clicking a div but not its child $(oTrPlanning).prev().children('td').each(function () { this.onclick = setCountClick; }); When a TD element is clicked, the function setCountClick() i ...

File Upload yields a result of 'undefined'

Currently, I am utilizing Express File Upload. When attempting to send a post request to it, the error-handler returns an error indicating that no files were found. Upon logging console.log(req.files), it shows as undefined, causing the error to be sent ba ...

What is the best way to align text and images for list items on the same line?

HTML:- ul { list-style-image: url(https://i.sstatic.net/yGSp1.png); } <ul> <li>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit, consequatur?</li> <li>Lorem ipsum dolor sit amet, consectetur adipisici ...