Make the button come to life when clicked and change color

https://i.sstatic.net/61NAY.png

I designed this button using Photoshop. While I have experience in graphic UI design, my knowledge of coding is limited to Python and HTML/CSS.

My plan was to use JavaScript to animate the button when clicked and change its color. However, being a beginner, I'm unsure of what steps to take next. Should I create the button entirely with code instead of Photoshop?

Alternatively, should I create separate images for different colors and switch between them? I'm concerned that this method may result in a choppy transition when the button is clicked. This project involves designing a dashboard GUI web app, and I initially tried creating a simple color-changing button using only code, but now I feel stuck. It's surprising to me that there isn't much information available on combining Photoshopped designs with code for UI creation and animation.

Javascript


var button = document.querySelector('.button');

button.onclick = function () {
    if (backgroundColor == green) {
       document.getElementById(id).style.backgroundColor = red";
}

CSS

.button {
  &:hover {
    background-color: green;
    cursor: pointer;
    cursor: hand;
  }
  width: 100px;
  height: 50px;
  background-color: green;
  color: white;
  text-align:center;
  line-height:50px;
  border-radius: 30px;
}

Answer №1

If I were to tackle this task, my approach would be to start with HTML & CSS as they offer the advantage of easy maintenance in the future (for instance, adjusting color or size can be done by simply tweaking a CSS value).

Based on your explanation, it seems like you are essentially creating a customized checkbox. It is advisable to use semantic elements instead of <div> and <span> whenever possible to enhance accessibility for screen readers and keyboard-only users. Therefore, consider building a hidden checkbox in HTML and then styling the visible element based on its state.

/* CSS code to style the button */
.your-button input {
  opacity: 0;
}

/* Disable user selection */
.your-button,
.your-button * {
    -webkit-user-select: none;
       -moz-user-select: none;
        -ms-user-select: none;
            user-select: none;
}

/* Styling for the default button appearance */
your-button-elem {
  display: inline-block;
  width: 100px;
  height: 100px;
  background: linear-gradient(hsl(0, 0%, 100%), hsl(0, 0%, 80%));
  border-radius: 50%;
  position: relative;
  cursor: pointer;
  box-shadow: 0 6px 6px hsla(0, 0%, 0%, 0.3);
  transition: 60ms;
}

/* Colored ring around the button */
your-button-elem::before {
  content: '';
  position: absolute;
  top: -16px;
  right: -16px;
  bottom: -16px;
  left: -16px;
  background: hsl(162, 0%, 69%);
  border-radius: 50%;
  box-shadow: inset 0 0 4px hsla(0, 0%, 0%, 0.3);
  z-index: -1;
}

...

<label class="your-button">
    <input type="checkbox">
    <your-button-elem></your-button-elem>
</label>

Answer №2

If you're looking to create a stylish button using CSS, here's an idea that allows for easy customization of color, size, smooth effects, and animations:

.button {
  display: inline-block;
  margin: 20px;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background: radial-gradient(circle at top, #f2f2f2, #ccc, #b3b3b3);
  position: relative;
  border: 12px solid #96c9b9;
  cursor: pointer;
  transition: 0.5s;
}

.button:before {
  content: "";
  position: absolute;
  top: 22%;
  bottom: 22%;
  right: 22%;
  left: 22%;
  border-radius: 50%;
  border: 1px solid #cecece;
  background: radial-gradient(circle at bottom, #f2f2f2, #ccc, #aaa);
}

.button:after {
  content: "";
  position: absolute;
  top: -1px;
  bottom: -1px;
  right: -1px;
  left: -1px;
  border-radius: 50%;
  border: 1px solid #b4b4b4;
  box-shadow: 0px 6px 9px #757373;
}

.button:hover {
  border-color: #9fdecb;
}
<div class="button"></div>

Answer №3

function toggleButton() {
var glow = document.getElementById("gldiv");
var dimp = document.getElementById("dimple");
var d = document.getElementById("dlght")
if (dimp.style.display == "block") {
glow.style.background = "#c9969d";
dimp.style.display = "none";
d.style.display = "none";
}
else {
glow.style.background = "#96c9b9";
dimp.style.display = "block";
d.style.display = "block";
}
}
body {
overflow-x: hidden;
background: #e7dede;
}

.mainbg {
background: #e7dede;
padding: 20px;
}

.gdiv {
width: 100%;
height: 100%;
border-radius: 50px;
background-color: #fff0;
padding: 10px;
transition: .5s all ease;
}

.glowdiv {
margin: 100px auto;
width: 100px;
height: 100px;
background: #c9969d;
box-shadow: inset 0px 0px 3px #00000055;
border-radius: 50px;
transition: .5s all ease;
}

.gdiv:hover {
background-color: #fff3;
}

.btninshadow {
box-shadow: inset -1px -1px 3px #6d81a5;
width: 100%;
height: 100%;
border-radius: 50px;
padding: 15px;
}

.btndiv {
height: 100%;
width: 100%;
background: linear-gradient(115deg, #f3f3f7, #b1bace);
border-radius: 50px;
box-shadow: -1px 3px 10px #00000099;
}

.btndimple {
height: 100%;
width: 100%;
background: linear-gradient(115deg, #f3f3f7, #b1bace);
border-radius: 50px;
box-shadow: inset 2px 2px 3px #6d81a5cc;
display: none;
transition: .5s all ease;
}

.btndimlgt {
width: 100%;
height: 100%;
box-shadow: 0px 0px 3px #fff;
border-radius: 50px;
display: none;
transition: .5s all ease;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="mainbg">
<div class="glowdiv" id="gldiv">
<div class="gdiv">
<div class="btndiv" onclick="toggleButton();">
<div class="btninshadow">
<div class="btndimlgt" id="dlght">
<div class="btndimple" id="dimple"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>

Answer №4

Why rely on JavaScript when you can achieve the same effect with CSS:

.button {
  padding: 15px 25px;
  font-size: 24px;
  text-align: center;
  cursor: pointer;
  outline: none;
  color: #fff;
  background-color: #4CAF50;
  border: none;
  border-radius: 15px;
  box-shadow: 0 9px #999;
}

.button:hover {background-color: #3e8e41}

.button:active {
  background-color: #3e8e41;
  box-shadow: 0 5px #666;
  transform: translateY(4px);
}

Answer №5

When it comes to a standard button, your code is almost there, just a few syntax errors need fixing.

If you want to change the color of an image button, you can achieve that using CSS filters. However, keep in mind that css:filter is only supported by modern browsers.

Update:

@Temani Afif has already created a flawless CSS button, so I decided to try using SVG for the same purpose. It may not be the best solution, but I wanted to share my attempt.

PS: I'm no expert when it comes to aesthetics, so please excuse the ugly-looking SVG!

Here's a sample code snippet:

// for normal button
var button = document.querySelector('.button');
button.style['background-color'] = "green"; // or button.style.backgroundColor
button.onclick = function () {
  console.log(this.style['background-color']);  // or this.style.backgroundColor
  if (this.style['background-color'] == 'green') {
    this.style.backgroundColor = 'red';
  }
  else {
    this.style.backgroundColor = 'green';
  }
}

//for image button
const imageStyles = ['saturate', 'grayscale', 'invert'];
var imageIndex = 0;
document.querySelector('.imgbutton').onclick = function() {
  console.log(this.className);
  this.className =imageStyles[imageIndex++%imageStyles.length];
}
.button {
  width: 100px;
  height: 50px;
  background-color: green;
  color: white;
  text-align:center;
  line-height:50px;
  border-radius: 30px;
}

.button:hover {
  cursor: pointer;
  cursor: hand;
}

.saturate { 
  filter: saturate(4); 
}
.grayscale {
  filter: grayscale(90%); 
}

.invert { 
  filter: invert(90%); 
}

input[type="checkbox"]:checked ~ svg circle:nth-child(1) {
  fill: black;
}
input[type="checkbox"]:checked ~ svg circle:nth-child(2) {
  fill: yellow;
}
<table>
<tr>
<td>

<a class="button">Click me</a>
<img style="width:100px;" src="https://i.sstatic.net/61NAY.png" class="imgbutton" alt="Click Me" title="click me!"/>

<label>
 <input type="checkbox" style="display:none"/>
 <svg width="100" height="100">
   <circle id="circle1" cx="50" cy="50" r="40" stroke="#8dbab1" stroke-width="9" fill="#eaf2f0"></circle>
   <circle id="circle2" cx="50" cy="50" r="20" stroke="#edf9f5" stroke-width="2" fill="#d1d6d4"></circle>
 </svg> 
</label>
</td>
</tr>
</table>

Answer №6

If you're looking to switch between two colors in the DOM, you can achieve it by following this code:

button.addEventListener("click", function() {
   const currentColor = document.getElementById(id).style.backgroundColor;
   if (currentColor === "green") {
       document.getElementById(id).style.backgroundColor = "red";
   } else {
       document.getElementById(id).style.backgroundColor = "green";
   }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Uniform heights but varied widths design for a versatile image gallery

I am currently working on a CodeIgniter website and I am trying to achieve a layout where all the images in a row have equal heights but different widths. You can see an example of what I'm aiming for https://i.sstatic.net/qyNJx.jpg All my images are ...

The behavior of Daterangepicker varies when using callback functions versus applying the daterangepicker

Encountered an issue with the daterangepicker recently. There is a form that needs to be submitted whenever a user selects a new date range. The problem arises when using the daterangepicker callback - even though the correct values for the newly selected ...

Storing items in localStorage

I have a unique need for saving passwords in localStorage, so please don't try to figure out the reason behind it. I simply want to know if it can be done. Here's the scenario: I have a registration form. If the localStorage is empty, I save an ...

Animate the video progress bar pause using .animate() in JavaScript

Exploring video control customization is my current project for learning. In the code below, I have implemented a feature that animates a progress bar upon clicking #play: http://jsfiddle.net/tmyie/TJB7r/ var video = $('video'); var duration; ...

Create a modal using the base of a[href^=“#id”]

What is the best way to minimize a call modal window? $('#button-1').on('click', function() { $('#modal-1').addClass('j-modal--open'); }); $('#button-2').on('click', function() { $(' ...

Encountering an issue with sending a direct message on Twitter through OAuth

I am currently developing a JavaScript script to work alongside my C++ application for sending direct messages to users. The script is responsible for constructing the request that I send out. However, whenever I make a request, I keep getting errors like ...

Activate animation when hovering over an image within a container

I am attempting to create an animation that runs on one image inside a div when I hover over another image within the same div. However, it is not working as expected. The animation only takes effect when I use #div:hover, but not when I use #image:hover. ...

Managing additional attributes and recording data - when forwarding to an external URL from a Django application

I integrated an HTML-based button for sharing on WhatsApp into my mobile web app created with Django: <a rel="nofollow" target="_blank" href="whatsapp://send?text=https://example.com" data-link="whatsapp://send?text=https://example.com" data-action="sh ...

Optimizing the selection and deselection of checkboxes using JQuery with X checkboxes in mind

If I have a set of 'X' checkboxes (any input elements) in a form and "M" option selection indexes ("M" less than or equal to "X"), how can I efficiently select the "M" option indexes/values and deselect the remaining checkboxes? For example, if ...

Excel-like JSON Data Grid using jQuery

I am in need of a data grid similar to an Excel sheet. My primary focus is on filtering capabilities only (refer to the image below). Can anyone offer assistance with this? ...

In Visual Studio Code, beautification feature splits HTML attributes onto separate lines, improving readability and code organization. Unfortunately, the print width setting does not apply

I have done extensive research and tried numerous solutions, When using Angular and formatting HTML with Prettier, it appears quite messy as it wraps each attribute to a new line, for example: <button pButton class="btn" ...

What could be causing the black spaces to appear after my text in HTML?

I recently tried to implement text on an image following a tutorial I found at https://css-tricks.com/text-blocks-over-image/. Here is the code snippet I used: .image{ position: relative; } h2{ position:absolute; top: 200px; left: 200px; wi ...

Endless invocation of AngularJS $http requests

Could someone kindly clarify why the $http request is continuously sending an infinite number of requests to the server in my application? The code snippet provided is causing this issue: (function(){ var app = angular.module("GrahamsSocksProducts", [ ...

Synchronized cross-domain ajax DELETE call during page exit

Currently, I am faced with a challenge involving cross-domain remote resources that require locking. The necessary CORs headers have been properly set up. The issue at hand is ensuring the resource is released by the client when the browser window is clos ...

How to emphasize the anchor tag chosen within Angularjs by utilizing ng-repeat

After gathering some data, I have successfully bound it to anchor tags using ng-repeat. <table style="width: 60%"> <tr> <td style="text-align: center" ng-repeat="displayyears in displayYears"> ...

Click to insert a div, then transfer it to another element

Currently, I am working on a script that adds a div inside the <li> tag when clicking on a list item. The functionality is working as expected, but now I need to figure out how to remove the previously added div and also the class .selected when cl ...

Having trouble with e.preventDefault() not working on submit() in Javascript?

I'm facing an issue with submitting a form using JavaScript submit() LIVE ACTION : https://jsfiddle.net/98sm3f3t/ HTML : <form id="myForm" action=""> First name: <input type="text" name="fname"><br> <button id="myButton ...

Is there a straightforward method to retrieve all information from Vue.js?

Is there a way to extract all of this data? I've attempted using this._data.forEach but it doesn't seem to be effective. Thank you! data() { return { childData: '', credit: '', company: '', email: ...

saving user input from html forms into an xml document

I have inputted 15 characters in the 'item_detail' field of data.html, but I only want to save 10 characters in the 'itemdetail' element in the XML file item.xml. How can I achieve this? data.html---- <form> <p>Id:&l ...

Concluding a row in PHP Bootstrap for various grid dimensions

My grid layout for displaying a list of users now includes the classes col-xs-4 col-sm-4 col-md-3 col-lg-2. In the past, I only used col-md-2 and relied on a $counter to manage the row layout: while ($row = $business_query->fetch_assoc()){ ...