Use the Drupal core CSS class to hide form elements when JavaScript is enabled

Created on 26 March 2023, about 2 years ago
Updated 16 July 2024, 9 months ago

The form examples show how to add graceful degradation so AJAX behavior can work when JavaScript is disabled. This is done with a submission button that's hidden with a CSS class.

    // Since we don't know if the user has js or not, we always need to output
    // this element, then hide it with with css if javascript is enabled.
    $form['instrument_family_fieldset']['choose_family'] = [
      '#type' => 'submit',
      '#value' => $this->t('Choose'),
      '#attributes' => ['class' => ['ajax-example-hide', 'ajax-example-inline']],
    ];

This is using a custom CSS class.

However, Drupal core already provides a CSS class for the same purpose.

/**
 * For anything you want to hide on page load when JS is enabled, so
 * that you can use the JS to control visibility and avoid flicker.
 */
.js .js-hide {
  display: none;
}

The example should use the CSS class already defined from Drupal core, instead of using a new CSS class.

📌 Task
Status

Fixed

Version

4.0

Component

AJAX Example

Created by

🇬🇧United Kingdom joachim

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Merge Requests

Comments & Activities

Production build 0.71.5 2024