Extract the URL of the background image from a preexisting <div> element, or append a new attribute to the background-image property

I am facing a challenge in updating the existing background-image with a linear gradient. Currently, my CMS is generating a background-image, but I am unable to adjust the opacity using a linear gradient. My goal is to darken the background-image using CSS.

Here is my approach -> Extracting the URL from all div elements with the class of "bg-image" to then use the "setAttribute" method to apply a new background-image property.

   var elems = document.getElementsByClassName("bg-image");
    for (var i = 0, n = elems.length; i<n; ++i){
        var img = document.getElementsByClassName('bg-image')[i],
            bi = style.backgroundImage.slice(4, -1);

        img.setAttribute('style', 'background-image: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5),url("' bi +'"));');};

Answer №1

Since you have tagged jQuery, I assume you are open to using it alongside vanilla JavaScript:

$(".bg-image").each({
    $(this).css({
        backgroundImage:"inear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5),"+$(this).css("backgroundImage"));
    });
});

Alternative approach without jQuery:

If you prefer using vanilla JavaScript, the issue lies in the line

bi = style.backgroundImage.slice(4, -1);
, which should likely be
bi = img.style.backgroundImage.slice(4, -1);
.

Moreover, avoid setting styles like this

img.setAttribute('style', 'background-image: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5),url("' bi +'"));')

Instead, use

img.style.backgroundImage="linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5),url("+bi+")";

Since you are reintroducing it as a URL, there is no necessity to extract it using slice. Also, there is no need to reselect the element.

var elems = document.getElementsByClassName("bg-image");
for (var i = 0; i<elems.length; i++){
    var bi = elems[i].style.backgroundImage;
    elems[i].style.backgroundImage="linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5),"+bi;
}

Answer №2

You can achieve this effect without relying on javascript. Here's a Simple CSS approach:

The key idea is to utilize the :before selector to apply styling.

The implementation may vary depending on the structure of your background-styled HTML element, but you can utilize z-index to control the stacking order if needed (Alternatively, if the background image is set using CSS, you can apply it to #content:before, transfer the rgba to #content, making z-index adjustment unnecessary).

Feel free to check out the code snippet below to visualize the effect (I've added a red tint for visibility purposes).

#content {
  width: 400px;
  height: 200px;
  background: url("http://lorempixel.com/g/400/200/city/1/");
  position: relative;
  z-index: 1;
  color: white;
}
#content:before {
  content: "";
  position: absolute;
  z-index: 1;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  /* A gradient isn't necessary with this approach */
  background: rgba(255, 0, 0, 0.5);
}
<div id="content">
</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

The preselected value in an AngularJS select box is set to static HTML by

