I am currently working on a project with a menu of buttons that dynamically changes based on the elements in a list. For instance, if my list contains ["A", "B", "C"], then I would have a menu with 3 buttons.
Here is how I display the buttons using a javascript plugin:
html += '<div id="buttonGallery">'
// add buttons for each element in the list
_.map(myList, function(letters, ind) {
html += '<div id="button_' + letters + '" class="buttons">';
html += '<p>' + letters + '</p></div>';
});
I am facing an issue where I need to change the background-color of each button when hovered over by the user. The challenge is that each button does not have a set id, making it difficult to target them individually in CSS.
I want my solution to be flexible and applicable to different scenarios where the list may contain different elements like "D" and "E". In such cases, there might be only 2 buttons, each with unique hover colors.
If anyone has suggestions on how to approach this problem, I would greatly appreciate your input!
Below is a simplified version of the code I am working with, but please note that it assigns explicit ids to the buttons which is not ideal for my generalizable solution. In this example, all buttons turn red when hovered over.)
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<style media="screen">
.buttons {
width: 150px;
height: 50px;
border: solid 2px black;
text-align: center;
color: black;
cursor: pointer;
background-color: white;
margin: 2px;
}
#buttonGallery {
margin: 10px;
padding: 10px;
border: solid 2px black;
width: 155px;
}
.buttons:hover {
background-color: red !important;
border: solid 3px black !important;
}
.selected {
background-color: red !important;
border: solid 3px black !important;
}
</style>
</head>
<body>
<div id="buttonGallery">
<div class="buttons">
<p>A</p>
</div>
<div id="button_B" class="buttons">
<p>B</p>
</div>
<div id="button_C" class="buttons">
<p>C</p>
</div>
</div>
<script type="text/javascript">
$('.buttons').click(function() {
$(".buttons").not($(this)).removeClass("selected");
$(this).toggleClass("selected");
</script>
</body>
</html>
(If you require further clarification, feel free to provide feedback on how I can improve the clarity of my post. Thank you!)