The onclick attribute in HTML allows you to execute JavaScript code when an element is clicked. Combined with CSS, onclick opens up a world of interactive web design while avoiding complex JavaScript code. In this guide, we‘ll explore practical onclick CSS techniques to create engaging user experiences.

Changing Element Styles on Click

One of the most straightforward uses of onclick is to toggle CSS styles. For example, we can change the color of text when a button is clicked:

<p id="text">Click to change my color!</p>

<button onclick="document.getElementById(‘text‘).style.color=‘blue‘">Blue</button>

Here we select the paragraph with id="text" using getElementById() and set its text color to blue.

This takes just a few lines of code, but we can expand on this concept to make more complex style changes:

<div id="box" style="background: red; width: 100px; height: 100px"></div>

<button onclick="document.getElementById(‘box‘).style.background=‘blue‘; 
                 document.getElementById(‘box‘).style.width=‘200px‘;
                 document.getElementById(‘box‘).style.height=‘200px‘">
  Grow Blue
</button>

Now we change multiple CSS properties like background color, width, and height all on one click.

We can also use this technique to dynamically add and remove CSS classes with predefined styles. For example:

.highlight {
  background: yellow;
  border: 2px solid black;
}
<p id="text">Click to highlight me!</p>

<button onclick="document.getElementById(‘text‘).classList.add(‘highlight‘)">
  Highlight
</button>

<button onclick="document.getElementById(‘text‘).classList.remove(‘highlight‘)">
  Unhighlight
</button>

The classList property lets us append or remove classes without affecting existing ones.

Toggling Visibility

Besides styling content, we can show and hide elements on click with CSS:

<img id="image" src="photo.jpg">

<button onclick="document.getElementById(‘image‘).style.display=‘none‘">
  Hide
</button>

<button onclick="document.getElementById(‘image‘).style.display=‘block‘">
  Show
</button>

This allows a simple show/hide function for images, text, divs, or any other content.

For more complex toggling behavior, we can create accoridons, tabs, and other collapsible components using radio buttons or checkbox inputs.

For example, clicking labels to expand "accordion" panels:

<input type="radio" name="panels" id="panel1" checked>
<label for="panel1">Section 1</label>
<div class="panel">
  <p>Content for section 1</p>  
</div>

<input type="radio" name="panels" id="panel2">
<label for="panel2">Section 2</label>
<div class="panel">
  <p>Content for section 2</p>
</div>
.panel {
  display: none;  
}

input[id="panel1"]:checked ~ .panel {
  display: block;
}

input[id="panel2"]:checked ~ .panel {
  display: block;  
}

Clicking the labels toggles the visibility of the panel divs using the general sibling (~). We can add as many sections as we need all working off those two onclick CSS rules!

Creating Overlays and Modals

One popular user interface pattern is the modal overlay. These pop up on click to display messages, notifications, login forms, contact forms, and more without navigating away.

A basic modal needs just a few lines of HTML and CSS:

<button id="open">Open Modal</button>

<div id="modal">
   <div class="content">
     Modal Content
   </div>
</div> 
#modal {
  display: none; 
  position: fixed;
  z-index: 1; 
  left: 0;
  top: 0;
  height: 100%;
  width: 100%;
  overflow: auto;
  background: rgba(0,0,0,0.5);
}

#modal .content{
  background: white;
  margin: 10% auto; 
  width: 60%;
  padding: 20px;
  border-radius: 5px;
}

We use onclick to toggle the display property and show the hidden #modal div:

<button onclick="document.getElementById(‘modal‘).style.display=‘block‘">
  Open Modal
</button>

<button onclick="document.getElementById(‘modal‘).style.display=‘none‘">
  Close Modal
</button>

Now we have a responsive modal that users can open and close! We could embed contact forms, videos, notifications or any other content.

With additional CSS we can animate the modal for slick transitions:

#modal {
  transform: scale(0);
  transition: 200ms ease-in-out;
}

#modal.active {
  transform: scale(1);
}
let modal = document.getElementById(‘modal‘);

openBtn.onclick = () => {
  modal.classList.add(‘active‘);
}

closeBtn.onclick = () => {
  modal.classList.remove(‘active‘);
}  

Now the modal animates open and closed on click. CSS handles the visuals while JavaScript toggles a simple .active class.

Creating Image Galleries

One of the most interesting applications of onclick CSS is building image galleries and sliders. We essentially stack images on top of each other, then show one at a time:

