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)?
You can do this without Javascript. Just use a
<label>
tag like this:By using the
for
andid
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 thefocus
event in JavaScript. You will need to style the placeholder label to useposition: absolute
. See live example (scroll down for some forms).The above method of defining placeholder text has some advantages:
placeholder
attribute.label
tag however You like, which is not so easy for theplaceholder
attribute. You can even use CSS or JS animations!