Search code examples
javascriptimagebuttonimagebutton

Using custom backgrounds for buttons created through JavaScript


Trying to have a button created in JavaScript to use the background image of the specific API image I seen many suggestions to use .style.backgroundImage = 'Url("yourimagelink")';. But can't seem to figure it out.

Updated to include my function.

//  The "addListItem" function creates li and button for item names also creates event on click

function addListItem(item) {
    let groupList = document.querySelector('.list-group');

    let listItem = document.createElement('li');
    listItem.classList.add('list-group-item');

    let button = document.createElement('button');
    button.classList.add('btn-image');
    button.innerText = item.name;
    button.style.backgroundImage = 'Url("item.imageUrl")';

    listItem.appendChild(button);

    groupList.appendChild(listItem);

    button.addEventListener('click', function () {
        showDetails(item);
    });
};

No image appears and no errors too.


Solution

  • You should add the button to the DOM, using appendChild for example, createElement only creates the button instance, it is not added to the DOM.

    Working example below:

    item = { name: 'test', imageUrl: 'https://images.unsplash.com/profile-1446404465118-3a53b909cc82?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=32&w=32&s=a2f8c40e39b8dfee1534eb32acfa6bc7' };
    
    let button = document.createElement('button'); // It only create the button instance, but don't add it to the DOM
    document.body.appendChild(button); // You should add the button to the DOM
    button.classList.add('btn-image');
    button.innerText = item.name;
    button.style.backgroundImage = `url(${item.imageUrl})`;