Activate CSS element with a click

Is there a way to add a click event to a CSS class so that when it is clicked, it changes to a different class? I am specifically looking to change the character class on li items when they are clicked. Here is the code snippet:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>Document</title>
        <link rel="stylesheet" href="app.css" />
    </head>
  
    <body>
        <div class="container">
            <h1>Client Search</h1>
            <div id="searchWrapper">
                <input
                    type="text"
                    name="searchBar"
                    id="searchBar"
                    placeholder="search for a character"
                    onkeyup="myFunction()"
                />
            </div>
            <ul id="charactersList"></ul>
        </div>
        <script src="app.js"></script>
    </body>
</html>

CSS

body {
    font-family: sans-serif;
    background-color: #111d4a;
}

* {
    box-sizing: border-box;
}
h1 {
    color: #eee;
    margin-bottom: 30px;
}
.container {
    padding: 40px;
    margin: 0 auto;
    max-width: 1000px;
    text-align: center;
}

#charactersList {
    padding-inline-start: 0;
    display: none;
    grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
    grid-gap: 20px;
}

.character {
    list-style-type: none;
    background-color: #eaeaea;
    border-radius: 3px;
    padding: 10px 20px;
    display: grid;
    grid-template-columns: 3fr 1fr;
    grid-template-areas:
        'name image'
        'house image';
    text-align: left;
}
.character:hover {
  background-color: blue;
  cursor: pointer;
}

.character > h2 {
    grid-area: name;
    margin-bottom: 0px;
}

.character > p {
    grid-area: house;
    margin: 0;
}

#searchBar {
    width: 100%;
    height: 32px;
    border-radius: 3px;
    border: 1px solid #eaeaea;
    padding: 5px 10px;
    font-size: 12px;
}

#searchWrapper {
    position: relative;
}

#searchWrapper::after {
    content: '🔍';
    position: absolute;
    top: 7px;
    right: 15px;
}

JavaScript

const charactersList = document.getElementById('charactersList');
const searchBar = document.getElementById('searchBar');
let clientNames = [];

searchBar.addEventListener('keyup', (e) => {
    const searchString = e.target.value.toLowerCase();

    const filteredCharacters = clientNames.filter((character) => {
        return (
            character.name.toLowerCase().includes(searchString) ||
            character.house.toLowerCase().includes(searchString)
        );
    });
    displayCharacters(filteredCharacters);
});

const loadCharacters = async () => {
    try {
        const res = await fetch('https://hp-api.herokuapp.com/api/characters');
        clientNames = await res.json();
        displayCharacters(hpCharacters);
    } catch (err) {
        console.error(err);
    }
};

const displayCharacters = (characters) => {
    const htmlString = characters
        .map((character) => {
            return `
            <li class="character">
                <h2>${character.name}</h2>
                <p>House: ${character.house}</p>
            </li>
        `;
        })
        .join('');
    charactersList.innerHTML = htmlString;
};

loadCharacters();


//change the display of characterListfrom none to grid
    function myFunction() {
      var charactersList = document.getElementById("charactersList");
      charactersList.style.display = "grid";

//also check if searchBar is empty and set display back to none
      var searchBar = document.getElementById("searchBar").value;
      if (searchBar === ""){
        charactersList.style.display = "none";
      }
    }

Answer №1

That's an excellent query!

I've created a CodePen demo to demonstrate how you can dynamically modify CSS classes when a li element is clicked. Take a look at this example and let me know if it helps clarify the issue : )

JS

let list = document.getElementById('myList');
let items = ['First', 'Second', 'Third', 'Fourth', 'Fifth'];

for(let item of items){
  let li = document.createElement("LI");
  li.appendChild(document.createTextNode(item));
  li.classList.add('blue');
  li.addEventListener("click", () => {
    li.classList.remove('blue');
    li.classList.add('red');
  });
  list.appendChild(li);
}

HTML

<ul id="myList"></ul>

CSS

.blue{
  color: blue;
}

.red{
  color: red;
}

https://codepen.io/CrowlsYung/pen/eYJRPjx

Suggested Change

<li class="character" onclick="handleItemClick(event)">
    <h2>${character.name}</h2>
    <p>House: ${character.house}</p>
</li>

function handleItemClick(e){
    e.currentTarget.classList.toggle('prevClass')
    e.currentTarget.classList.toggle('newClass');
}

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

Which specific CSS attributes should be applied to create a scroll bar within this table?

Below is the table that I am working with: 'table' I want to ensure that its width remains the same even when the screen size is reduced, and only add a scroll bar to view it. I have already included overflow: scroll; in the container <div> ...

When attempting to trigger a function by clicking a button in Angular 8 using HTTP POST, nothing is happening as

