Most of the components we can see around the wide web requires some kind of interaction by the user. Take as an example a very common type of component that we can see in many websites, a carousel. The basic functionality of a carousel is to show a content block allowing a continuous interaction through all the content blocks. Below is an example of a carousel using YUI3.
Shut up and show me the code
To start I will introduce you to the basic concept which we will use to develop our sample code and that can be used for you in the future to develop your own widgets.
Thinking about carousels we know that the user needs to click on a kind of button which will fire an event that will make the carousel show the next content block. Then we have states that will change in response to the user”s interaction. So, we need something to handle the click event of the user and store the current state and then the interface needs to change to represent the new state. Below there”s an example of everything we need in a carousel: states that change in response to the user”s interaction and update the component on the page.
The most important part of this example is how it changes when we activate the different radio buttons. Below is the HTML structure of the example.
Each rectangle is called a page element and is 100px wide. In the code fragment below it”s clear that we use only CSS selectors to define the different states and what visually changes when each radio button is activated. I”m omitting the CSS code needed only for styling the elements, but you can see the complete example later.
With this we can evolve the example to a more elaborated version hiding the radio buttons and allowing the user only to click to move to the next page of the carousel. For that, we can style content inside of a label element that targets each radio button in our controls as you can see in the example below.
For that example we”ve created simple elements to represent our buttons. When clicked, they will check the radio button and switch to the next state.
Then we hide all the radio buttons and define the state of each next button that will appear in every possible state.
The complete example 2 is also available to you.
Now we can create the possibility to move left and wrap around. For that we just need to duplicate the control elements to have some control focused only on moving left. We also need two containers for our pages, one which moves left and another which moves right; each button moves the respective container.
Then update the CSS selectors to handle the new states.
After that, we can see our example working like below.
Creating widgets only using CSS can reduce considerably the size and loading time of your pages and is a task full of creativity. Others are creating interesting things using similar techniques. Create your own widgets to amaze the world.