Struggling to access the height attribute from a CSS file

Hey there.

I'm pretty confident that the solution to my query is quite simple.

So, I have a .css file with this particular code snippet:

div.site
{
  text-align:center;
  border:2px solid #4b6c9e; 
  padding:1px;
  margin-top:10px;
  font-size:medium;
  font-family:Verdana;
  font-weight:bold;
  height:25px; 
}

Then comes the a .js file which constructs my div using data from an xml. Here's an excerpt:

txt = txt + "<div class='site'><span class='link'><a class='nav' href='" + siteUrl[0].firstChild.nodeValue + "' target='_blank'>" + siteName[0].firstChild.nodeValue + "</a></span></div>"

document.getElementById('portalLinks').innerHTML = txt;

And in my .html file, I've got this:

<div id="portalLinks"></div>

Now, displaying the content on the page isn't an issue. But where I'm facing difficulty is in fetching the height for the site class from my .css file. This is the code I'm trying to use:

var height = $(".site").height();

My goal here is to utilize this height value to dynamically calculate and adjust the height of portalLinks:

$("#portalLinks").css({ "height": newHeight }) - where the value of newHeight will be calculated based on `height`

Thanks a bunch in advance.

Answer №1

It's important to note that the value returned by $(".site").height(); is simply a number and not a complete CSS height value.

When using

$("#portalLinks").css({"height": newHeight})
with the result of the initial call, you'll end up with an invalid value of 25. To remedy this, make sure to append a unit to the variable - for example, px:

$("#portalLinks").css({"height": newHeight +'px'});

Furthermore, keep in mind that this action alone will set the height of #portalLinks to match the height of just one .site element.

If your intention is to set the height to the cumulative total, you will need to loop through the results of $('.site'):

var newHeight = 0;
$(".site").each(function(){
    newHeight += $(this).height()
});

$("#portalLinks").css({"height": newHeight +'px'});

For a demonstration, refer to this fiddle: http://jsfiddle.net/EZWX4/


Additional Information: The method .height() retrieves the CSS height attribute value and doesn't include padding or borders.

In certain scenarios, this could lead to display issues, prompting the use of outerHeight() as an alternative.

Moreover, when employing outerHeight(true), any specified margins will be factored into the calculation.

Answer №2

Here's a suggestion to consider:

Adjust the height of "#portalLinks" using this line of code: $("#portalLinks").css("height", newHeight);

Another way to get the height, including stroke width, is by using this snippet:

var height = $(".site").outerHeight(); // this will include the stroke width as well

I hope this information proves helpful.

Answer №3

Hey everyone, I just wanted to share the solution I found. I really appreciate all of your assistance with this issue. The problem was stemming from my approach in the method - initially trying to retrieve the height of site before constructing the content itself. This is why I couldn't obtain the correct height value. To rectify this, here is what I altered to dynamically generate my html:

        var height = $(".site").height();
        var margin = $(".site").css("margin-top");
        var newHeight = (height * site.length) + (margin * site.lenght);

        $("#portalLinks").css({ "height": newHeight + "px" });

This adjustment successfully resolved my issue.

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

Unlocking the Sound: Using a Custom Button to Activate Audio on HTML Video in React

While working on a project, I encountered a small issue: I have a video tag in my code: <video muted autoPlay loop src={video}> I simply want to add a single custom button/control to toggle between muting and unmuting the video. I'm thinking of ...

Exploring the method to reveal the password hidden field in MVC by utilizing the Html helper

@Html.Password("password", null, new { @class = "form-control frmField", placeholder = "Password" }) I want to incorporate a button that when clicked will make the password visible. I know this can be achieved using jQuery or Javascript, but I am unsure h ...

Utilizing Selenium to Extract Data from ESPN Website

I am currently working on a project that involves scraping data from ESPN, performing calculations on the scraped data, and then iterating through a dataframe to process player information. While I have successfully completed this task for one player, I am ...

What is the best way to include a file attachment using a relative path in Nodemailer?

I am currently utilizing the html-pdf converter plugin to transform an HTML page into a PDF file. After conversion, this plugin automatically saves the PDF to the downloads folder. When I attempt to attach a PDF to a nodemailer email, my code looks someth ...

