Generating a dynamic triangle within a div while ensuring it fits perfectly with the maximum width

I need help with creating a responsive triangle on a web page that takes three inputs. The challenge is to adjust the size of the triangle so it fits inside a div element while maintaining the aspect ratio of the inputs. For instance, if the inputs are 500, 500, and 300, I want to scale them down to fit within the designated div section.

Here's the basic setup:

<div id="triangle"></div>

And here's how you can style it with CSS:

#triangle {  
  max-width: 200px;
  width: 0;
  height: 0;
  margin: 0 auto;
}

To dynamically create the triangle with jQuery, use the following code snippet:

$("#triangle").css({
  "border-left": length1 + "px solid transparent",
  "border-right": length2 + "px solid transparent",
  "border-bottom": length3 + "px solid #2383ea"
});

Answer №1

Here is one approach to achieve this.

Begin with the provided HTML, which consists of two nested block elements:

<div id="triangle"><div class="inner"></div></div>

along with some basic CSS:

body {
    margin: 0;
}
#triangle {
    border: 1px dotted gray;
    max-width: 400px;
    margin: 0 auto;
}
#triangle .inner {
    width: 0;
    height: 0;
}

Next, utilize the following jQuery/JavaScript code:

var length1 = 1500;
var length2 = 1500;
var length3 = 1500;

var maxWidth = parseInt($("#triangle").css("max-width"));

var baseWidth = Math.min($("#triangle").width(),maxWidth);
var scale = baseWidth/(length1+length2);

$("#triangle .inner").css({
  "border-left": length1*scale + "px solid red",
  "border-right": length2*scale + "px solid green",
  "border-bottom": length3*scale+ "px solid #2383ea"
});

A demo showcasing this functionality can be viewed at: http://jsfiddle.net/audetwebdesign/WVcvj/

Programming Guidelines

The values for length1, length2, and length3 will typically be obtained from a form input or similar source.

Remember that, by default, #triangle will inherit the width of its parent container. If this width is less than the maximum specified width (accessible via the .css function), it should be used instead. The parseInt() function is useful for removing the accompanying px unit.

The base width of the triangle corresponds to length1+length2, so calculate the ratio between the available width and the total specified width.

Normalize the three border widths accordingly to complete the task!

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

Guide on passing the set[State] function to a trigger component that is not a descendent

Take a look at this diagram. ChildComponentB contains a state called stateX. In ChildComponentA, when a certain event occurs, it should modify the stateX in ChildComponentB. If ChildComponentA is a child component of ChildComponentB, passing the setStateX ...

Is Ajax failing to function correctly?

Below is the AJAX code snippet that I am working with: $('.AllTaskDownloadButton').on('click', '.CheckBoxesForDownload', function(){ var n = $( "input:checked.CheckBoxesForDownload" ).length; var arr=[] for(i=0;i ...

Tutorial: Implementing InfoWindows for Markers in Google Maps API V3 in a C# Web Page

Here's my newbie question, hope the formatting is correct :) I'm working on an ASP.NET, C# application that retrieves coordinates (Lat, Lon) from SQL and displays them as markers (which is working fine). However, when I try to add infowindow ...

Retrieve every video on React.js channel from YouTube

Currently, I am working on integrating react-youtube into my React App with the goal of accessing all videos from a specific YouTube channel. The challenge I am facing is that I need to display these videos as thumbnails, exactly how they are listed in the ...

Combine bar and stacked bar charts on a single graph with morris.js

Can a combination of a stacked bar chart and a regular bar chart be created in morris.js? I have successfully generated a stacked bar chart using the following code: Morris.Bar({ element: 'bar-example', data: [ {x: '2011 Q1', ...

An SQL query that functions flawlessly in STUDIO 3T, yet fails to execute in Express.js

I encountered a puzzling situation where a query that functions perfectly in STUDIO 3t fails to retrieve any data in express js. Below is the code comparison: STUDIO 3t Query: db.getCollection("tickets").find({ $and: [ {"TCKT_CRTE_DTTM" : { ...

Troubleshooting the issue of a callback function not properly updating state within the componentDidMount

I am currently utilizing Next.js and have the following functions implemented: componentDidMount = () => { //Retrieves cart from storage let self = this this.updateCart(Store.getCart(), self) ... } updateCart = (cart, self) => { ...

Grab information from PHP script received through Ajax and jQuery

I am currently facing an issue with retrieving data sent to a php script. After checking the chrome tools (networks->xhr->headers), I noticed that the Content-length is also showing 0. Furthermore, when looking at the Response tab, the errors displa ...

What steps can be taken to avoid including empty tasks in React code?

Is there a way to prevent my application from adding empty tasks? Below is the code snippet for adding a new task to an array. How can I implement a condition to block the addition of empty tasks? This application follows Mozilla's guidelines for a R ...

The BG column image is not stretching to full height

I am facing an issue with my website layout where the left column has a background image and another background image is set for the body to fill the rest of the screen. The content area on the right extends vertically beyond the browser window height. How ...

Calling functions in AngularJS/HTML can help you execute specific

Just started with angularjs and facing some major issues haha... I have something that seems to be working fine, but I can't figure out what's wrong with this code... can someone please help me? Here it is: Basically, the scope.create function ...

Enhance your WordPress menu with additional attributes

Currently, I am implementing a lightweight lightbox script on my WordPress website. My goal is to have one of the main navigation buttons open a Vimeo link in the lightbox. According to the lightbox documentation, I need to "Add the 'data-lity' a ...

Add CSS styling to a single form

When working on a larger project, the goal is to reduce the size of various elements within a form named quickpost-form <div id="qp-form"> Specific elements in the form require a smaller font size such as text, input, input-group, and tex ...

The image slider is blocking the dropdown functionality of the navbar on mobile devices

My code is experiencing a conflict of events. I have created a menu bar using nav bar, as well as an image slider called the caroussel. The issue arises when the window is minimized - the menu bar fails to drop down properly with the presence of the caro ...

Unable to link JSON response to input field using jQuery AJAX (MVC 4)

I am facing an issue with binding JSON values to a text box. Despite searching online, I haven't been able to find a solution for this. Here is the code that I am using: JQuery: $(document).ready(function () { $('#Email').mousemove(functio ...

What is the best way to showcase a specific column from a dataset using Vue.js and axios?

Hey there, I'm still getting the hang of all this and haven't quite mastered the jargon yet. Here's what I need help with: I managed to retrieve data from my SQL database using axios, and when I check in (f12) - network - preview, it shows: ...

What causes the image to not appear at the center bottom of the page when using IE for loading?

Why does the loading image not appear at the center bottom of the page in IE? This function loads content when the page is loaded and also loads content when scrolled to the bottom. When you load the page index.php, you will see the loading image at the ...

Is there a way to disable text selection in AngularJS when double-clicking using ng-dblclick?

My element has ng-dblclick='doSomthing()' functionality that is functioning correctly, however, it also selects the text in the element which is not visually appealing. Is there a way to avoid this issue? ...

Performing multiplication and calculating the final sum of an array object in Node JS

I am looking to calculate the total based on an array of objects sum of each row = sum of costs * quantity total = sum of (sum of each row) Below is the object array that I am working with const newArray = [ { 'LOA Qty': '2000', ' ...

Is there a way to use regular expressions to search for class names within nested div elements?

I'm struggling to find nested divs like these in my document object model (DOM) <div class="two-columns some-other-class"> <div class="two-columns some-other-class"> </div> </div> I attempted to search for neste ...