Advertisements
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 ?
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')})`);