I got transitions to work using a simple hover, but how do i make them respond to onclick?

<html>
<head>
<style>
#trans {
opacity:100;
transition: all 1st ease-in-out;
}
#trans:hover {
opacity:0;
}
</style>
</head>

<body>
<img src="myimage.jpg" id="trans" />
</body>
</html>

Dani AI

Generated

Short answer: CSS transitions fire whenever the computed value of an animatable property changes — not only on :hover. That change can come from a class swap, an inline style change, or a stylesheet rule change. As suggested, JavaScript can trigger the transition, but toggling a class with classList is cleaner and reversible.

Practical pattern (keeps style/behavior separate):

<img src="myimage.jpg" class="thumb" alt="example image">

.thumb {
  transition: transform 300ms ease, opacity 300ms ease;
  transform-origin: center;
}
.thumb.toggled {
  transform: scale(0.85) translateY(8px);
  opacity: 0;
}
document.querySelector('.thumb').addEventListener('click', function () {
  this.classList.toggle('toggled');
});

Why some properties seemed to “not work” (as noticed): transitions animate numeric values that the browser can interpolate. You cannot animate between auto and a number, or between different unit types; height/width often default to auto, so a direct transition will fail. Solutions: give explicit start/end numeric values (or use a max-height trick), or — preferably — animate transform (translate/scale) and opacity for smoother, GPU-accelerated motion. Avoid animating layout properties like left/top or large width changes if performance matters.

Further reading and reference on which properties are animatable and best practices: MDN — transition and MDN — transform.

Notes: ensure opacity uses 0..1 (not 100) and durations use s or ms (for example 300ms or 0.3s). For older browsers, vendor prefixes were required in the past; modern browsers generally accept the unprefixed properties.

Recommended Answers

All 3 Replies

You would probably have to do it with JS, something like

<html>
<head>
<script language="javascript">
  function transition(){
    document.getElementById('trans').style.opacity = 0;
  }
</script>
<style>
#trans {
opacity:100;
transition: all 1st ease-in-out;
}
</style>
</head>

<body>
<img src="myimage.jpg" id="trans" onclick="transition()" />
</body>
</html>

Didn't test it

Actually this only seems to work for properties without types, like opacity and whatnot. Things like position and size, marked in pixels or ems dont seem to work.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.