Friday, February 24, 2012

Changing the CSS style of a DIV in response to mouse clicks, using the :target pseudo-class

In my HTML pages I regularly change the layout of a DIV element by changing the DIV's className in JavaScript.The following CSS classes, for instance, describe a 'Panel' DIV before and after a mouse click on a hyperlink HTML element:
.panel
{
    width: 300px;
    height: 30px;
    padding: 30px;
    color: Red;
    background: #eee;
    opacity: 1;
}

.hidden-panel
{
    opacity: 0;
}
My hyperlink click handler in JavaScript will look like:
function linkClicked() {
    var panel = document.getElementById('Panel');
    if (panel) {
        // Assign the CSS properties of the 'hidden-panel' class to the DIV.
        panel.className = 'hidden-panel';
    }
}
In my ongoing attempts to use pure HTML and CSS (instead of JavaScript) whenever possible, I remembered having read about the :target pseudo-class. Everyone knows the :hover pseudo-class that applies to hyperlinks when the mouse moves over them. The :target selector may be even more useful because it can replace the JavaScript className changes that I have described earlier. You can actually make a hyperlink refer to a DIV, that becomes that link's target when the link is clicked. Here is some example HTML:
<div class="panel" id="Panel">
    Click the link below to hide me.
</div>
<a href="#Panel">Hide the panel</a>
    <!-- The href attribute refers to the ID of the DIV element. -->
You can find the corresponding CSS at the beginning of this post. The 'hidden-panel' class must be changed to '#Panel:target':
#Panel:target
{
    opacity: 0;
    -webkit-transition: all 1s ease-in-out;
        /* Fade-out effect, CSS3 webkit browsers only. */
}
I have setup a quick jsFiddle to try the code yourself and experiment with it. As you can see, we no longer need JavaScript to change the Panel's CSS. Fortunately, the :target pseudo-class is also supported by Internet Explorer (version 9).

No comments:

Post a Comment