I've been struggling to send a POST request to the server with form data using Observables, promises, and xmlhttprequest in the latest Angular with Ionic. It's driving me crazy because either I call the function right at the start and the POST wo ...

What are the steps to utilizing an npm package that simply encapsulates my JavaScript code?

Our current npm package is designed for clients working on ES6-based projects, such as React. The main index file of the package looks like this: export function ourFunction() { } Clients import this function using the following syntax: import { ourFunc ...

Obtaining a file using capybara independently of rails

Case Study: Attempting to access an external URL using Capybara for downloading a file. It is necessary to use Selenium or Webkit as the driver, since Rack-test does not allow visiting external URLs. This website utilizes iframes. The prompt for file dow ...

Navigating from a Card to a new View in Angular

I am currently developing a project using Angular (latest version). Within my application, I have the functionality to dynamically generate bootstrap cards from an Order Array and display them in my "Order-Item-Component through its respective template. ...

Using a JavaScript script in my HTML alongside Vue.js is not possible

Hello there! I recently created a Node.js server and now I'm trying to display an HTML file that contains a Vue script which loads data using another method written in a separate JS file. However, when I attempt to load my HTML file in the browser, ...

Methods for animating .jpg images using CSS

I'm currently working on animating an image, specifically moving it from left to right and back. However, before I dive into implementing CSS animation keyframes, I noticed that I am having trouble getting the HTML element to follow the CSS styles I a ...

I am having trouble with my jQuery login function not properly connecting to the PHP file

Hey there, I've been working on creating a login system from scratch by following an online tutorial. The initial Javascript is functioning properly as it detects errors when the inputs are empty. However, once I enter text into the input fields and c ...

Unable to eliminate border from image within label

The following code generates a border that appears to be approximately 1px thick and solid, colored grey around the image. Despite setting the border of the image to none, the border still remains. Here is the code snippet: <label> <img styl ...

What is the best way to extract all image URLs from a website using JavaScript?

There are various methods to retrieve image src urls using JavaScript, such as utilizing document.images or by targeting all img elements and fetching their src attributes. However, I am currently unable to extract the image urls specified within CSS styl ...

A guide on embedding the flag status within the image tag

I would like to determine the status of the image within the img tag using a flag called "imagestatus" in the provided code: echo '<a href="#" class="swap-menu"><img id="menu_image" src="images/collapsed.gif" hspace = "2"/>'.$B-> ...

Master the art of utilizing angular-filter

Encountering some challenges while attempting to utilize angular-filter: The following links have been imported into the HTML file: <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script> <script src=" ...

Utilizing Material UI with Appbar logo aligned to the left and Tabs featured at the center

I am currently working on creating a react material ui AppBar. The design includes a logo and tabs, with the tabs supposed to be centered in the AppBar and the logo positioned on the left side. However, I have been facing difficulty in making the logo al ...

Error Received While Attempting to Log in using Ajax

Having an issue with logging in using ajax and php. I am able to log in successfully, but when trying to display an alert message and refresh the page upon login, it gives me an error without refreshing. However, upon manually refreshing the page, I can se ...

Utilize Jquery to dynamically modify the content on a webpage

I am looking to use Tampermonkey in order to reverse the text on a specific website, like BBC News. I have already started working on a script that can replace certain text, but I am facing difficulty in accessing all the text present on the page efficient ...

Getting a ReferenceError while trying to use a MongoDB Collection variable in an external resolver file that had been imported through mergeResolvers

Here is a simplified example to illustrate the issue at hand. When using the resolver Query getAllUsers, the MongoDB Collection Users is not accessible in the external resolver file user.js. This results in the following error when executing the query: ...

The <picture> element is malfunctioning

Today, I came across the <picture> tag that allows for multiple image sources for an <img>. Following the example from w3schools, I learned how to use it: <picture> <source media="(min-width: 650px)" srcset="img_pink_flowers.jpg"> ...

Unleashing the power of RollupJs: A guide to dynamically bundling modules and objects

Is there a way to dynamically bundle a module/object into my RollupJs output file? I have experimented with various options without success in achieving the desired result. Below is a brief sample project that demonstrates what I am trying to achieve. The ...

Using media queries in CSS to create responsive designs

<link type="text/css" rel="stylesheet" media="only screen and (max-device-width: 480px)" href="/assets/css/phone.css" /> <link type="text/css" rel="stylesheet" media="only screen and (min-device-width: 768px)" href="/assets/css/tablet.css" /&g ...

Is it possible to activate a block display for an article based on the class value when a radio

Here is the HTML code snippet I'm working with: <div id="contentapp"> <input type="radio" name="menu" id="interest" checked> <input type="radio" name="menu" id="about"> <div id="tab"> <label for="intere ...