Issue with jQuery auto resizing feature malfunctioning

I'm trying to incorporate an image into a div (#bg) using jQuery in order to create a webpage that automatically resizes. However, I've encountered some issues with the auto-resizing functionality. When I manually add the image to the div, everything works perfectly fine. I'm still relatively new to jQuery, so any detailed explanations would be greatly appreciated. Thank you in advance.

HTML

<div id="bg">​
</div>

CSS

#bg { position: fixed; top: 0; left: 0; }
.bgwidth { width: 100%; }
.bgheight { height: 100%; }

jQuery


$(window).load(function() { 

    $('#bg').prepend('<img src="Background.jpg" id="bg" alt="" />')

var theWindow        = $(window),
    $bg              = $("#bg"),
    aspectRatio      = $bg.width() / $bg.height();

function resizeBg() {

    if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
        $bg
            .removeClass()
            .addClass('bgheight');
    } else {
        $bg
            .removeClass()
            .addClass('bgwidth');
    }

}

theWindow.resize(resizeBg).trigger("resize");

});

Answer №1

Some time ago, I created a function that is quite similar:

HTML

<img src="http://ge.tt/api/1/files/1jN8IzR/0/blob?download" class='bg'>

CSS not really required

.bg {
    position: fixed;
    top: 0;
    left: 0;
    z-index: -1
}

JS

var fitPic = (function() {
    var winW = $(window).width(),
        winH = window.innerHeight || $(window).height(); // `innerHeight` for mobile safari

    $(".bg").each(function() {

        var elem = $(this),
            elemW = elem.width(),
            elemH = elem.height(),

            imgW = (elemW * winH) / elemH,
            imgH = (elemH * winW) / elemW,

            newW = imgH < winH ? imgW : winW,
            newH = imgH < winH ? winH : imgH;

        this.style.width = newW + "px";
        this.style.height = newH + "px";

    });
});

$(window).on('load resize', fitPic);

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 showing a URL within an onclick event using the jQuery Append method

My method involves using AJAX to upload images and then displaying the uploaded image by utilizing the jQuery append function. The challenge comes when I try to add an onclick event to the specific image tag. To tackle this, I start by creating a JavaScri ...

Troubleshooting: Border not showing up in Tailwind CSS (React JS)

Below is the code snippet from my JSX file: import { useState, useEffect } from "react"; import { PropTypes } from "prop-types"; import { HashtagIcon } from "@heroicons/react/24/outline"; // Function to fetch categories from the API (temporary replaced wi ...

Modify the image inside a div when hovering

How can I create a product card that displays thumbnails of images when hovered over, and changes the main image to the thumbnail image? My current challenge is getting this functionality to work individually for each card on an e-commerce site. Currently, ...

Attempting to configure the <img> element to automatically adjust its size in accordance with the page dimensions

<center> <img style="width: 100%; max-height: 100%" src="images/ratios/3to2ratio.JPG" /> This is a traditional 35mm Still Film ratio of 3:2. </center> Although this code allows the image to scale with the page size, I prefer ...

Is the vertical 3D carousel malfunctioning?

While working on a vertical carousel and rotating it 180deg on the X-axis, I noticed that the backside of the carousel appears to have an incorrect orientation in 3D space. I'm looking for a solution that not only includes the code but also explains w ...

What steps can be taken to address an unusual conflict arising between a form post and an ajax post

One web page features the use of ajax for editing existing values. This is achieved by utilizing jQuery Inline Edit to post new data, update records, and return with success. The process works well initially. Subsequently, I implemented the functionality ...

Deleting a segment of code in HTML with Python

My HTML text is lengthy and follows this structure: <div> <div> <p>Paragraph 1 Lorem ipsum dolor... long text... </p> <p>Paragraph 2 Lorem ipsum dolor... long text... </p> <p>Paragraph ...

Is there a way to dynamically adjust a node's rotation using both jQuery and vanilla JavaScript, incorporating the transform property rotate(30deg)?

1. When aiming to support as many browsers as possible, which of the following is the optimal choice?: -webkit-transform: rotate(30deg); -moz-transform: rotate(30deg); -ms-transform: rotate(30deg); -o-transform: rotate(30deg); transform: rotate(30deg); ...

Changing the div background color based on the status of the `.play()` function

I need assistance with changing the background color of a div based on whether an audio file is playing or not. $('.uprow2').on('click', function() { $('#karma')[0].play(); }); .uprow2 { width: 680px; height: 60px; ...

Troubleshooting a unique problem with custom mat errors in Angular File Upload

In my Angular 5 app, I have a file upload form where I need to show a custom error message if the file format does not match certain criteria: The error message that should be displayed to the user is: "Only PDF, Excel, PowerPoint, or Audio (wav and wmv) ...

The CSS styling for changing the color of a button in React JS is not

Creating a custom css style in mypagestyle.styl with the following properties: :local .mybutton border-radius: 1px; padding: 2px; margin: 2px; font-size: 14px; text-align: center; background-color: #4582ec; color: #fff; All styles are being ...

AngularJS - Textarea not resetting content on ng-click event

Having an issue with my textarea. When attempting to clear it using ng-click, nothing happens... Can anyone provide assistance? Here is my code for testing: My app If you prefer to view it here: HTML : <div ng-controller="Ctrl1"> <d ...

What is the best way to retrieve the value of the nearest text input using JavaScript?

I am currently working on designing an HTML table that includes a time picker in one column for the start time and another time picker in a separate column for the end time within the same row. My goal is to retrieve both values (start time and end time), ...

Unable to move the content inside a fixed container by scrolling

Having difficulties with a menu layout where the parent container spans across the entire site and a div contains the actual content. Everything looks fine on larger screens, but on mobile devices, it's challenging to display all the content. I' ...

Refine Image Display when Scaling Down on Screen

When I zoom in, the image area goes off-screen. I want it to stay fixed in place. <img style="margin-bottom:-10px;width:280px;height:280px;border-adius:50% ;border:3px solid white" id="image" src="@Model.Image" /> <br /> <a id="editbutto ...

The fadeOut function in jQuery isn't functioning as expected

Looking to design an eye-catching jQuery banner ad. The content is styled in the following way: <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Open House : Banner Advertisements</title> ...

What is the process for sending JavaScript with an Ajax request?

Working with ajax and javascript for the first time, I'm no expert in web development. Here is the code I've written and tested so far. I have a select div containing some options. <select id="month" onchange="refreshGraph()"> When an op ...

The function .jqGrid() cannot be found when trying to call it on an .aspx webpage

I successfully integrated a JQgrid into my Visual Studio 2010 project, but I encountered an error when trying to add it to my Visual Studio 2013 web project. The error message reads: $(...).jqGrid is not a function empty string passed to getElementById H ...

Blazor compatibility issue with Bootstrap 5 carousel functionality

Check out the link below to view a carousel that is functioning with the help of jquery and bootstrap 4.3.1 (code lines 48,50). I attempted to switch to using Bootstrap 5 JS files for the carousel, but it did not work as expected due to issues with code li ...

Issue with React Material UI: Box is not scrollable vertically

I've been grappling with this issue for hours and could really use some assistance. My goal is to create a Chat component that allows vertical scrolling, but I've hit a roadblock. Here's a simplified version of the problem on Codesandbox: ht ...