Using css :target selector as a fallback do JS
Lets say we have a hidden search field in our website and it will show up when the user clicks on a magnifier. The HTML is as it follows:
<aside id="search-box">
<div id="search-container">
<form id="searchform" action="#" method="get">
<input type="text" placeholder="Search" name="search">
</form>
</div>
<a id="toggle-search" href="#search-container">Search</a>
</aside>
Ok, the javascript ( coffeescript with jQuery actually) to make it work isn't magical and there's nothing new here:
$ ->
$searchBox = $('#search-box')
$searchContainer = $('#search-container', $searchBox)
$('#toggle-search', $searchBox).on "click", (e) ->
$searchContainer.slideToggle("fast")
$('input[type=text]', $searchContainer).focus()
false
Great! Now follows my tip
We want to provide a fallback for the users with disabled javascript, in a scenario where nobody uses old browsers (I mean, we can use CSS3 selectors with no worries) =)
#search-container
display: none
&:target
display: block
Ok, now it works very similar as with enabled javascript!
Click here if you want to see a demo (don't forget to disable your javascript).
Conclusion
The css :target selector can be used in many ways, but I have to admit I didn't see its real value till I started to use it as fallback to JS.
Cheers!
Written by Gustavo Guichard
Related protips
Have a fresh tip? Share with Coderwall community!
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside