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>
4
Answers
To get the image src using jquery, you can use:
$('.user-profile-box-img').attr('src');
then add this to .same-image-div class background-image: url("") property through Jquery or Javascript.
If you want to use an image src in CSS background image URL using javascript.
You have set the image using javascript simply like this :
element.style.background-image = "URL(‘img_tree.png’)";
If you want to "move" src attribute to a CSS attribute of the same element, in jQuery you should do this (with a little element caching):
Here is one way to do it using JavaScript:
Here is one way to do it using jQuery: