“This is the real secret of life -- to be completely engaged with what you are doing in the here and now. And instead of calling it work, realize it is play.” ― Alan Watts

Hide form labels and add them as placeholders instead

March 30, 2019

Here's a simple way to hide the labels on your web forms and move them into the inputs or text areas as a placeholder using jQuery. 

In my example I was using this script on a Drupal contact page, so I was checking that we were in fact on the contact page to begin with by looking for a html class in the body tag. This script assumes all of your form inputs share a common parent class, in my case it was '.form-item'.

My HTML structure was essentially as follows:

<div class="form-item">
      <label>Your name</label>
      <input  type="text">
<div class="form-item">
      <label>Your email</label>
      <input  type="text">
<div class="form-item">

I created a loop in jQuery that finds each of the '.form-item' divs and first finds the label, grabs the text from the label and assigns it to a variable called placeholder, then hides the label and creates the placeholder for any input or textarea within that form-item div.

(function($) {

	// if we are on the contact page
	if ($('body').hasClass('path-contact')) {
                // loops through each form item
		$('.form-item').each(function() {
			var placeholder = $(this).find('label').text();
			$(this).find('input, textarea').attr("placeholder", placeholder); 


If you are unsure how to add a javascript file in Drupal 8, here is the simplest method, find the file in your theme directory named your_theme_name.libraries.yml, the contents should look something similar to this:

      css/style.css: {}
      font-awesome/css/font-awesome.min.css: {}
    js/script.js: {}

As you can see I have added a Javascript file called 'script.js' which is in a folder called 'js' in my theme's folder. Don't forget to clear cache. If you want to know more about how to add javascript to a Drupal 8 project check out these instructions.