css background is repeating after the height of the div is reset

I'm working on a project where I want to resize an image while maintaining its aspect ratio to fit the height/width of the browser window. However, every time the code for resizing is implemented, the div height continues to increase with each resize event instead of just adjusting to the new height. How can I prevent the div from growing in this manner?

<div class="header-pc" style="background-image: url('assets/sunset-flipped1.png');background-size: 100% auto;height:1000px"></div>

function resizeHeaderPic(){
    var height = $(window).height();
    $('.header-pc').height(height);
}
$(document).ready(function(){
    //resizeHeaderPic();
    $(window).resize(function(){
        resizeHeaderPic();
    });
});

Answer №1

Avoid using Javascript unnecessarily for simple CSS tasks.

body {
    background-image: url('assets/sunset-flipped1.png');
    background-size: cover;         /* Adjust to fit the entire element */
    background-position: center;    /* Specify scaling starting point in the image */
}

With this approach, you can achieve the desired result without any need for HTML or Javascript involvement.

Answer №2

Niels has a solid approach here. By setting the height of the div to window.height, we need to keep in mind that window height is actually window.innerheight + scrollbar/toolbar. This means that every time it increases by the size of the scrollbar.

function resizeHeaderPic(){
    var height = $(window).innerHeight();
    $('.header-pc').height(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

Transforming a JSON into a JavaScript object using deserialization

Within a Java server application, there exists a string that can be accessed through AJAX. The structure of this string is exemplified below: var json = [{ "adjacencies": [ { "nodeTo": "graphnode2", "nodeFrom": "graphnode1" ...

Using Javascript, you can create a function that can disable or enable a text link based on

Here is the code snippet showcasing CSS styles and HTML elements: CSS: .enableLink{ font-family:Verdana, Geneva, sans-serif; font-size:12px; color:#069; padding-right:20px; text-decoration:underline; cursor:pointer; } .disableLink{ display:none; fon ...

An unexpected error occurred while parsing the JSON document: "unexpected token: '{'"

I'm facing an issue where I need to specify a URL in a JavaScript app that retrieves weather data from an API. The URL is constructed using a string and some variables. When I initially wrote the code below, I encountered the error message Missing { b ...

Navigating File Paths in Node.js

My directory structure is as follows: Main > models > file1.ejs | |> routes > file2.ejs In my code, I'm trying to require file1 from file2 like this: const variable = require("../models/file1.ejs). But what if I don't want to use relative ...

Arrange objects in an array according to the order specified in another array

Here is my array of car makes: const makes = [ {id: "4", name: "Audi"}, {id: "5", name: "Bmw"}, {id: "6", name: "Porsche"}, {id: "31", name: "Seat"}, {id: "32", name: "Skoda"}, {id: "36", name: "Toyota"}, {id: "38", name: "Volkswagen"} ] Now, I want to o ...

a script in JavaScript that retrieves the selected value from a radio button box

I have an AJAX table where I need to highlight one of the rows with a radio box on the left side. However, I lack proficiency in JavaScript and would like assistance in retrieving the value of the radio box by its ID from this table once it has been select ...

Space constraints within an li element

Is there a solution to resolve the unusual impact of margins/paddings? Check out this example on jsfiddle: jsfiddle. Here is the screenshot of the issue: i.imgur.com/64S8C.jpg. I want to eliminate any margins/paddings in the li element. ...

Tips for stopping a click from going through a fixed element to the one in the background

My website features a fixed positioned header with a search box, overlaying content below it (thanks to the higher z-index). When I click on the search box, an event handler is triggered. However, the click response also passes through the header to the ...

Utilize the DataTables plugin to arrange a column based on icons with hidden boolean values in rows

I am currently utilizing the DataTables plugin to enhance my HTML table. While I have managed to successfully implement most functionalities, I am facing a challenge with the boolean column. This particular column consists of icons representing X (value 0) ...

Struggling to locate desired href links using BeautifulSoup

I'm currently working on compiling a list of hrefs from the Netflix job portal: . Each job posting on this platform comes with an anchor and a specific class: <a class=css-2y5mtm essqqm81>. To ensure accuracy, here is the complete anchor: <a ...

Managing selected ticket IDs in a table with AngularJS

I have a table that includes options for navigating to the next and previous pages using corresponding buttons. When I trigger actions for moving to the previous or next page (via controller methods), I store the IDs of checked tickets in an array $scope. ...

Revoke the prior invocation of the Google Maps geocoding function

While working on implementing an autocomplete with JavaScript and the Google Maps geocode method (using the keyup event on input), I have encountered a problem where I sometimes receive the results of the previous search instead of the current one. I am l ...

Dynamic way to fetch computed properties in VueJS

I am trying to find a way to calculate the sum of computed properties that begin with the string calculateSum. The challenge is that I cannot access their names using this.computed. Here is my approach: getSubTotal(){ var computed_names = []; var ...

Connecting an admin dashboard to a MERN e-commerce application: A step-by-step guide

In the process of developing an e-commerce platform, I find myself using React.js for the frontend and Node.js/Express.js for the backend. My current challenge lies in creating a seamless dashboard to manage items within the app. One possible solution wo ...

Node.js is throwing an error code 344, indicating that it is not possible to manipulate headers after they have already been

I'm still learning about Node and I've encountered this confusing error that I can't seem to figure out. I've searched for similar cases online, but none of them quite match mine. Any help would be greatly appreciated. From what I gathe ...

Tips for adding color to the <td> element in an ejs file using nodeJS

I am looking to incorporate a color into my .ejs file. Here is the code snippet I am working with: <% resultList.forEach(function(item, index){ %> <tr> <td><%= item.function %></td> <td><%= item.value %>< ...

Efficiently loading components in Angular using browserify with lazy loading

As I work on developing the architecture of a complex application with Angular, I have started with the angular-seed project which seems to be a solid starting point. However, one issue that concerns me is how Angular apps tend to load everything upfront b ...

What is the most effective method to arrange absolute divs generated randomly in a grid-like formation?

Hey there! I'm facing an intriguing challenge with my app. It's designed to generate a variable number of divs which are always in absolute positioning. Unfortunately, making them relative is not an option due to some other factors within the app ...

Expansive dropdown menu stretching across the entire width, yet the content within restricted to a width of

I have recently made some updates to our website's dropdown menu, expanding the results displayed. However, I would like the dropdown contents to fit within the width of our page. I have tried adjusting the CSS with limited success: .menu > ul > ...

Attempting to display a singular form

Currently, I am working on a MERN app and encountering a small issue... I am developing an application where users can create rooms and within those rooms, they can plan their daily activities. It's similar to a TODO app but more intricate. I wanted ...