I'm a bit lost with this and could do with some help from a Drupal JS veteran.
In my module I'm dynamically generating a settings form based on a CSS file, part of which provides a font select list with real-time updated preview text underneath. There can be any number of these font select lists + preview depending on the contents of the CSS file. The relevant (simplified) markup is something like:
<!-- First font select & preview -->
<div id="font-selector-group-1" class="font-selector-group">
<label for="font-select-1">Font</label>
<select id="font-select-1" class="font-select" name="font-select-1">
<option value="arial">Arial</option>
<option value="verdana">Verdana</option>
<option value="helvetica">Helvetica</option>
</select>
<div id="font-preview-1" class="font-preview">Preview: <span class="">The quick brown fox jumped etc ...</span></div>
</div>
<!-- Second font select & preview -->
<div id="font-selector-group-2" class="font-selector-group">
<label for="font-select-2">Font</label>
<select id="font-select-2" class="font-select" name="font-select-2">
<option value="arial">Arial</option>
<option value="verdana">Verdana</option>
<option value="helvetica">Helvetica</option>
</select>
<div id="font-preview-2" class="font-preview">Preview: <span class="">The quick brown fox jumped etc ...</span></div>
</div>
<!-- Et cetera ... -->
In addition to styling (applying the correct font to) each font option I also want to change the class of #font-preview-x span
to the selected option value from the relevant #font-select-x
(i.e. "arial", "verdana" etc), thus showing a real-time preview of what the font will look like.
At present I have all this working OK using something like the following in my form array to change the preview text's class to the correct font class:
'#attributes' => array(
'onchange' => "jQuery('#font-preview-" . $i . " span').removeClass().addClass(jQuery('select[name=\"font-select-" . $i ."\"]').val());",
),
This mostly works onchange but not on page load, but on reading up further I gather there is probably a cleaner and better way i.e. using '#attached'
to attach a Drupal behaviour, and I also shouldn't need to pass in the specific id. With jQuery I should be able to attach event handlers to each font select that update their respective preview text.
Any direction or advice would be much appreciated, as this aspect of Drupal is relatively new to me. Have read the docs and googled around but still am a little lost.