CSS Click Event

So you have click the link to find out, how on earth is there a CSS Click Event that I have not heard of? Well that’s because there is no Click Event directly, but we can replicate that event with CSS. Below will show you with a simple example how to action CSS on a click.

As I have said there is not real Click Event in CSS, but you can use the other tools you have to replicate that event. In CSS you can determine the stat of elements on the screen and so with that you can check the stat of a Checkbox. This is how we are going create the Click Event.

You can use the pseudo attribute ‘:checked’ to determine is the Checkbox is checked or not. If you use the pseudo then all CSS under it will only action when it is checked.

 

input{
    background-color:red;
}
input:checked{
    background-color:green;
}

 

Now that we know we can click on an Checkbox to activate CSS, we will need to expand its reach. If you are to click on a menu item of a button, you don’t want it to be a Checkbox. We get round this with the label element. With this element you can surround your items that will change. You can link the input and the label together so when you click on the label you are also clicking on the input.

 

<label for="chk" >

<input type="checkbox" id="chk" />

<span>

<!-- content -->

</span>

</label>

 

From this you can change the style depending on the checkbox state, but with CSS you can only target the children elements. This means you can’t target the ‘span’ because its not a child on the input that is having its state changed. What we can do is target the next element. We can do this by using the ‘+’. If you put this next to the input element then add the span in CSS the it will target the span. It affects the next element to the one on the left, please see the example below:

 

#chk:checked + span {

/* Checked Style Here */

}

 

Now you can put it all together and create a click event like I have in the Codepen below:

http://codepen.io/purerandom/full/mEyqmR/

Advertisements

Leave a message please

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s