<div class="slider">
  <img src="img1.jpg">  
  <img src="img2.jpg">
  <img src="img3.jpg">
</div>

We set up click handlers to display one image while hiding the others:

let current = 1;

function showImage(n) {
  let images = document.querySelectorAll(".slider img");

  images.forEach(img => {
    img.style.display = ‘none‘; 
  });

  images[n-1].style.display = "block";  
}

img1.onclick = () => {
  showImage(1);
}

img2.onclick = () => {
  showImage(2); 
}

img3.onclick = () => {
  showImage(3);
}

Now we can click the images to change which one shows! With some additional features like next/previous buttons, transition effects, dynamic image counts etc. we transform this into a custom state-of-the-art gallery.

All running off simple onclick functions and CSS without complex frameworks.

React to Mouse Position

We can also use onclick CSS to create interesting effects based on mouse location. For example, changing color:

box.onclick = (e) => {

  let x = e.clientX - e.target.offsetLeft;
  let y = e.clientY - e.target.offsetTop;

  box.style.background = ‘rgb(‘+x+‘,‘+y+‘,100)‘;

}

This gets the mouse X/Y within the element and passes to RGB() to generate colors. Clicking higher creates lighter shades dynamically.

Or we can use mouse position to shift elements on click:

box.onclick = (e) => {

  let x = e.clientX - 50; 
  let y = e.clientY - 25;

  box.style.left = x+‘px‘;
  box.style.top = y+‘px‘;

}

Now clicking moves the box below our mouse pointer. This brings onclick interactivity to the next level!

Draggable Elements

In addition to the onclick event, we also have onmousemove and onmouseup events. Combining all three allows us to make draggable elements with simple CSS rules:

let selected = null;

box.onclick = (e) => {
  selected = box;  
}

window.onmousemove = (e) => {
  if(selected) {
    selected.style.left = (e.clientX - 25)+‘px‘;
    selected.style.top = (e.clientY - 25)+‘px‘; 
  }
}

window.onmouseup = () => {
  selected = null;
} 

Here we set the clicked element to a selected variable, then track mouse moves to drag it accordingly. onmouseup sets selected back to null.

Now users can click and drag elements freely without libraries or plugins! We add limits, snap points and collision detection to transform this into a basic drag & drop system.

Create Scrolling Effects

The onscroll event combined with CSS animations gives interesting scrolling effects as users scroll down pages.

For example, fading in content from the right:

div {
  opacity: 0;
  transform: translateX(50%);
  transition: 500ms;
}

div.visible {
  opacity: 1;
  transform: translateX(0);
}
const boxes = document.querySelectorAll(‘.box‘);

window.onscroll = () => {

  const triggerBottom = window.innerHeight;

  boxes.forEach(box => {
    const boxTop = box.getBoundingClientRect().top;

    if(boxTop < triggerBottom) {
      box.classList.add(‘visible‘);
    } else {
     box.classList.remove(‘visible‘);
    }
  })

}

This calculates each element‘s location then applies animated visible class accordingly. Items fade in nicely as users scroll down the page.

Parallax effects work similarly tied to scroll position instead of hard CSS values. More advanced techniques even link webpage animations to scroll speed for unique effects.

Responsive Designs

CSS media queries check browser width to modify styling appropriately across devices. We can integrate onclick behavior to change functionality as well.

For example, a mobile menu button:

<button onclick="showNav()">Show Nav </button>

<nav id="nav">
  <!-- navigation links here -->
</nav>

We write media queries to handle desktop vs mobile:

/* Show nav automatically on wider screens */
@media (min-width: 700px) {
  #nav { 
    display: block;
  }
}

/* Hide nav on mobiles then toggle with JS */
@media (max-width: 699px) {
  #nav {
    display: none; 
  }
}
function showNav() {
  let nav = document.getElementById(‘nav‘);

  if(nav.style.display == ‘block‘) {
    nav.style.display = ‘none‘;
  } else {
    nav.style.display = ‘block‘; 
  }
}

Now the navigation works beautifully across screen sizes thanks to media+onclick handling responsively. The same patterns adapt landing pages, rearrange page layouts, launch mobile mods and more.

Customize Form Elements

HTML form elements like select menus, checkboxes and toggles turn dull interfaces into usable tools. We enhance them further with CSS using the :checked pseudo-selector.

For example, custom styled radio buttons:

<input type="radio" id="blue">
<label for="blue">Blue</label>

