Hide/Show DIV when input element is focused

Yesterday, I was browsing Play-Asia for a game (Resident Evil Chronicles HD by the way), the website is packed with so many text and images that they've found out a way to display the search box's extra options elegantly, as shown below:

Before

After: User clicks on search textbox

Tasks:
  • Textfield with placeholder
  • When user clicks on the textfield, an outer DIV will display with more search options and a submit button/image
  • If user clicks anywhere outside of the search dialog box or the 'X' button, the outer DIV will be hidden.
  • Avoid user from spam-clicking on the textfield that may cause unexpected behaviour of the toggle show/hide feature.
  • Able to put the textfield anywhere within a webpage and have the same effect
Eager to find out how they code such effect, I have successfully used jQuery to replicate it and improve on the element positioning.

HTML part


Javascript part


Explanation:

  • The hidden outer DIV will have absolute positioning while its parent will have relative positioning so that their positions will be adjusted accordingly.  Click here for more information about css positioning.
  • event.stopPropagation() is used to stop the click queue.  If this is omitted, clicking on the "X" button will trigger the fadeOut() effect initially, then it will proceed to trigger the parent's fadeIn() effect (in 'else' statement).

Click here to download the files (ZIP).

No comments:

Post a Comment