A dynamic number of divs are generated from a data source. Each div contains an image button and another div with text. While the actual scenario is more complex, we can present a simplified version:
<div id="main">
<div id="content_block_1" class="content_block">
<img id="content_block_button_1" class="content_block_button" src="images/1.png">
<div id="content_block_textfield_1" class="content_block_textfield>
This is some text.
</div>
</div>
<div id="content_block_2" class="content_block">
<img id="content_block_button_2" class="content_block_button" src="images/2.png">
<div id="content_block_textfield_2" class="content_block_textfield>
This is more content.
</div>
</div>
<div id="content_block_3" class="content_block">
<img id="content_block_button_3" class="content_block_button" src="images/3.png">
<div id="content_block_textfield_3" class="content_block_textfield>
This is even more content.
</div>
</div>
</div>
When users click on the images, they should be able to change the background color of the relevant textfield to yellow. If the textfield is already yellow, it should revert back to its normal background color. If one textfield is highlighted while another already is, the existing highlights should be removed before activating the new one.
I am aware of using the toggle() function to manage the .highlight css class. Here's a simplistic yet inefficient function I developed for this purpose:
//1st
$('#content_block_button_1').click(function () {
//toggle the associated
$('#content_block_textfield_1').toggleClass('highlight');
//reset other highlights
$('#content_block_textfield_2, #content_block_textfield_3').removeClass('highlight');
console.log("toggled highlight 1");
});
//2nd
$('#content_block_button_2').click(function () {
//toggle the related
$('#content_block_textfield_2').toggleClass('highlight');
//reset other highlights
$('#content_block_textfield_1, #content_block_textfield_3').removeClass('highlight');
console.log("toggled highlight 2");
});
//3rd
$('#content_block_button_3').click(function () {
//toggle the respective
$('#content_block_textfield_3').toggleClass('highlight');
//reset other highlights
$('#content_block_textfield_1, #content_block_textfield_2').removeClass('highlight');
console.log("toggled highlight 3");
});
This code lacks elegance and scalability. It's clear that a better approach is needed.
I aim to utilize the fact that the button and textfield elements share the same "parent". I seek a way to remove the .highlight class from all textfields except the one directly linked to the button calling the function, without relying on specific ids. Ideally, this solution would work seamlessly regardless of the number of content blocks.
If anyone can provide guidance in the right direction, it would be greatly appreciated.