Table of Contents
Tutorial on hiding elements highly based on another element
Home Web Front-end HTML Tutorial Tutorial on hiding elements highly based on another element

Tutorial on hiding elements highly based on another element

Oct 05, 2025 pm 11:45 PM

Tutorial on hiding elements highly based on another element

Tutorial on hiding elements highly based on another element

This article will explain how to use JavaScript to dynamically hide or display another element based on the height of one container element (such as the Show More button). The core idea is to determine whether to hide the "Show More" button by getting the height of the container element and comparing it to the preset maximum height. This method is simple and effective, which can improve the user experience and avoid unnecessary element display.

In web development, you often encounter the need to dynamically adjust the display of elements according to the content of the page. For example, when the content height of a container exceeds a certain limit, the "Show More" button is displayed, otherwise the button will be hidden to avoid unnecessary clicks from the user. The following will introduce how to implement this function in detail.

HTML Structure

First, we need a container element, such as a div, to store content. At the same time, a "Show More" button is also needed.

 <div class="ccontainer" id="ccontainer">
  <p id="context"> Content 1 </p>
  <div class="img" id="cntimgcon">
    <img  src="/static/imghw/default1.png" data-src="images\image2.jpg" class="lazy" id="cntimgp1" alt="Tutorial on hiding elements highly based on another element" >
  </div>
  <p id="context"> Content 2 </p>
</div>
<button class="showmore"> Show more</button>

In this example, ccontainer is the id of the container element and showmore is the class of the "Show More" button.

JavaScript Code

Next, use JavaScript code to determine the height of the container and hide or display the Show More button based on the height.

 const btn = document.querySelector('.showmore'); // Get the button element const container = document.querySelector('#ccontainer'); // Get the container element const height = container.clientHeight; // Get the actual height of the container const maxHeight = 530; // Set the maximum height if (height <p> <strong>Code explanation</strong></p><ol>
<li> <strong>Get elements:</strong> Use the document.querySelector() method to get the "Show More" button and container elements respectively.</li>
<li> <strong>Get height:</strong> Use the clientHeight property to get the actual height of the container. The clientHeight property returns the visible height of the element, including the inner margins, but does not include scrollbars and borders.</li>
<li> <strong>Set maximum height:</strong> define a variable maxHeight to set the maximum height of the container.</li>
<li> <strong>Conditional judgment:</strong> Use the if statement to determine whether the height of the container is less than or equal to the maximum height.</li>
<li> <strong>Hide or Show Buttons:</strong> If the container height is less than or equal to the maximum height, set the display style of the Show More button to none, thus hiding the button. Otherwise, set the display style to an empty string '' to display the button.</li>
</ol><p> <strong>Things to note</strong></p>
  • Make sure to execute JavaScript code after the DOM is loading. You can place the code at the bottom of the <script> tag, or use the DOMContentLoaded event listener.</script>
  • If the content of the container is loaded dynamically, you need to re-execute this JavaScript code after the content is loaded to ensure that the button displays correctly.
  • The value of maxHeight can be adjusted according to actual needs.
  • display = '' will restore the default display attribute value of the element, usually inline, block, or inline-block, depending on the type of element.

Complete example

 


<title>Hide elements based on height</title>
<style>
  .ccontainer {
    width: 300px;
    border: 1px solid #ccc;
    padding: 10px;
    overflow: hidden;
    max-height: 530px; /* Initial maximum height, only for visual effects*/
  }
</style>



<div class="ccontainer" id="ccontainer">
  <p id="context">This is an example piece of content that demonstrates how to hide the Show More button based on the height of the container. The "Show More" button will only be displayed when the content of the container exceeds a certain height. </p>
  <p id="context">This is an example piece of content that demonstrates how to hide the Show More button based on the height of the container. The "Show More" button will only be displayed when the content of the container exceeds a certain height. </p>
  <p id="context">This is an example piece of content that demonstrates how to hide the Show More button based on the height of the container. The "Show More" button will only be displayed when the content of the container exceeds a certain height. </p>
</div>

<button class="showmore">Show more</button>

