5

I have such a code :

<div class="lighter">
  <form method="get" action="http://www.google.pl" id="search">
    <span>
      <input id="button_search" type="image" src="images/search.png" id="button_search"/>
    </span>
    <span>
      <input type="text" class="search rounded" placeholder="Search...">
    </span>
    <div class= "list_search">
      <ul>
        <li class="search_link"><a href="">Search all of Movies</a></li>
        <li class="search_link"><a href="">Advanced Search</a></li>
      </ul>
    </div>
  </form>
</div>

Is it possible simply using css to have an effect that when input type="text" is on focus list_search will appear? If yes, how?

Thanks a lot for help

srquinn
  • 10,134
  • 2
  • 48
  • 54
Gan
  • 164
  • 1
  • 4
  • 13

2 Answers2

27

This is actually possible with pure CSS, if you are able to change your markup slightly.

div {
    background: #f0a;
    display: none;
    height: 200px;
    width: 200px; }

input:focus + div { display: block; }

What I essentially do, is that first hide the div, and when the input field has focus, the immediate next sibling matching div changes it's display mode to block.

For this to work, it must be the immediate next sibling, as you cannot travel up the DOM tree, so you need to unwrap your input field. from the span.

See my fiddle: http://jsfiddle.net/TheNix/U28sd/

EDIT:
The "adjacent selector" (+) should work in IE7 and up (although I think there might be some issues with asynchronously loaded content). Note that the element must come immediately after, so it's just not "next element that matches Y" but actually "the element immediately following X, IF it matches Y".

Some times, if you know the markup and you like to hack, you can "count" your way down. input + div + div would target the second div, for example (provided the markup exactly matches). Of course, I would not recommend it, as it would blow up at the slightest change in your markup, and would be a pain to maintain.

Read more on selectors here: http://www.w3.org/TR/CSS2/selector.html#adjacent-selectors

Nix
  • 5,746
  • 4
  • 30
  • 51
1

If you are using jQuery (which I strongly suggest if you are just starting out in JS)

$(':text').focus(function(e){
    $('.list_search').toggle();
}).blur(function(e){
    $('.list_search').toggle();
});
srquinn
  • 10,134
  • 2
  • 48
  • 54