Start by creating a set of vertices and triangles to be utilized by the vertex shader

After experimenting with vertexshaderart.com, I'm eager to apply what I've learned on a different website. While I have experience using shaders in the past, some effects achieved on the site require access to vertices, lines, and triangles. Pass ...

interactive vuetify navigation trail elements

Currently working on a vuetify project and I'm facing an issue with implementing breadcrumbs. The problem arises when clicking on a breadcrumb, as it deletes the ones that come after it in the list. I've tried some code snippets but could only ma ...

Is there a simple way to delete an element from a multidimensional array object in React JS?

In my current project using React Js, I'm facing an issue with removing an item that corresponds to the "product_option_value_id". The task at hand is to remove an item from the product_option_value (a child array object) if the given itemId matches t ...

Minimize the entire project by compressing the .css, .js, and .html files

After recently incorporating Grunt into my workflow, I was thrilled with how it streamlined the process of minifying/concatenating .css files and minifying/uglify/concatenating .js files. With Grunt watch and express, I was able to automate compiling and ...

Triggering an Ajax call for form validation only occurs when the form is not validated

I am struggling with a simple form that has an Ajax call, but the ajax call gets executed even if the form is not validated. In the code snippet below, the line console.log("This line should execute only if Form is validated"); gets executed when the form ...

Issue with directive causing hoverable or clickable tooltip not opening when the tooltip is supposed to be displayed

Incorporating ng-mouseover/ng-mouseleave along with tooltip-is-open to control the state of the tooltip, I have successfully implemented a tooltip that remains open when hovered over. However, when attempting to reorganize it into a directive with ...

Using jQuery, you can utilize the $.when() function with both a single deferred object and an

In my current jquery setup, I am working with two variables. trackFeatures - representing a single ajax request, and artistRequests - an array of ajax requests. I am looking for a way to create a condition that triggers when both trackFeatures and artist ...

The :not() exclusion in CSS property fails to exclude the class

I'm attempting to style all the links on my webpage in a particular way, except for those in the navigation bar. Despite trying to exclude the navbar links using a:not(.navbar), it seems that the styling still applies to all links, including Link 1 in ...

What is the best way to incorporate currency formatting into a table using sumtr and datatables?

I have a table where I am utilizing sumtr for the table footer, and displaying all the information within datatables. My requirement is to show all the values as currency. However, I am unable to modify the values after sumtr because it won't be able ...

What is the best way to verify the presence of a file using jQuery?

I am using "tinyMCE" dynamically on a single page. To modify the content in "tinyMCE", I have to use the "setContent" function. However, I am unsure how to check for the existence of a file (using PHP's is_file function) either within ajax or before ...

The login page allows entry of any password

I'm running a xamp-based webserver with an attendance system installed. I have 10 registered users who are supposed to log in individually to enter their attendance. However, there seems to be an issue on the login page where any password is accepted ...

What is the best way to position this dropdown menu component directly under a specific section of my navbar in a React application?

As I delved into creating a basic navbar and dropdown menu in React, I encountered a puzzling issue. I envisioned a section within the nav that would trigger a dropdown menu right below it upon hovering over it. Attempting to replicate this functionality b ...

What is the best way to align my SVG to display inline with text?

I am trying to add an SVG image next to some text in a navbar, but I'm running into some issues. The SVG is overflowing from the navbar instead of aligning inline with the text. Here's a snippet of my HTML code: ...

Exploring the art of path zooming in d3.js

Trying to resolve this issue, I adjusted the geoJsonURL to handle a more intricate shape. Despite the new shape allowing the zoom method to function correctly, the shape itself appears completely distorted. Based on the Coordinate system: WGS 84 (EPSG:4326 ...

What is the process for monitoring all functions that will run upon completion of an ajax request?

Let's say I am dealing with an ajax call that is initiated by a page over which I have no control. This page makes the request, processes the response, and performs its own tasks. None of this page's code belongs to me. How can I determine whic ...

The error message "ReferenceError: $ is not defined" is displayed within

My current requirement involves loading templates within an iframe, and to achieve this, I have implemented the following code: <div class="col m8 l8 s12 margin-top-30" id="hue-demo-bg-div"> <iframe id="myiframe" src="/themes/{{$themeid}}.ht ...