<script>
  const btn = document.querySelector(&#39;.showmore&#39;);
  const container = document.querySelector(&#39;#ccontainer&#39;);
  const height = container.clientHeight;
  const maxHeight = 530;

  if (height <= maxHeight) {
    btn.style.display = &#39;none&#39;;
  } else {
    btn.style.display = &#39;&#39;;
  }
</script>


Summarize

Through the above steps, the function of dynamically hiding or displaying the "Show More" button according to the height of the container element can be achieved. This method is simple and effective, which can improve the user experience and avoid unnecessary element display. You can adjust according to actual needs, such as using the CSS class name to control the display status of the button, or using animation effects to smoothly display or hide the buttons.

The above is the detailed content of Tutorial on hiding elements highly based on another element. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to make text wrap around an image in html? How to make text wrap around an image in html? Sep 21, 2025 am 04:02 AM

UseCSSfloatpropertytowraptextaroundanimage:floatleftfortextontheright,floatrightfortextontheleft,addmarginforspacing,andclearfloatstopreventlayoutissues.

How to create a hyperlink to an email address in html? How to create a hyperlink to an email address in html? Sep 16, 2025 am 02:24 AM

Usemailto:inhreftocreateemaillinks.Startwithforbasiclinks,add?subject=and&body=forpre-filledcontent,andincludemultipleaddressesorcc=,bcc=foradvancedoptions.

How to add a tooltip on hover in html? How to add a tooltip on hover in html? Sep 18, 2025 am 01:16 AM

UsethetitleattributeforsimpletooltipsorCSSforcustom-styledones.1.Addtitle="text"toanyelementfordefaulttooltips.2.Forstyledtooltips,wraptheelementinacontainer,use.tooltipand.tooltiptextclasseswithCSSpositioning,pseudo-elements,andvisibilityc

CSS tips: precisely hide specific text content without affecting parent elements CSS tips: precisely hide specific text content without affecting parent elements Sep 16, 2025 pm 10:54 PM

This tutorial details how to use CSS to accurately hide specific text content in HTML pages to avoid the problem of the entire parent element being hidden due to improper selectors. By adding exclusive CSS classes to the wrapping elements of the target text and using the display: none; attribute, developers can achieve refined control of page elements, ensuring that only the required parts are hidden, thereby optimizing page layout and user experience.

How to set the lang attribute in HTML How to set the lang attribute in HTML Sep 21, 2025 am 02:34 AM

Setthelangattributeinthehtmltagtospecifypagelanguage,e.g.,forEnglish;2.UseISOcodeslike"es"forSpanishor"fr"forFrench;3.Includeregionalvariantswithcountrycodeslike"en-US"or"zh-CN";4.Applylangtospecificelementswhe

Capture mousedown events with parent element containing cross-domain iframes: Principles and limitations Capture mousedown events with parent element containing cross-domain iframes: Principles and limitations Sep 20, 2025 pm 11:00 PM

This article explores the challenge of capturing mousedown events on parent divs containing cross-domain iframes. The core problem is that browser security policies (same-origin policy) prevent direct DOM event listening on cross-domain iframe content. This type of event capture cannot be achieved unless the iframe source domain name is controlled and CORS is configured. The article will explain these security mechanisms in detail and their limitations on event interactions and provide possible alternatives.

JavaScript external function call difficulty analysis: script location and naming specification JavaScript external function call difficulty analysis: script location and naming specification Sep 20, 2025 pm 10:09 PM

This article explores two common problems when calling external JavaScript functions in HTML: improper script loading time causes DOM elements to be unready, and function naming may conflict with browser built-in events or keywords. The article provides detailed solutions, including tweaking script reference locations and following good function naming specifications to ensure JavaScript code is executed correctly.

What is the difference between object and embed tags in html? What is the difference between object and embed tags in html? Sep 23, 2025 am 01:54 AM

Theobjecttagispreferredforembeddingexternalcontentduetoitsversatility,fallbacksupport,andstandardscompliance,whileembedissimplerbutlacksfallbackandparameteroptions,makingitsuitableonlyforbasicusecases.

See all articles