Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Us image src url in CSS background image url using javascript or jquery

I’m novice at Javascript. I want to use an image src in CSS background image url using javascript.

For example, <img class="user-profile-box-img" src="https://img.freepik.com/free-photo/portrait-young-man-using-mobile-phone-while-standing-outdoors_58466-16294.jpg"/>

This is an image src to show image. I want to use the same image url in css background-image: url(""), so that I don’t need to write twice the same url. How can I do it using javascript or jquery ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

To sum up, I’ll just write image src once inside img tag, and it will automatically add in background-image: url("");

Code Example:

.same-image-div {
    width: 100%;
    margin: auto;
    padding: 60px 15px!important;
background-image: linear-gradient(rgba(38, 70, 235, 0.4), rgba(38, 70, 235, 0.4)),    
url(" here I want the "user-profile-box-img" class image src url ");
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
}

.user-profile-box-img{
width: 50%;
margin: auto;
}
<div class="same-image-div">
<img class="user-profile-box-img" src="https://img.freepik.com/free-photo/portrait-young-man-using-mobile-phone-while-standing-outdoors_58466-16294.jpg"/>
</div>

>Solution :

Here is one way to do it using JavaScript:

const img = document.querySelector('.user-profile-box-img');
const div = document.querySelector('.same-image-div');
div.style.backgroundImage = `linear-gradient(rgba(38, 70, 235, 0.4), rgba(38, 70, 235, 0.4)), url(${img.src})`;

Here is one way to do it using jQuery:

const img = $('.user-profile-box-img');
const div = $('.same-image-div');
div.css('background-image', `linear-gradient(rgba(38, 70, 235, 0.4), rgba(38, 70, 235, 0.4)), url(${img.attr('src')})`);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading