essentially I have a textbox on my webpage, and I’m trying to add a “clear” button like in iOS. I have a normal input, and an img tag (with the reset button). So far, I’ve used CSS relative positioning to make it look like the image is inside the textbox.
I’ve set the image to disappear when the text field loses focus (onfocus/onblur for the input) with javascript. I’ve got a few problems:
-
The onclick code never executes for the img tag because it goes away right when the input loses focus. (fixed with onmousedown but I’d like a more elegant solution)
-
I can’t seem to refocus the text input after click, using document.getElementById(‘searchbox’).focus(); (I checked the id is correct).
So I’m thinking I’m not doing this the best way, I’m wondering if I can somehow group the input and reset button better (they’re both in the same li right now)? And while I’m at it, is there a way to set the hide/disappear with CSS? So like with the input#searchbox:focus selector, change the properties of img#searchreset
Thanks!
I created something similar for a project I was working on. The main difference is that the image was visible at all times for usability reasons.
Grouping the input and button:
For the first part of your question, the approach I took was to use a parent container to hold both the textbox and the button. This will allow you to take the approach Apple took with their search. They used a css sprite (tutorial) instead of svg for the image. If you happen to be using a browser that allows you to “inspect element”, you can go to their site and see how they’re doing it.
Basically, I recommend putting the background image on the containing element so that the textbox and the button both look as if they’re “inside the image”. Then once the textbox gains focus, you can shift the background image vertically with CSS positioning and you get the look you want.
Hide/Disappear:
To hide and disappear using CSS alone is not possible. You can however create two classes, one to hide and the other to show the button. Then in javascript, once the textbox gains focus, you can set the button’s visibility to “visible” and on blur, you set it to “hidden”.
JS recommendation:
You should look into using event listeners (tutorial) instead of the HTML attributes to detect your clicks or presses. It’s a much cleaner and more elegant approach. This is where I would say that using a framework like jQuery would make things much easier. It allows you to set event listeners and not worry about legacy browsers and varied implementations of the standard.
Hope this helps.