Incorrect use of the jQuery .height() method

I am working on creating a responsive div with a sloped edge that needs to adjust according to the screen size. I have successfully maintained a consistent angle across all screen sizes, but I am facing an issue where the height calculation for $('#slope') is not always accurate. It seems to glitch when I resize the window or switch tabs.

HTML

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  </head>
  <body>
    <div class="row">
      <div id="block">
        <div id="content">
          Some content<<br>
          Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit sint culpa, dolor quaerat autem repellendus, doloremque molestiae, natus ut veritatis eius deserunt mollitia. Eaque ex facilis nobis obcaecati dolorem odio veniam laudantium nemo voluptates voluptas nulla ducimus officia quod maiores corporis hic nisi incidunt aliquid fugiat tenetur at, labore earum. Sapiente perspiciatis, laudantium consectetur sed omnis porro quasi quae. Neque voluptatem, praesentium mollitia ad cumque voluptates ipsa dolores velit beatae odio veniam, voluptatum atque repellat. Minus perferendis, natus accusantium! Sunt architecto provident error commodi. Provident dolorum praesentium quis fuga saepe odio fugiat reiciendis laborum sed at facilis natus facere, dignissimos repellendus. Numquam fugiat consectetur deleniti tempora quibusdam distinctio nulla sequi voluptate inventore voluptas cupiditate eaque soluta neque optio rem vel autem adipisci id fuga sapiente voluptates harum, eius est qui. Asperiores molestiae recusandae cum non sint deserunt nisi aliquid dicta obcaecati ut repellat tenetur laudantium eaque, amet praesentium numquam laboriosam, beatae vitae vel. Tenetur recusandae dicta voluptate aperiam architecto saepe provident odit deleniti possimus consequatur libero voluptas sequi officia minima perspiciatis repellendus voluptates nostrum fugit voluptatem, vero. Minima, tempora vero dicta provident, ducimus nobis quibusdam nam blanditiis eligendi architecto pariatur, enim ut eos reiciendis quisquam aut, eum at porro esse!
        </div>
        <div id="slope">

        </div>
      </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
  </body>
</html>

CSS

.row {
  margin: 0 !important;
}

#block {
  background-color: green;
  width: 50%;
  height: auto;
  min-height: 150px;
  position: relative;
}

#slope {
  content: '';
  position: absolute;
  right: 0;
  bottom: 0;
  width: 0;
  height: 100%;
  background: #fff;
  border-bottom: solid #fff;
  border-left: solid green;
  border-width: 0 0 0 0;
}

JS

$(document).ready(function() {


updateSize();


  $(window).resize(function() {
    updateSize();
  });
});

function updateSize() {
  $('#slope').css('border-width', '0 0 ' + $('#slope').height() + 'px ' + $('#slope').height()/6 + 'px');
}

Check out my Code on JSFiddle

To reproduce the glitch, try resizing the window. The slope should always maintain a consistent 10° angle from the top right corner.

Answer №1

It's puzzling to see that the value returned by .height fluctuates at times. To tackle this issue, I recommend utilizing .outerHeight instead, which consistently provides the accurate 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

What is the process for updating a placeholder text after the user makes a guess or enters

My latest project involves creating a fun guessing game where players have to identify the driver based on the teams they have driven for. The game displays the number of guesses allowed and keeps track of how many attempts the player has made so far. For ...

The new update for Bootstrap 4's HTML tooltip feature includes a fix that prevents

When setting up tooltips, I use the following code: $('.tooltip').each(function () { $(this).tooltip({ html: true, title: $('#' + $(this).data('tip')).html() }); }); An example of tooltip code looks like ...

The font color fails to change when hovering over

I'm experiencing an issue with the styling of my input box. When the user starts typing, a div containing a list of possible clubs is displayed. Currently, I am having trouble with the .clubLink:hover class and its background color. CSS: <style& ...

What's the best way to capture an element screenshot using JavaScript?

I'm working on developing a unique gradient selection application. One of the exciting features I would like to incorporate is the ability for users to save their chosen gradients as digital images (.jpg format) directly onto their computers. When the ...

How can a server retrieve a file uploaded using FormData and Ajax on a cross-domain upload?

my website is running on localhost:8084 and I need to upload a file to localhost:8086. Below is the JavaScript code: var xhr = new XMLHttpRequest(); xhr.open("post", "http://localshot:8086"+ "?type=ajax",true); xhr.setRequestHeader("X-Reque ...

Creating fixed values in HTML

I need to maintain consistency in the headings of multiple tables spread across 3 HTML pages. The heading structure is as follows: <thead> <tr> <th>MyHeading</th> </tr> </thead> My goal is to store the string MyHeadin ...

Vuetify offers a convenient solution for implementing multiple buttons in a Vue

My search bar retrieves data from an API query in the following format: Data: [[id, datafield1, datafield2],[id, datafield1, datafield2],...] I wish to include an on/off button for each row of the data, with each button having its own independent state. ...

Tips for creating a mobile-friendly Bootstrap carousel that is both scalable and zoomable while maintaining the default slide functionality

I have a website using Bootstrap 4.x carousel. The layout is user-scalable with the following viewport meta tag: <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2, shrink-to-fit=no">. Currently, users can pinch to z ...

Invoking a Components function from a Service in Angular may lead to a potential cyclic dependency issue

I am facing a challenge where I need to call a function from my filterComponent(component) within my engagementService(service). The function in my filterComponent accesses an array that is located within the engagementService. It uses the data from this ...

Secret message concealed within the depths of my Bootstrap 5 Side Navbar

I have successfully created a side NavBar using Bootstrap 5, but I'm facing an issue where my text is getting hidden behind the navbar. Any suggestions on how I can resolve this? Below is the code for my side Navbar: const Navbar = ({ handleClick, is ...

How plupload can seamlessly transition to the next upload after completing one

Using plupload 1.5.7 and the jQuery Queue Widget, I've noticed that after completing an upload, the Add files and Start Upload buttons disappear, replaced by a label saying Upload 1/1 files. Unfortunately, this means I can't add more files witho ...

It seems that CSS shadows are working perfectly on Firefox and Chrome, but unfortunately, they are not displaying on

I have encountered an issue where CSS shadows appear fine on Firefox and Chrome, but do not display in Internet Explorer. Below is the code I am using: -moz-box-shadow: 0 0 20px #000; Can anyone provide a solution for this compatibility problem? Thank ...

What is the best way to implement dynamic generation of Form::date() in Laravel 8?

Is there a way to dynamically generate the Form::date() based on the selection of 1? If 1 is selected, then display the Form::date() under the Form::select(). However, if 0 is selected, then hide the Form::date() in this particular view. For example: Sel ...

Display JSON data in a hierarchical tree structure using AngularJS

Looking to display three nodes of a JSON file as a tree using AngularJS. The nodes are data.key, data.parentItem, and data.title. Below is the JavaScript code: var phonecatApp = angular.module('myApp', []) phonecatApp.controller('myContr ...

Aggregate X and Y values based on a key in a scatter plot using dc.js

Here is a glimpse of my dataset: var items = [ {name: "X", duration: 1, quantity: 2}, {name: "X", duration: 2, quantity: 1}, {name: "Y", duration: 1, quantity: 4}, {name: "X", duration: 3, quantity: 1 ...

Transmit picture to server - HTTP Error 415 (Unsupported Media Type): "The media type 'image/png' in the request is not supported."

My attempts to send an image from the frontend using AJAX to the backend with Django Rest Framework have been unsuccessful. The error response received is: {"detail":"Unsupported media type \"image/png\" in request." ...

"Troubleshooting problem with fetching JSON data for Highcharts

As a relative newcomer to web development, my usual focus is on server-side work. Currently, I'm diving into a fun little electronic project where a Netduino server handles JSON requests within my LAN. The JSON response format from the Netduino looks ...

Express Module Paths Failing to Function Properly

When I first started building my routes, I had everything in one api.js file. However, I realized there might be a better approach, so I did some research online to see how others handle it. After following a few tutorials, I decided on a new layout with s ...

Tips for integrating a unique font into your PhoneGap project

I've been attempting to incorporate a custom font into my PhoneGap application, trying out two different methods I came across online. Unfortunately, neither of them seem to be effective when using PhoneGap 3 and Xcode 5. First method involves using ...

Troubleshooting: Navbar Hover Effect in Tailwind CSS Not Functioning as Expected

This week, I've been working on building a navbar and it seems like the layout is coming together nicely. However, I've encountered a couple of small issues with the hover effect and the links for the menu items on the left and the logo in the ce ...