skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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’)";

    document.body.style.background-image = "URL('https://images.unsplash.com/photo-1661956602139-ec64991b8b16?ixlib=rb-4.0.3&ixid=MnwxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2765&q=80')";
    
    Login or Signup to reply.
  3. 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):

    let element = $('img.user-profile-box-img');
    element.css('background-image', 'url('+element.attr('src')+')');
    
    Login or Signup to reply.
  4. 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')})`);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search