Enable a button or class to dynamically alter its color

Hi there! I'm new to coding and just started learning HTML and CSS. My question is: How can I change the color of buttons once they are clicked?

<div class="icon-bar">
  <a href="#"><i class="fa fa-search" onclick="myFunction()"></i></a> 
  <a href="#"><i class="fa fa-envelope"></i></a> 
  <a href="#"><i class="fa fa-globe"></i></a>
</div>

I've attempted to use an onclick event, but it didn't have the desired effect. This is the function I tried:

<script>
function myFunction() {
    document.getElementById("fa fa-search").style.color = "red";
}
</script>

Below is the complete code:

<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
body {margin:0}

.icon-bar {
    margin-top: 20%;
    margin-left: 0.2%;
    width: 90px;
    background-color: rgba(85, 85, 85, 0.85);;
}

.icon-bar a {
  display: block;
  text-align: center;
  padding: 16px;
  transition: all 0.3s ease;
  color: white;
  font-size: 36px;
}

.icon-bar a:hover {
  background-color: rgba(0, 140, 255, 0.5);
}

.active {
  background-color: rgba(0, 140, 255, 1);
}
</style>
<body>

<div class="icon-bar">
  <a href="#"><i class="fa fa-search" onclick="myFunction()"></i></a> 
  <a href="#"><i class="fa fa-envelope"></i></a> 
  <a href="#"><i class="fa fa-globe"></i></a>
</div>

<script>
function myFunction() {
    document.getElementById("fa fa-search").style.color = "red";
}
</script>

</body>
</html> 

Answer №1

  • Avoid using inline JavaScript handlers like on*="", just as you avoid inline style="" attributes. Keep your JavaScript in one central location, such as a script tag or file.
  • Utilize Element.addEventListener()
  • Retrieve desired elements using .querySelectorAll()
  • Loop through elements using NodeList.prototype.forEach()
  • Employ the methods of Element.classList like .add() and .remove().
  • Enhance CSS specificity by using selectors like .icon-bar a.active to override styles on hover.

const ELS_barItems = document.querySelectorAll(".icon-bar a");

function makeActive(ev) {
  ev.preventDefault(); // prevent browser action on Anchors
  ELS_barItems.forEach(el => el.classList.remove("active"));
  ev.currentTarget.classList.add("active");
}

ELS_barItems.forEach(el => el.addEventListener("click", makeActive));
body {margin:0}

.icon-bar {
    margin-top: 20%;
    margin-left: 0.2%;
    width: 90px;
    background-color: rgba(85, 85, 85, 0.85);;
}

.icon-bar a {
  display: block;
  text-align: center;
  padding: 16px;
  transition: all 0.3s ease;
  color: white;
  font-size: 36px;
}

.icon-bar a:hover {
  background-color: rgba(0, 140, 255, 0.5);
}

