Resizing background images to their original size using jQuery

Can anyone help me figure out the actual size in pixels of a background image that is being displayed?

<style>
body {
    background-image: url(background.jpg);
    background-size: contain;
}
</style>

I tried using jQuery to get the size of the background image with the following code:

var img = new Image;
img.src = $('body').css('background-image').replace(/url\(\"|\"\)$/ig, "");
var bgImgWidth = img.width;
var bgImgHeight = img.height;

However, this code returns the size of the real image, not the displayed size. For example, on a device with 320px width, bgImgWidth still shows 800px from the actual image.

Any suggestions or clues on how to correctly determine the displayed size of the background image?

Answer №1

To determine the height of an image being displayed, you can calculate it based on its width and height.

var img = new Image();
var $el = $('body');
var containHeight = null;
var containWidth = null;
var containImg = {
  w: null,
  h: null
};
var bkgImgDims = null;

img.src = $el.css('background-image').replace(/url\(\"|\"\)$/ig, "");

var bgImgWidth = img.width;
var bgImgHeight = img.height;

var imgProportionalH = Math.abs(bgImgHeight / bgImgWidth);
var imgProportionalW = Math.abs(bgImgWidth / bgImgHeight);

// Calculate the proportions of the background image contained in the element
function getElProportions() {
  var elW = $el.width();
  var elH = $el.height();
  var elProportionalH = Math.abs(elH / elW);
  var elProportionalW = Math.abs(elW / elH);

  // Determine if the image is not taking up 100% of the element's width
  if(elProportionalH < imgProportionalH) {

    containImg.h = elH;
    containImg.w = Math.abs( elH / imgProportionalH );        

  } else {

    containImg.h = Math.abs( elW / imgProportionalW );
    containImg.w = elW;

  }

  return containImg;
}

$(document).ready(function(){
  bkgImgDims = getElProportions();
});

$(window).resize(function(){
  bkgImgDims = getElProportions();
});

JSBin Example

Answer №2

One potential solution is to utilize a script provided by a plugin. You can find the source of this script at: https://gist.github.com/schmidsi/1276118

I have incorporated this script into a JSFiddle, allowing you to visualize and compare the body content with the background image.

var url = $('body').css('background-image').replace('url(', '').replace(')', '').replace("'", '').replace('"', '');
var bgImg = $('<img />');
var bodyHeight = $('body').height();
var bodyWidth = $('body').width();

bgImg.hide();
bgImg.bind('load', function()
{
    var imgHeight = $(this).height();
    var imgWidth = $(this).width();

    alert("Body height: " + bodyHeight + "px, Body width: " + bodyWidth + "px");
    alert("Image height: " + imgHeight + "px, Image width: " + imgWidth + "px");
});
$('body').append(bgImg);
bgImg.attr('src', url);

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

To make the down arrow image scroll to the end of the page after the 2nd click, simply follow these steps. Initially, the first click

After setting up the image icon and utilizing Javascript and jQuery, I encountered an issue with the down arrow functionality. The first click successfully takes me to the second row grid box downwards, but I am struggling to implement a second click actio ...

Retrieve Wikipedia API JSON information using jQuery

$('#searchButton').click(function(){ var searchInput = ""; searchInput = document.getElementById('test'); if(searchInput.value !== ""){ $.getJSON('https://en.wikipedia.org/w/api.php?action=query&list=search&format ...

Guidance on uploading a file with AJAX in PHP following the display of a Sweet Alert

I am currently facing an issue with inserting a file input (images) into my database. When I try to insert it, the value returned is empty. Below is the script I am using: <script> $("#insertform").on('submit',(function(e) { ...

The minimum height increases as the inner divs expand

Can you help me with the code below? html <div class="content"> <div class="col"> </div> <div class="col"> </div> <div class="col"> </div> <div class="col"> </div> ...

"Combining Angular and jQuery for powerful web development

I am looking to develop an application using Angular and incorporate numerous jQuery animations and jQuery UI effects (such as animate, fadeIn, fadeOut, etc). Is it feasible to use jQuery functions in conjunction with Angular? ...

Assistance required for posting Jquery files

Attempted to upload a file using jQuery with a hidden form and an Input element, triggering the file browser with jQuery. The changed input is then sent to a PHP server script. Encountered an issue where submitting the form with $("form1").submit(); worke ...

Update the Div when Fancybox is Closed

Is there a way to refresh a parent page's div after closing Fancybox? I am aware of using onClosed: function(), but I'm unsure which specific function to include in it. ...

Challenges with Hangman in JavaScript

As a beginner in JavaScript, I recently developed a simple hangman-like game. However, I encountered some challenges that I need help with. One issue is related to my lettersGuessed array. Currently, the array displays every time a key is pressed and repea ...

Trigger a warning pop-up if a selection has not been made in a dropdown menu using jQuery

I am attempting to display an alert popup when the user fails to select a value from the dropdown menu. Below is my HTML code: <div id="reminder" class="popup-layout"> ... ... </form> </div> In my JavaScript function page, I have tried ...

Stop the page from scrolling

I'm trying to find a way to disable page scrolling, so I used this style for the body: overflow: hidden; Surprisingly, it worked perfectly on desktop but had no effect on mobile devices. After checking out this resource, it seems that creating a ch ...

Can a file object be transmitted using this method?

I'm new to jquery and I am attempting to upload a File object obtained from my HTML: <label for="photo" class="col-xs-2">Photo</label> <input id="photo" name="fileName" type="file" class="col-xs-4"/> This is the snippet of my J ...

adjusting iframe dimensions for iPads

I am dealing with an HTML file that contains the following code snippet: <table height="100%" cellspacing="0" cellpadding="0" border="0" width="646" class="data border"> <tbody> <tr> <td valig ...

"Efficiently fetching and handling multiple rows with

Having 2 questions: 1. Retrieving Ajax data from query.php like this: echo json_encode($records, JSON_UNESCAPED_UNICODE); This results in: [{"cinfo_id":"25","fullName":"علی علوی","phone":"123456","mail":"<a href="/cdn-cgi/l/email-protection" ...

What could be causing the disappearance of the replaced div content after a refresh?

Does anyone have experience with using jquery in conjunction with django? I am currently trying to update the content of a div after successful user authentication. While my code is functional, I'm facing an issue where upon page refresh, it reverts b ...

Steps to ensure my collapsible is open from the start

Is there a way to have the collapsible content open by default without much hassle? I'm a bit lost here and could use some guidance. I must confess, I'm not very familiar with this, so hopefully, it's not too complicated. While my question ...

Unable to establish the origin for an element using JavaScript

Currently, I am developing a simple game in JavaScript that includes a grid and various cells. Here is the current look of the game which functions perfectly. However, I am facing an issue with setting the margin to 0 and wanting to center the canvas inste ...

Incorporate a dropdown menu based on the selection made in another dropdown menu

I have a scenario on my website where I want to dynamically add select boxes based on the value selected in the previous one. Here is the code snippet: <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.js"> </script> & ...

What is the process for adding a custom header when making an ajax call in a datatable?

Currently, I am utilizing datatables and need to include a custom header for specific server-side requirements. Can anyone provide guidance on how to send a custom header when navigating to the next or previous pages using jQuery datatables? Additional ...

What is the procedure for configuring this.class to perform a specific action?

Does anyone know how to set this.class to perform a specific action? It seems like this.block is not functioning correctly! CSS <div class="container"> <div class="block" >#Product 01.</div> <img src="001.jpg" width="300"/> ...

Creating markers for every value in a table using Google Maps API v3

Looking for some guidance here. I have a table with multiple values that I need to process using a function. Could someone help me with a suitable loop in jQuery or JavaScript that can achieve this? I'm still learning the ropes of these languages. My ...