Verify whether the div contains a height style. If it does, refrain from altering the height

In my design, I have a main container div with a set height (which may change depending on css media query). There is also a parent div where the user can input a height value (usually in percentage, occasionally in pixels). The child divs allow the user to enter percentage and pixel values for their heights.

My goal is:

  1. If the user does not set a height for the parent div, all child divs should adjust their height based on their content.

  2. If the user sets a height for the parent div but not for the children, the child divs should be evenly distributed.

I have achieved points 1 and 2.

Now I am working on the following:

  1. If the user sets a height for the parent div, all child divs should be divided evenly, except for those with specific height values set by the user.

Here is a link to a fiddle showing my current progress:

http://jsfiddle.net/andyderuyter/qepqdmer/

$('.child').each(function() {

  var numOfDivs = $(".child").length;
  var parentHeight = $(this).parent().height();
  var newChildHeight = parentHeight / numOfDivs;
  var hasHeightValue = $(this).height().length;

  if (parentHeight == 700) {
    $('.child').height(newChildHeight);
  }

});
.grandparent {
  height: 700px;
}
.parent {
  height: 100%;
  background-color: black;
  text-align: center;
}
.child-1 {
  background-color: orange;
}
.child-2 {
  background-color: purple;
  color: white;
}
.child-3 {
  background-color: violet;
}
.vertical {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="grandparent">
  <div class="parent">
    <div class="child child-1">
      <div class="vertical">Div 1</div>
    </div>
    <div class="child child-2">
      <div class="vertical">Div 2</div>
    </div>
    <div class="child child-3" style="height:25%;">
      <div class="vertical">Div 3</div>
    </div>
  </div>
</div>

Answer №1

If the objective is to establish a consistent height for all divs that do not have an explicit height set in a style tag (excluding any CSS settings), one can utilize a jQuery attribute filter like [style*=height]:

let childDivs = $('.child'); // retrieve all child elements
let height = childDivs.parent().height();
let withHeight = childDivs.filter('[style*=height]'); // gather elements with a height set in their style tag
withHeight.each(function(){height -= $(this).height();}); // deduct those heights from the parent's height
let otherDivs = childDivs.not(withHeight); // obtain remaining elements without a height tag
otherDivs.height(height / otherDivs.length); // adjust all elements to have parent height divided by number of other elements

JSFiddle Example

While using classes to manage custom heights is generally recommended, even when done dynamically by users, the above code snippet should suffice for this particular scenario.

Answer №2

It would be beneficial to add a specific class when setting the height of an element, as this allows for easy identification using hasClass() method on the div.

Alternatively, you can utilize the attr('style') function and search for the presence of height in the styling.

function isHeightSet(styletext){
  if(typeof styletext != 'undefined'){
    testStyleL = styletext.toLowerCase(),
    testH = testStyleL.indexOf('height'),
    test1 = false;
    if(testH >= 0){
       return true;
    }
  } 
  return false;
}

var test1Style = $('.test1').attr('style'),
test1 = isHeightSet(test1Style);

var test2Style = $('.test2').attr('style');
test2 = isHeightSet(test2Style);

$('.test1').html('Height : '+test1Style + '/' + test1);
$('.test2').html('Height : '+test2Style + '/' + test2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="test1" style="Height:120px;">Test1</div>
<div class="test2" ><span>Test2</span></div>

Answer №3

I made some adjustments to your jsFiffle example at http://jsfiddle.net/001z9xvk/2/. Previously, the height was being set for all elements with the class of .child, regardless of whether they actually had that class or not. I fixed this issue by changing $('.child').height() to $(this).height().

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

Several jquery functions fail to operate as expected

After spending the entire day attempting to troubleshoot my code, I am still unable to figure out why it's not functioning properly. I have several jQuery functions, but when I try to combine them, one of them fails to work. Here is the current state ...

determining the validity of a knockout validation

Why am I getting an error when trying to use the isvalid method inside viewmodel? It says isvalid is not a valid function. function Student(name,age,country) { var self = this; self.Name = ko.observable(name).extend({ required ...

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 ...

Custom CSS Editor for Third Party Visual Studio Themes

Are there any reliable and user-friendly style sheet editors that can be integrated with Visual Studio? I recently came across a resource editor that surpassed the default version for opening .resx files. This got me thinking, there may be some advanced ...

Swapping out the context of JavaScript's this keyword

After researching scope and context through various articles, I still have a question lingering in my mind. If you take a look at my JSFiddle here, you'll see what I'm working with. My goal is to convert my functions to arrow functions and replac ...

Reverse the orientation of the SVG image, for instance, the graph

I've been experimenting with creating a bar graph using SVG, but I'm struggling to understand how it works. I tried rotating an existing graph upside down, but there seems to be a small offset. You can view the corresponding jsfiddle here - http: ...

Shifting the position of personalized tabs using Jquery

I have created some basic HTML/CSS tabs and I want to move to the next tab by clicking a link at the bottom of every tab. HTML <ul class="tabs"> <li class="active"> <a href="#">Explainer (2mins)</a> <div class=" ...

Issues with ng-show functionality occurring during the initialization of the webpage

While working on a webpage using HTML, CSS, and Angular.js, I encountered an issue where the page content would not display properly upon loading. The objective was to show selected content based on user choices from a dropdown menu. Although the filtering ...

Tips for saving ajax data in a line

I need to showcase data fetched from my database using jQuery.ajax() regularly, with each data entry having a title and description. To achieve this, I plan on utilizing setInterval(func, 5000). What I require is a JavaScript container (could be an array ...

Clicking 'Back to Top' within an accordion

On my webpage, I have two scrolls present. One is clearly visible on the page (not loaded with ajax), while the other one is located inside an accordion. Both of them share the same class names. I want these scrolls to always be positioned at the top. I&a ...

I received a value of NoneType from jQuery within my Django project

I am looking to create a feature that updates the graph and shows the number of updates when a button is clicked. However, I'm facing an issue where I'm getting NoneType instead of the expected value when trying to retrieve a parameter in view.p ...

I would like to implement a delay on this button so that when it is clicked, there is a pause before navigating

When I add the delay, it doesn't work, and when I remove it, it does. What can I do to make this button have a href link that delays before redirecting to another page? (I'm a newbie) I need to click and wait 3 seconds before navigating to other ...

Creating animations with an svg mask can be effective, however, it seems to only work properly

I have been experimenting with creating a transition effect using SVG masks and CSS. Initially, everything was working as intended, but after a few repetitions (usually 1 or 2, unpredictably), the transition effect would suddenly stop and become instantane ...

Tips for adding a personalized close button to a Bootstrap modal

I need help with a Bootstrap modal in my project that has a close button positioned at the top right corner. I've used CSS to position the button, but it's not staying in one place consistently despite applying absolute positioning. I've tri ...

Choose a different PHP value when the selection changes

I am looking to create a seamless connection between a select element and an input text field without the need to refresh the page. Here is an example of what I am trying to achieve: <select name="name_select" id="my_select"> <option value="1" ...

Guide on positioning the Bootstrap accordion button ahead of text and modifying its appearance

Check out this link for a bootstrap accordion with plus and minus icons: I'm looking to put buttons similar to the ones shown in this image: https://ibb.co/GJRGKnn Additionally, I would like to change the style of the buttons to match what's di ...

Implementing jQuery for cross-domain simple authentication

I am currently facing an issue with my system development where I have created a dynamic data retrieval feature in Grails. Upon making a request to a specific controller action, such as "http://localhost:8080/foo/bar", a JSON list is returned containing th ...

Discovering with jQuery

Can we actually change the background color of '.preview-inner' to yellow from "#change_color"? <div id = "form-container> <input class="color-picker" id="change_color" type="text"> <div class="replacer"> <div class= ...

Utilizing Laravel 5.3 and Vue.js for Dynamic AJAX Calls Based on Select Box Selections

I am looking to display a newly added record in a select box once it has been inserted into the table. Below is my Laravel HTML code: <div class="form gorup"> <select class="form-control" > <option @click="called" ...

Implementing AJAX in Laravel to enable real-time search functionality that retrieves data from

my controller public function autoComplete(Request $request) { $query = $request->get('term',''); $products=User::where('fullname','LIKE','%'.$query.'%')->get(); $data=array(); ...