.icon-bar a.active {
  background-color: rgba(0, 140, 255, 1);
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<div class="icon-bar">
  <a href="#"><i class="fa fa-search"></i></a> 
  <a href="#"><i class="fa fa-envelope"></i></a> 
  <a href="#"><i class="fa fa-globe"></i></a>
</div>

Answer №2

If you want to change the background color of an element when clicking a button, simply pass the element reference to your function like this:

<button onclick="makeBackgroundRed(this)">click</button>

Here's how your JavaScript function would look:

makeBackgroundRed = function(element){
  element.style.background = 'red'
}

The issue in your code is that you are using

getElementById("fa fa-search")
but providing a class instead of an ID. You could switch to using getElementsByClassName, but keep in mind that every element with that class will be affected.

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

Finding the x and y coordinates of a rotated 3D cube using JavaScript

In my quest to create a 3D cube using separate div elements, I am faced with a challenge. Imagine a cube made up of 3*3*3 divs where each div has: X, Y, Z coordinates in the 3D space Rotation angles around the X and Y axes With this information, I shoul ...

How can I use jQuery to access the parent node in an XML document?

I have been trying to extract the top-level 'label' attribute from the XML code below using jQuery, but I haven't had any luck so far. I have already converted it into a DOM object, but the results are not what I expected. Does anyone have a ...

Guide on sending files and data simultaneously from Angular to .NET Core

I'm currently working on an Angular 9 application and I am trying to incorporate a file upload feature. The user needs to input title, description, and upload only one file in .zip format. Upon clicking Submit, I intend to send the form data along wit ...

JavaScript failing to retrieve JSON information from PHP

I seem to be encountering an issue when trying to read JSON data that I create in PHP and send back to my JavaScript. The problem is puzzling me. Here's the PHP code: header("content-type: text/json"); curl_setopt($ch,CURLOPT_URL, $url); curl_setop ...

Navigate to a different HTML file following a JavaScript function in Ionic and AngularJS with Cordova

I am currently creating an Android application in Cordova Tools for Visual Studio using Ionic and AngularJS. My goal is to redirect to another HTML page once my function has completed its execution, but I'm having trouble getting it to work correctly ...

Vertical scroll bar positioned on the left side of a DIV

Can a vertical scroll bar be placed on the left side of a DIV using CSS? What about JavaScript? ...

Adding a fresh HTML element to a list at a designated location

I found this excellent example on CODEPEN Is there a way to insert a new random number into the list so that it appears after 24 but before 19? Is there an efficient solution or do I need to manually check each li element and determine where to place the ...

Forward to a SubDomain

Utilizing Yellowtree's GEOIP-Detect plugin, I attempted to implement a location-based redirection system for visitors. Unfortunately, I encountered issues with the code execution. The process initially involves extracting the user's IP address an ...

How do you unfocus a React Native TextInput when a button is clicked?

Is there a way to remove the focus from a React Native textInput when clicking on a button? This is how my TextInput is set up: <TextInput onChangeText={onChange} value={searchQuery} placeholder="Start t ...

In Production environment, v-model triggers a ReferenceError

My Vue View includes the following code: <script setup> import Overwrite from "../components/Overwrite.vue"; </script> <template> <div> ... <textarea v-model="text" cols="99" rows=&qu ...

How can you implement a bootstrap navigation bar in a vue.js project?

I have encountered a problem with using html in my vue project. Despite following the documentation, it seems that the html is not working properly. I am unsure if this issue could be related to the import of popper.js. I have checked my code and I believe ...

Unable to find / DELETE Express.js

Within my script, I am attempting to perform POST, GET, and DELETE operations. Whenever I use POST or GET, the correct messages are logged. However, whenever I attempt to use DELETE, I encounter the following error: Cannot GET /del_user The URL I have ...

Ways to avoid submitting based on the outcome of AJAX requests

When working on an ASP.NET MVC Project, I encountered an issue where I wanted to prevent a button from submitting if the result returned from an AJAX call was false. However, no matter what I tried, the button always triggered the submission. Below is th ...

Dragging and dropping an HTML canvas element causes its width and height to be reset to zero

I am currently developing a customizable dashboard that allows users to rearrange dashboard tiles (represented by div elements) and position them anywhere within the dashboard. HTML Structure The HTML structure is outlined in the snippet below: <div cl ...

Changing the height of one Div based on another Div's height

I currently have a display of four divs positioned side by side. I am seeking a solution to ensure that the height of each div remains consistent, and should adjust accordingly if one of them increases in size due to added text content. For reference, ple ...

I'm working with Angular 12, Bootstrap 5, and ngPrime, and I'm looking to overlap a p-dialog with another element in my project

Is there a way in Angular 12 with Bootstrap 5 using ngPrime to overlap a p-dialog over any other element without using z-index and CSS, solely relying on PrimeNG? I have tried using z-index with: .my-class{ z-index: 2147483647 !important; } However, ...

Error: The script is not found in the package.json configuration

I encountered the following error while trying to execute npm run dev: Error: Missing script: "dev" Error: Error: To view a list of available scripts, use the command: Error: npm run Here is a list of scripts present in my package.json file: "scripts ...

What is the significance of the term "Object object"?

I am new to javascript and encountering an issue. When I use alert in my script, the output data is shown as [Object object]. The function below is called when the button (onClick) is clicked. There are [Object object] elements in the array. The last line ...

A Step-by-Step Guide on Sending Response to ajaxError Callback in Perl

When working with JavaScript, I have a method of capturing errors that looks like this: $(document).ajaxError(function(event, jqxhr, settings, thrownError) { handleError(MSG_SAVE_ERROR); }); Now, my question is how can I retrieve an error message fro ...

Adjust the stacking order of bars in a vertical chart and exclude negative values with Vega-Lite

I am utilizing this chart as a guide for my current project Explore Vega Editor here Is there a way to rearrange the order of the 'Measure' while keeping 'Measure 1' at the top, disregarding its negative value? I want to display the & ...