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

2
  • 1
    No, you need to use JavaScript to do this. Commented Nov 9, 2012 at 20:26
  • Thank You very much :D Could You please write the javascript code for this, I still didnt cover javascript...
    – Gan
    Commented Nov 9, 2012 at 20:31

2 Answers 2

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

2
  • This is clever. For posterity, it works in >=IE7
    – srquinn
    Commented Nov 9, 2012 at 21:09
  • Good point, @jibsales. I've added that to my answer for the benefit of our future readers. :)
    – Nix
    Commented Nov 9, 2012 at 21:25
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();
});
1
  • I dont know why this doesnt work still :(
    – Gan
    Commented Nov 9, 2012 at 20:57

Not the answer you're looking for? Browse other questions tagged or ask your own question.