CSS click event and attr(). Say no to Javascript

Today I will show how to handle click event using CSS hack. No javascript will be harmed during this example.

we in this tutorial we will implement custom tooltips components.

basically, we’ll have an anchor tag, on mouse over or mouse click a tooltip will show.

See the Pen CSS click event and attr(). Say no to Javascript by Arkaprava majumder (@arkaindas) on CodePen.

So here is our markup:

<div class="container">
  <a href="javascript:void(0)" tooltips="CoderExample" class="mouseover"> Mouseover to see the Tooltips</a>
  <a href="javascript:void(0)" tooltips="CoderExample" class="click"> Click to see the Tooltips</a>
</div>

if you mouse-hover on the first link, we are getting a custom tooltips text from a custom attribute “tooltips” using CSS attr() property and showing in after content using CSS pseudo selector.

.mouseover:hover:after {
  content: attr(tooltips);
  position:absolute;
  left:40px;
  top:-30px;
  display:block;
}

Let’s continue with using :focus pseudo-selector instead of :hover. So here is our magic. When you click the link tooltip will be visible until you blur event. Something like focus into an input text field.

.click:focus:after {
  content: attr(tooltips);
  position:absolute;
  left:25px;
  top:-30px;
  display:block;
}

Keep in mind that :focus does not works on element like div, p etc. It only works on either a focusable element or the tabindex elements like a, input etc.

You can also handle click event with another way using :checked, :target, :active pseudo-classes in pure css.

DownloadDemo


  • Henry ng

    Awesome .