Using JavaScript to ensure that a background image is only displayed once in an HTML document

I am currently working with two cells, where I have set background images for these cells using Javascript from an array of images.

The images available are:

image1= 150*150 referred to as image1 once

image2=150*150 referred to as image2 once

However, a problem arises when setting the images as background images for the cells. The same image gets repeated multiple times within each cell,

For example, Image1 appears three times in cell[1].

`I am seeking guidance on how to solve this issue and make sure that the background image appears only once, fitting perfectly into each entire cell.

var images = [
  {label: '1',url: 'https://via.placeholder.com/150x150.jpg?text=image1'},
  {label: '2',url: 'https://via.placeholder.com/150x150.jpg?text=image2'}
];

function bgsetting() {
  boxtags = document.getElementsByClassName("cell");

  boxtags[0].style.backgroundImage = 'url(' + images[0].url + ')'; 
  boxtags[1].style.backgroundImage = 'url(' + images[1].url + ')'; 

}

bgsetting();
.cell {
  width: calc(33.3% - 4px);
  border: 2px solid #333;
  margin: -2px;
  background-color: #99ffff;
  height: 15vh;
  display: inline-flex;
  align-items: center;
  background-size:contain;
}
<div id="container">
  <div class="cell"  ></div>
  <div class="cell"  ></div>
</div>

Answer №1

Ensure that the background-image is not repeated by setting the background-repeat property to no-repeat. This will display the image only once.

To make the image fit into each cell, you can utilize background-size: cover and background-position: center.

var images = [{label: '1',url: 'https://via.placeholder.com/150x150.jpg?text=image1'},
{label: '2',url: 'https://via.placeholder.com/150x150.jpg?text=image2'}];

function bgsetting() {
  boxtags = document.getElementsByClassName("cell");

  boxtags[0].style.backgroundImage = 'url(' + images[0].url + ')'; 
  boxtags[1].style.backgroundImage = 'url(' + images[1].url + ')'; 
}

bgsetting();
.cell {
  width: calc(33.3% - 4px);
  border: 2px solid #333;
  margin: -2px;
  background-color: #99ffff;
  height: 15vh;
  display: inline-flex;
  align-items: center;
  background-size:contain;
  
  /* style to set image properly*/
  background-repeat:no-repeat;
  background-size: cover;
  background-position: center; 
}
<div id="container">
  <div class="cell"></div>
  <div class="cell"></div>
</div>

Answer №2

Simply include this css code in your project...

.cell {
    background-repeat:no-repeat;
    background-size: cover;
    background-position: center;
}

var images = [

{label: '1',url: 'https://via.placeholder.com/150x150.jpg?text=image1'},
{label: '2',url: 'https://via.placeholder.com/150x150.jpg?text=image2'}];

function bgsetting() 
{
boxtags = document.getElementsByClassName("cell");

boxtags[0].style.backgroundImage = 'url(' + images[0].url + ')'; 
boxtags[1].style.backgroundImage = 'url(' + images[1].url + ')'; 

}

bgsetting();
.cell {
  width: calc(33.3% - 4px);
  border: 2px solid #333;
  margin: -2px;
  background-color: #99ffff;
  height: 15vh;
  display: inline-flex;
  align-items: center;
  background-size:contain;
  background-repeat:no-repeat;
      background-size: cover;
    background-position: center;
}
<div id="container">
<div class="cell"  ></div>
<div class="cell"  ></div>
</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

Retrieving modified object values in Node.js - A comprehensive guide

How can I retrieve the modified value of an object? The file index.js is executed before index2.js and here's what my code looks like: var object = { size:'5' }; var setSize = function(size) { object.size = size; } exports.object ...

Scrolling through four limited list items automatically

Hey there! I am currently working on a design project. You can check it out here. I'm trying to replicate a section from another site, which you can see here. <div class="latest-winners-container"> <h3 class="header">Latest Winners< ...

Setting the title of the master page body dynamically

Looking for a solution similar to the one discussed below, I am attempting to extract the title entered in the title tag on each page and use it to update an asp label dynamically to display the title on each page. My goal is to achieve this using only C# ...

Issues with PHP Mail Forms not functioning as intended

I've been struggling for hours trying to figure this out. I'm new to PHP mail form coding and any assistance would be greatly appreciated! Below are two images: one of the HTML code and one of the PHP code. It seems like a simple setup, but even ...

Changing <br/> tag to (new line) using jQuery

I attempted to use the following code snippet in jQuery to replace the <br/> tag with "\n" (new line), but unfortunately it did not yield the desired result: $("#UserTextArea").html(data.projectDescription).replace(/\<br\>/g ...

JsDoc presents the complete code instead of the commented block

I have a VUE.JS application that needs to be documented. For .VUE components, we are using Vuese. However, when it comes to regular JS files like modules, we decided to use JsDoc. I have installed JsDoc and everything seems fine, but when I generate the HT ...

What are the distinctions between utilizing util.inherits() and prototypes for inheritance in node.js?

The method util.inherits() allows for the inheritance of methods from one function to another. Prototypes are also a way to achieve inheritance in JavaScript. I am wondering when it is best to use .inherits() versus changing the prototype chain. Any advi ...

What is the process for removing an item from a JSON file using an HTTP DELETE request in a Node.js environment?

Essentially, I have a JSON file containing user and group data and I need to delete a specific group from it. Below is a snippet of the JSON file named authdata.json: [{ "name": "Allan", "role": ["Group Admin", "Super Admin"], "group": ["Cool- ...

What is the process of adding a div to the left side of the parent element in AngularJS

I am trying to append the code on the left side of the click. My current controller code looks like this: demo.$inject = ['$scope']; demo.directive("boxCreator", function($compile){ return{ restrict: 'A', l ...

Prevent the use of harmful language by implementing jQuery or JavaScript

Is there a way for me to filter certain words (such as "sex") using regex, even when people use variations like "b a d", "b.a.d", or "b/a/d"? How can I prevent these kinds of words from getting through? I'm trying to filter more than just one word - ...

What's the reason this doesn't vanish when I hover over it?

Check out this JsFiddle link HTML Code <p>I am a duck</p> CSS Code p:hover { display:none; } Why is the text not disappearing when hovered over? ...

Updating the redux state in react by passing a variable from a child component to the parent

I'm currently in the process of updating my Redux state within a component by utilizing a variable that has been passed up to the component from a child, specifically through a form submission callback. The form is responsible for submitting a user&ap ...

Leveraging the power of JavaScript's .map(...) method in a

Within my React code, I have a structure similar to the following: {elements.map((element) => { return ( <div> {renderDate(element.date)} </div> ) }})} This structure calls the renderDate function defined as: co ...

Center the list items vertically within a div by using the class list-inline

Struggling to vertically center the unordered list '.header-top-widget' within a div. Despite trying several methods, I can't seem to get it centered. My attempts so far include: .header-top-widget { display:flex; align-items:center; } ...

The "util" module has been extracted to ensure compatibility with browsers. Trying to use "util.promisify" in client code is not possible

Currently, I'm in the process of scraping LinkedIn profiles with the help of this library: https://www.npmjs.com/package/@n-h-n/linkedin-profile-scraper. Listed below is the code snippet that I am using: <script> import { LinkedInProfileScraper ...

How can I convert an Array into a Dictionary using JavaScript?

Is there a clever method (perhaps using a map function) to restructure my data object from this: [ {id: 1, from: "1/1/2021", to: "1/2/2022"}, {id: 2, from: "1/3/2021", to: "1/4/2022"}, {id: 1, from: "1/5/2 ...

Content within the p tag is failing to wrap onto separate lines

Take a look at the image below: Here is the code causing issues: <div class="excerpt"> <p>Manual for downloading and installing digital content from the Educational Canaima Project, comprised of learning resources that aim to promote interac ...

Navigating to a specific page based on the selected option is the key to efficient web browsing

I'm currently working on a form development project and I'm looking for guidance on how to navigate to different pages based on the selection made in a radio button. Here's the current form setup with two radio buttons: .sh_k .sh_sl { ...

Finding the optimal image prediction from HTML using Google JSoup - A guide

Our goal is to accurately identify the best guess for an image based on the HTML content of the search results page returned by Google. Among the various classes present, we know that the best guess is associated with the class qb-b. To target this specifi ...

A compilation of approved classes for the quill toolbar

The instructions provided in the documentation for the quill module indicate that you can manually create a toolbar using HTML, and then pass the corresponding DOM element or selector to Quill. This will result in the ql-toolbar class being added to the to ...