Hide form labels and add them as placeholders instead

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:

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

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() {
			$(this).find('label').css('display','none');
			var placeholder = $(this).find('label').text();
			$(this).find('input, textarea').attr("placeholder", placeholder); 
		});
	} 

})(jQuery)

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:

global-styling:
  css:
    theme:
      css/style.css: {}
      font-awesome/css/font-awesome.min.css: {}
  js:
    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.