The jQuery height() function may not always provide the expected height value, often returning either 0, -2, or 2 instead

I need a solution to display an icon in front of headlines that vary in length, sometimes spanning one line and other times extending to two lines. The challenge is to ensure the icon resizes accordingly to match the height of the headline element.

Currently, the SVG occupies all available space within its container, resulting in icons that are always as large as the .svg-container itself. To address this issue, I aim to make the .svg-container square-shaped, mirroring the dimensions of the svgs it holds. This means the container should have a height equal to that of the .headline element, serving as both the height and width for the .svg-container.

To achieve this goal, I attempted to retrieve the height of the .headline span (or possibly a div) using $('.headline').height(); and then apply this value to the .svg-container via .css().

However, I encountered difficulties as the actual height returned was 0. I experimented with obtaining the heights of other elements on the page, but I consistently received values of 0, -2, or 2.

My research revealed that wrapping the code inside $(document).ready(function(){ was necessary, yet it failed to rectify the situation.

$(document).ready(function() {
  var headlineHeight = $('.headline').height();
  $('.svg-container').css('width', headlineHeight)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h1 class="spacing-after headline-with-icon">
  <span class="svg-container">
    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
 viewBox="0 0 40 40" style="enable-background:new 0 0 40 40;" xml:space="preserve">
    <use xlink:href="#icon-1"/><!-- takes the icon form an svg sprite -->  
  </svg>
  </span>
  <span class="headline">Headline in here</span>
</h1>

Answer №1

I made a modification to the .svg-container element by changing it from a span to a div, since a span does not naturally support a width property. Additionally, I included width: 100%; to ensure that the svg adapts to its parent's width, resulting in a smaller svg after executing the script. To confirm this change, I inserted a console.log() as well.

$(document).ready(() => {
  let headlineHeight = $('.headline').height();
  
  console.log(headlineHeight);
  
  $('.svg-container').css('width', headlineHeight)
});
.svg-container > svg {
  width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h1 class="spacing-after headline-with-icon">
  <div class="svg-container">
    <svg width="200" height="100" xmlns="http://www.w3.org/2000/svg"><rect x="2" y="2" width="196" height="96" style="fill:#dedede;stroke:#555555;stroke-width:2"/></svg>
  </div>
  <span class="headline">Headline in here</span>
</h1>

Answer №2

When we make a span a block element, it takes on width and height. Spans are typically displayed inline by default, meaning they do not have inherent height and width.

Therefore, switch,

 <span class="headline">Headline in here</span>

to,

 <div class="headline">Headline in here</div>

EDIT 1:

As noted by MiXT4PE, also replace the svg-container with a div tag.

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

Having difficulty displaying elements from two arrays at particular intervals

I am currently working with two arrays that have the same number of items in each. My goal is to print these items in intervals within the console. The desired output would look something like this: 1 Bruce Wayne 45 Then, after a one-second interval, it s ...

What is the best way to link HTML transformations across several classes?

Is it possible to combine multiple transforms in a single element to create a unique end result? It seems that when applying multiple transform properties to an element, only one of them will be recognized. For example, trying to transform a div with bot ...

The Cordova Ajax request fails to send when connected to a mobile network

Currently, I am in the process of developing android applications on cordova. A jquery ajax call is made to my server, which functions properly when tested on my browser and even on my device when connected to a local proxy for http sniffing and local wi-f ...

Troubleshooting a malfunctioning AJAX function in CakePHP 2.x

I am currently learning cakephp and experimenting with incorporating AJAX functionality into my project. Within the view file add.ctp, I have included the following code: $('#office_type').change(function(){ var office_id = $('#office_ ...

Using the previous page button will cause the current page button to have various states

Whenever I use the previous page browser button, the current page's button state does not reset. This causes multiple menu items to appear as if they are in their 'current' state when the previous page is revisited. If I hover over the &apos ...

Tips on retrieving the API response using AJAX

Currently, I am attempting to retrieve the API response from Flickr using Ajax in my application built with Laravel. To accomplish this, I have established a specific Route and function dedicated to handling API calls. //Route.php Route::post('/getlo ...

Using the ampersand symbol '&' in Sass to target the body tag with a particular class applied

Demo: https://codepen.io/moradxd/pen/WJpPyQ Consider this sample HTML code: <body class="boxed"> <div class="text-white"> <a href="#" class="btn-featured">Button</a> </div> </dody> I am implementing the follow ...

How can I utilize jQuery to add tags in a box?

I have an idea for a feature similar to the Stack Overflow tag insert. My goal is to have a box where I can type in a tag, click 'Add', and see it appear above. Additionally, I want this action to update an array called 'SelectedTags'. ...

What is the best way to save information using local storage in AngularJS?

I have been struggling to implement local storage in AngularJS to store information. Can anyone offer guidance or assistance? Below is the code I have attempted: angular.module('todo', []) .controller('ToDoCtrl', ['$scope&apo ...

When utilizing the HTML select element, the <option> tag may only display the initial letter of the chosen option

Here is a snippet of my PHP code: <?php if($_POST['post'] == 'Post') { $cat = $_POST['cat']; $update = "UPDATE table SET category='$cat' WHERE id = '$id' "; $result = mys ...

Steps for transforming a text from xml into a clickable hyperlink in html with the help of xslt

Is there a way to transform text in an XML file into a hyperlink in HTML using XSLT? This is the XML code I am working with: <Steps> <Filepath>C:\Test\Capture\050615165617TC001_05_06_1516_57_11.png</Filepath> ...

renewing a div element without the need to reload the entire webpage

I'm currently developing a setup process for configuring a database. My goal is to allow the user to progress through each phase without having to refresh the page. However, I've encountered an issue while trying to implement the .load() function ...

Hide the first div within the inner div of a section using CSS

I am working on a section that contains multiple nested divs. Within each outer div, there are 3-4 inner divs. My goal is to hide only the first inner div of each outer div while still displaying some text. section div div:nth-child(1){ display: n ...

Step-by-step guide to displaying the dropdown menu button content at the top of the page in main.html by using the frameset tag

The layout of my main.html involves displaying menu.htm and welcome.htm using frameset. One issue that arises is with the drop-down menu buttons "Admin..." and "Scheduler...". When hovering over these buttons, the dropdown content does not display properly ...

Employing setTimeout within a repetitive sequence

function displayColors() { $.each(colors, function(index) { setTimeout(function(){ revealColor(colors[index]); }, 1000); }); } I'm attempting to create a loop where the revealColor function is executed every second until all colors ...

Button from Bootstrap extends beyond the page on mobile devices

I am facing an issue with my button. It looks great on desktop, but when I switch to the mobile version, it goes beyond the screen width like in the image below: https://i.sstatic.net/69Zbs.png 1) How can I prevent this from happening with the code provi ...

The CSS rotation effect causes the element to spin and twirl

I've been struggling once again to grasp the concept of CSS animations, particularly the rotate animation. I'm trying to create an effect where an image rotates back and forth on hover, but for some reason it only starts rotating after shifting t ...

Is the main content positioned below the sidebar on smaller screens?

In order to achieve a 250px col-2 sidebar with a col-10 main body that collapses into a top navbar and main content beneath it, my goal is set. However, I am facing an issue where the main content body goes underneath the sidebar when the screen size cha ...

Difficulty: Issue with displaying Backbone collection using Mustache template

I'm new to backbone js and Mustache. I want to load a backbone collection on page load from rails json object to avoid making an extra call. However, I'm facing issues when trying to render the backbone collection using a mustache template. Here ...

Django will not be replacing the outdated image

My Django App is designed to display images on the browser based on user selections in the UI. Whenever there is a change in the UI, a JavaScript function is triggered that makes a call to a Django view. Each time I modify the UI in the browser, a new ima ...