In my HTML, I have a select tag that I am populating using ng-repeat. <td> <select ng-model="item.data.region" style="margin-bottom: 2px;"> <option ng-repeat="region in vm.regions track by $index" value="{{region}}">{{region} ...

Tips for keeping a floating action button visible at the bottom of the screen at all times

I am currently utilizing the Material UI framework. I have a floating action button that I would like to display in a specific position on the page without it moving when scrolling, and I am also wondering if this is a common issue. Below is the code sn ...

Utilize the entire width for header elements

I have implemented four header elements: home, about, portfolio, and contact. I want these elements to stretch across the entire navigation bar with each taking up 25% of the space. How can I achieve this? Additionally, I specified that the home element sh ...

Enhancing AngularJs code effectiveness through the use of MVC framework

I'm completely new to AngularJs and still trying to grasp the concepts. I have a few questions that I hope someone can help me with: Is it possible to trigger code in the controller only when a button is clicked, rather than having it load with the ...

A helpful guide on resetting ReactJs to its default state when data is not found

Currently, I'm fetching data from my database, but just for the sake of this question, I have opted to manually create an example with fake data. I am in the process of creating a search bar for my users to navigate through all the data retrieved fro ...

PHP does not receive the submitted data from a JavaScript form submission

It appears that the form is submitting to the same page (contact.php), but I am unable to access the posted data, such as $_POST["message"]. It seems that these values are empty as nothing is being echoed out. Here is the JavaScript code in the head secti ...

Transfer the values selected from checkboxes into an HTML input field

I am attempting to capture the values of checkboxes and then insert them into an input field once they have been checked. Using JavaScript, I have managed to show these values in a <span> tag successfully. However, when trying to do the same within a ...

Creating a callback function within its own definition

I need help with my download function that is calling a callback to "downloadCallback". Is it possible to define the downloadCallback function inside the download function itself? If so, how can I achieve this? Below is the implementation of the download ...

Ways to modify the CSS of an active class within a child component when clicking on another shared component in angular

In my HTML template, I am encountering an issue with two common components. When I click on the app-header link, its active class is applied. However, when I proceed to click on the side navbar's link, its active class also gets applied. I want to en ...

Update the array state based on the selection of checkboxes and user input in real-time

In my current project using react js, I am working on a UI development task where I need to create a dynamic table based on data fetched from an API. Each row in the table includes a checkbox and a text input field that are dynamically generated. My goal i ...

Adding the jQuery library to Ember's jQuery integration

I am currently in the process of integrating an 'ember-cli' application into my existing 'main app'. Main App mylibs.js jquery.js my_validator_jquery.js Ember CLI App vendor.js (generated by Ember) mylibs.js (from main app) ...

What could be causing the search function of the datatable to be hidden?

I am experiencing some difficulties with the code I have. My goal is to incorporate search functionality and pagination into my table. Unfortunately, it does not seem to be working as expected. Below is a snippet of the script located in the header section ...

Is there a way to simulate a middle mouse click using Selenium and JavaScript?

I am looking to simulate a middle button mouse click on a text URL within a webpage using Selenium code in JavaScript so that it opens in a new tab. Here's an example: await driver.get("https://google.com"); // This is the xpath for the &a ...

Choose a particular optgroup simultaneously using custom JavaScript

Check out this Fiddle for an example I am facing a situation where I have two different types of option groups with options. My challenge is to ensure validation between these two groups. How can I achieve this? Situation 1 If I select something from g ...

Refreshing the parent page in Oracle Apex upon closing the child window.When the child window

I have created an interactive report with a form where the interactive report is on page 2 as the parent page and the form page is on page 3 as the child page. In the parent page, I have written JavaScript to open a modal window (form page - page 3) using ...

Guide to utilizing Bootstrap v4 SCSS edition in a Bower project

Recently, I have been using the SASS/SCSS version of Bootstrap #3.3.6 but I just found out that they released version 4. While there is a lot of information on how to use Bootstrap v4 (non SCSS) in projects, I'm having trouble finding resources on ho ...

Is there a way to retrieve the hand-drawn lines at no cost in the form of a list, with each line represented as a collection of coordinates

I am currently contemplating the idea of utilizing fabric.js for an online handwriting recognition system. In order to make this system work, I need to transmit the sketched lines as a collection of lines, where each line consists of several points. If a ...

Guide on implementing various styles for a class in Tailwind CSS when transitioning to dark mode with the help of Next.js 13.4 and next-theme

Is it possible to apply unique styles for a class in Tailwind CSS when transitioning to dark mode using Next.js 13.4 and next-theme? I am currently setting up a dark theme in Tailwind CSS with Next.js 13.4 utilizing next-theme. Within my globals.css file, ...

Verify whether a pop-up window has been opened

Situation: Greetings, I provide a sensitive service to my clients. However, some of them are generating advertisement popups (using JavaScript) on their websites where my service is integrated, causing issues for us. My service involves a .js file hosted ...

Encasing the Angular 2 component template in a <div> tag

Currently, I have a parent component managing multiple child components. My goal is to enclose each child component's template with a *ngIf directive for conditional rendering. The number of children in the parent component can vary. Here is an examp ...