<input type="radio" id="red">
<label for="red">Red</label> 
label {
  display: block; 
  padding: 10px 20px;
  background: #CCC;
  color: #333;
}

input[id="blue"]:checked + label {
  background: blue;
  color: white;
} 

input[id="red"]:checked + label {
  background: red; 
  color: white;
}

Clicking swaps colors dynamically. We hide default inputs completely, delegating behavior to custom CSS updated with :checked.

We shape toggles, range sliders, select menus and more the same way:

<input type="checkbox" id="toggle">
<label for="toggle"></label>

No matter the input, onclick handles customization!

Animate SVG Graphics

Scalable vector graphics (SVG) let us draw shapes directly in webpages for interactive illustrations.

We modify SVG elements by ID or class name through CSS or inline styles. For example, change properties on hover:

<svg viewBox="0 0 100 100">
  <circle id="circle" cx="50" cy="50" r="30" />
</svg>
#circle:hover {
  fill: blue;
} 

Dynamic onclick animations take this further:

let circle = document.getElementById(‘circle‘);

circle.onclick = () => {
  circle.setAttribute(‘fill‘, ‘blue‘);

  setTimeout( () => {
    circle.setAttribute(‘fill‘, ‘black‘);
  }, 500);
}

Here clicking the circle turns it blue then back to black after a delay. Perfect for indicating selections, toggling states and visualizing data!

With creative shape animations, we build beautiful data visualizations, animated icons and even mini games!

Create Image Hotspots

Image maps allow clicking specific parts of images to trigger actions. We highlight shapes and areas without complex code:

<img src="image.jpg" usemap="#image-map">

<map name="image-map">
  <area id="circle" shape="circle" coords="200,250,50">
</map>  
let circle = document.getElementById(‘circle‘);

circle.onclick = () => {
  alert(‘Circle clicked!‘); 
};

Areas don‘t need hardcoded shapes either. We position elements over images via CSS:

<img src="image.jpg">

<div class="circle"></div>
.circle {
  position: relative;
  top: 200px; 
  left: 200px;
  width: 100px; 
  height: 100px;
  border-radius: 50px;  
  background: rgba(0,0,0,0); 
}

This overlays a clickable circle without editing the image itself. Great for highlighting details on photos!

Create Interactive Experiences

Stepping back from individual techniques, we can put everything together to craft immersive interactive experiences. Multi-step forms, 360-degree image viewers, dashboards with real-time chart updates, and more.

For example, an interactive triangle for learning geometry:

let area, sideA, sideB, hypotenuse; 

function calculate() {
  // Calculate area, angles, etc  
}

function resize(element, amount) {
   // Grow/shrink triangle side 
}

function rotate(deg) {
  // Rotate entire shape
}

function reset() {
  // Reset to original state  
}

sideA.onmousedown = () => dragResize(‘sideA‘); 

sideB// Drag handler
hypotenuse// Drag handler

shape.ondblclick = rotate;

btnReset.onclick = reset;

btnCalculate.onclick = calculate;

We dynamically update visuals coupled to interactive clicks, taps, drags and gestures. Students engage with concepts hands-on instead of static text or images.

The same principles transform tutorials, simulations, declarative visualizations and other next-gen learning tools!

Animate Page Transitions

For full-page animations between navigations, we use the pageshow and pagehide events.

As an example, a fade transition:

main {
  opacity: 1;
  transition: opacity 500ms; 
}
window.addEventListener(‘pagehide‘, () => {
  main.style.opacity = 0; 
});

window.addEventListener(‘pageshow‘, () => {
  main.style.opacity = 1;
});  

This cross-fades pages on every navigation for a cinematic experience.

With loaders and transition effects, we build intricate movie-like animations through simple CSS manipulation. Creative page transitions guided by events over code!

Conclusion

While complex frameworks serve their purpose, onclick powered CSS unlocks simpler and more intuitive interactive interfaces. We explored concepts like:

  • Toggling element visibility
  • Launching popups and overlays
  • Building image galleries
  • Dragging / dropping elements
  • Reacting to scroll position
  • Creating SVG animations and hotspots
  • Crafting fluid responsive designs
  • Customizing form inputs
  • Building full-page transitions

Onclick handles the JavaScript, while CSS delivers the presentation. This frees us to focus on innovative interfaces, not implementation details.

Whether enhancing existing designs, or crafting new experiences from scratch – the power lies directly in your hands. Unleash creativity with onclick CSS today!

Similar Posts