Visualization:
[IMG]+[HIDDEN INPUT]-—-[TEXT]-—-[ICON]
[IMG]+[HIDDEN INPUT]-—-[TEXT]-—-[ICON]
[IMG]+[HIDDEN INPUT]-—-[TEXT]-—-[ICON]
(For each individual)
I am looking to match the background color of the icon on the right with the IMG on the left. The image used is an SVG avatar from Dicebear.
The concept is, if a user is identified as male (sex===M
), their avatar should have a blue background; if female, a pink one.
I attempted to achieve this by using a hidden input with their gender as the value (M, F, O
), and then processing it through a Javascript function on initialization;
function recolor() {
var x = document.querySelectorAll(".fa-icon");
for (let i = 0; i < x.length; i++) {
let sex = document.getElementById("sex").value;
let background;
if (sex === "M") {
background = "blue";
}
else if (sex === "F") {
background = "pink";
}
else {
background = "yellow";
}
x[i].style.backgroundColor = background;
}
}
Results varied from all icons displaying the background color from the last else condition, to them simply inheriting the color from their default CSS (which should be overridden by the DOM manipulation, right?)
My Javascript skills are still developing, and despite trying different iterations of the code above, I keep encountering diverse outcomes.
It is highly likely that I am overlooking something rather simple. Any assistance would be greatly appreciated!
Edit (the HTML):
<div class="container">
<div>
<img src="https://avatars.dicebear.com/api/avataaars/profile.svg?<?php echo $user->pf_settings ?>">
<input type="hidden" name="sex" id="sex" value="<?php echo $user->sex ?>">
</div>
<div>
<p><?php echo $user->text; ?></p>
</div>
<div>
<i class="fa fa-icon"></i>
</div>
</div>