Luc
Luc

Reputation: 843

Replacing alpha inside rgba issue

I did the following function to replace the alpha inside an rgba string:

function replaceAlpha(elemAttr,alpha) {
    elemAttr = elemAttr.replace(elemAttr.substring(elemAttr.lastIndexOf(",")+1,elemAttr.lastIndexOf(")")),alpha)
}

but it doesn't seem to work even if the result is correct see:

function replaceAlpha(elemAttr,alpha) {
    elemAttr = elemAttr.replace(elemAttr.substring(elemAttr.lastIndexOf(",")+1,elemAttr.lastIndexOf(")")),alpha)
    console.log(elemAttr)
}
replaceAlpha(document.getElementById("invisibleSpan").style.backgroundColor,0)
<span id="invisibleSpan" style="background-color: rgba(0,0,0,0.5);color:white">I wanna be invisible</span>

what am I doing wrong?

Upvotes: 0

Views: 119

Answers (1)

Algef Almocera
Algef Almocera

Reputation: 819

What your issue here is thinking that the style would update directly from the function. You are simply generating the new style but not updating the background color itself. Here's an updated version of your code:

I simply returned your new value from your function and set it as the new background color.

function replaceAlpha(elemAttr,alpha) {
    return elemAttr.replace(elemAttr.substring(elemAttr.lastIndexOf(",")+1,elemAttr.lastIndexOf(")")),alpha)
}

const elem = document.getElementById("invisibleSpan")
const rgba = replaceAlpha(elem.style.backgroundColor,0);
elem.style.backgroundColor = rgba;

If you want to update it from the function, you can do this instead:

function replaceAlpha(element,alpha) {
    const backgroundColor = element.style.backgroundColor;
    const [r,g,b,a] = backgroundColor.split(',');
    const newBackgroundColor = [r,g,b,alpha].join(',') + ')';

    element.style.backgroundColor = newBackgroundColor;
}

const elem = document.getElementById("invisibleSpan")
replaceAlpha(elem, 0);

Added a way to update from the function itself with any element and color attribute. Note that this doesn't handle validations. You can encounter errors if you don't check whether the property you are replacing is actually a color, I'll leave that task to you:

function replaceAlpha(element, attribute, alpha) {
    const color = element.style[attribute];
    const [r,g,b,a] = color.split(',');
    const newColor = [r,g,b,alpha].join(',') + ')';

    element.style[attribute] = newColor;
}

const elem = document.getElementById("invisibleSpan")
replaceAlpha(elem, 'backgroundColor',0);

Upvotes: 2

Related Questions