Complete picture in a circular div with aspect ratio

I'm currently working on creating a profile page and I'd like to have an image inside a circular div. The challenge is that I want the image to maintain its aspect ratio, even though the dimensions are unknown and users can upload images of any size.

Here's the code I have so far:

$(window).load(function(){
 $('.profile-img').find('img').each(function(){
  var imgClass = (this.width/this.height > 1) ? 'wide' : 'tall';
  $(this).addClass(imgClass);
 })
})
.profile-img{
    
    height:150px;
    width:150px;
    overflow:hidden;
    border-radius:50%;
    box-shadow: 0 0 5px silver;
}
.profile-img img.tall {
    max-width: 100%;
    height: auto;
}
.profile-img img.wide {
    max-height: 100%;
    max-width: 100%;
    width: auto;
}​
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
<div id="profile-img" class="profile-img">
  <img src="http://i.enrolin.in/img/profile2.jpg" />
</div>

Answer №1

Adjusting image size based on width and height ratio.

$(window).load(function() {
  $('.profile-img').find('img').each(function() {
    if(this.width / this.height > 1)
      this.height = $(this).parent().height();
    else
      this.width = $(this).parent().width();
  });
});
.profile-img {
  height: 150px;
  width: 150px;
  overflow: hidden;
  border-radius: 50%;
  box-shadow: 0 0 5px silver;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="profile-img" class="profile-img">
  <img src="https://i.sstatic.net/2kpOL.png" />
</div>
<div id="profile-img-2" class="profile-img">
  <img src="https://i.sstatic.net/JIVkh.png" />
</div>

Answer №2

When I was using jQuery 1.3.1, I encountered this error:

Uncaught TypeError: (F || "").split is not a function

As a result, I decided to upgrade to the latest version available (2.1.1).

$(window).load(function () {
  $('.profile-img img').addClass(function () {
    return $(this).width() / $(this).height() > 1 ? 'wide' : 'tall';
  });
});
.profile-img {
    height: 150px;
    width: 150px;
    overflow: hidden;
    border-radius: 50%;
    box-shadow: 0 0 5px silver;
}
.profile-img img.tall {
    width: 100%;
}
.profile-img img.wide {
    height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="profile-img" class="profile-img">
  <img src="http://i.enrolin.in/img/profile2.jpg" />
</div>

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

include a new value to the current state array within a react component

I am working with an array in React State and I need to add a new property called Value. However, every time I try to add it, it creates a new item in the array. What I actually want is for the new property to be added as follows: value: '' Belo ...

Is there a way to manipulate a DOM element using a component?

import { FlagIcon, ChartIcon, ShareIcon, ConnectIcon, HearIcon, AnalyticsIcon, AddIcon, RemoveIcon, } from "../../icons/Icons"; import "./Sidebar.scss"; import ReactDOM from "react-dom"; const Sidebar = () =&g ...

Guide to pre-populate a text field within a WKWebView on a website with the use of Swift

I am a beginner in the world of coding, specifically with Swift. My goal is to allow users to input their username and password in the settings section, which will then automatically populate the login page on a WKWebView that I have created. Currently, I ...

When using a React Router path variable along with other paths, React may have difficulty distinguishing between them

Setting up react router in my project to differentiate between user username variables and other paths is proving challenging. For instance: baseUrl/admin baseUrl/daniel Currently, React is unable to distinguish between the two. My intention is to query ...

Express encountered an error: NODE_ENV is undefined

This section contains my index.js code: var express = require('express'); var app = express(); var compression = require('compression'); var path = require('path'); app.use(compression()); app.set('port', (process. ...

the neighboring div sliding to the left causing the div not to expand with its content

I am trying to create a website similar to this one. When I click on the arrow, the left div collapses and the right one expands. However, the content of the right div does not expand as expected! Below is my HTML code: <div class="tools-bg"> & ...

React issue: parent state becoming unresponsive when updating during input onChange event

I am currently working on a large form that consists of at least 50 input fields. I have developed a function within the form component to store the input values in the form's state: PARENT FUNCTION saveToState(details) { const { company } = thi ...

Building a class structure with a JavaScript MVC approach - best practices

I am looking to develop a JavaScript web application using the MVC-like principle. While my code is functional, I am facing challenges in implementing it correctly. I have created a global variable called APP where I store controllers, views, and other com ...

Layer one div background image over another div background image

My goal is to have the Mario image displayed on top of the background seen in the screenshot below. While I've managed to get it working, I'm struggling to center the Mario image properly over the background. Additionally, I would like to elimina ...

Utilizing jQuery to append a new item to a list without using any identifiers and an excessive number of classes

I have been tasked with adding a new link to an unordered list on three different pages using a custom.js override file. Due to system requirements, I must use jquery for this task. However, I am having trouble figuring out how to select and insert the new ...

Creating AngularJS variables with dependencies on integer values

Hello, I am a brand new developer and I am currently working on creating an expenses calculator. The goal is to have the sum of inputted integers from a table, each with a default value, become the integer value of another variable. However, I seem to be m ...

I'm curious about utilizing jsviews in conjunction with jquery sortable

Check out my jsFiddle Example where I am using jsViews in conjunction with JQuery sortable. By default, the remove function works fine; however, when you change the order of items and then try to delete one, multiple items are removed. How can this issue ...

Border shifts on hover effect

After much trial and error, I finally managed to center two links in a nav bar perfectly on the page. I also added a grey bottom border that spans the entire width of the page, with the hover effect turning it blue under the links. Check out this example: ...

A step-by-step guide on how to exclusively print items that have been selected using a checkbox in AngularJS

I have created two tables and added a checkbox for each one. Instead of default checkboxes, I have used images that change when clicked. Here is the code snippet: <button class="btn btn-lg btn-customPrint-md no-print" ng-click="checkBoxPrint2 = !check ...

Avoiding cross-site scripting vulnerabilities, an AJAX response will return an HTML response

function accessAccount() { var errorMessage = ""; var checkedResult = true; $(".errorDisplay").hide(); var accountNumber = document.getElementById('customerAccountNumber').value; var accountType = document.getElementById(&apos ...

The series attribute cannot be located within the reactD3Basic object in ReactD3

Recently, I attempted to integrate the reactd3 library into my project and encountered an issue: Uncaught TypeError: (0 , _reactD3Basic.series) is not a function This error is specifically pointing to this line in the library code: var chartSeriesData = ...

What is the process for appending a URL parameter to the existing URL in a React application?

Presently, I am working within the Post component and using the Fetch API to retrieve data from the "/home" route. componentDidMount() { fetch('/home') .then(res => res.json()) .then((data)=> { console.log(data.ports) ...

Validating forms in angular: How to check if a form is legitimate

I am attempting to validate a form using Angular to determine its validity. The form structure is as follows: <form name="form" novalidate> <p> <label>Number: </label> <input type="number" min="0" max="10" ng-mo ...

CKEditor not functioning properly when generated using AJAX and PHP in JavaScript file

I am facing an issue where I am using PHP and AJAX to generate a CKEditor textarea. The CKEditor JavaScript files are included in the main HTML file, and the PHP and AJAX functionalities are working correctly. However, when the form is displayed, the CKEdi ...

Ensure that the text is contained within a div element with a border-radius of 100%

Is there a way to set text inside a div with a border-radius of 100% in a circular shape? I have paragraphs and ul li's within the div, but the text goes outside the borders. How can I wrap the text within the curved edges of the div? ...