Question

I'd like to place a custom placeholder text element above a text input (input type='text' or textarea). However, I can't figure out how to make the text input clickable when the placeholder text element is right above it. Setting pointer-events:none to make the placeholder unclickable works great, but is not supported in older versions of IE.

Workarounds to pointer-events:none typically involve manually triggering the onclick of the child element. However, for a text input, the onclick is done implicitly by the browser, so there's no event to trigger.

Other solutions I've considered include setting an onclick on the placeholder to focus the text input, but this means the cursor is always placed at the end of the input. I want to be able to click on the text input and have the cursor appear where I click.

Another option is to use z-index to place the placeholder below the input, and then make the input transparent. However, this also removes the default border of the input, which is undesirable.

How can a text input be clickable even when text is showing above it, using only HTML/CSS and pure Javascript (no jquery)?

Was it helpful?

Solution

You can do this without Javascript. Just use a <label> tag like this:

<label class="placeholder" for="name">Name</label>
<input type="text" id="name">

By using the for and id attributes when clicking on the label, browser will switch focus to the linked form field. Then You can for example hide the placeholder by listening on the focus event in JavaScript. You will need to style the placeholder label to use position: absolute. See live example (scroll down for some forms).

The above method of defining placeholder text has some advantages:

  1. You actually define a label for a field. This probably can help accessibility.
  2. You separate form field's value and placeholder text, so You can support forms that are partially filled.
  3. You can support more browsers than by using the placeholder attribute.
  4. You can style the label tag however You like, which is not so easy for the placeholder attribute. You can even use CSS or JS animations!
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top