I’m trying to overlay text over a text form field. The text should appear over (with illusion of being in) the text box when the focus event occurs, and stay there until the user actually types a letter. Before the focus even occurs, there is already default text.
There’s a similar/simpler variation where the box starts with a default value and the default value disappears on focus, but that’s not what I’m trying to do in this case.
The problem I’m having is getting the helper text to appear in the right spot once its inserted, specifically with setting the top and left css properties dynamically.
My onFocus function:
TrueThis.OldValue = $('#MyField').val(); // Save the current value
$('#MyField').val(''); // Empty the text box
var OverlayHTML = '<div>This is helper text that goes on top.</div>'
// Insert the Overlay and position the top and left to match the parent
// PROBLEM:: The element is inserted, but is not positioned.
// No top and left css attributes were assigned according to Firebug.
$('#MyField').after(OverlayHTML).css({
'top':$('#MyField').position.top,
'left':$('#MyField').position.left
});
// Remove the overlay when a user starts typing.
$('#MyField').next().keyup(function(){this.remove();});
I think the problem is that I’m not able to grab the new element, or possibly that it doesn’t exist in the DOM yet until the whole function completes?
Along with the suggestions from James, for the keyup function to work, I think you need to bind it to the actual text input, and remove the overlay using the .next() function inside the callback.
As for the position of the overlay, it depends on what the parents are of the text input. Say you have a relatively positioned div around the input:
The parent div creates a new coordinate system so you can set the overlay to absolute positioning: