Restore font-weight if a different list item is chosen

I previously inquired about setting the font-weight to bold on a text element when selected. Thanks to @Eric, this has been successfully implemented! However, I am facing an issue where clicking on one text makes it bold, and then clicking on another text also makes it bold simultaneously.

How can I ensure that only one text element is bold at a time?

You can view my code on JSFiddle: http://jsfiddle.net/6XMzf/ or see below:

CSS:

/* CSS code goes here */

HTML:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Sample HTML Page</title>
        <link rel="stylesheet" type="text/css" href="styles.css" />
    </head>
    <body>
        <div id="container">
            <p class="text-bold">Text 1</p>
            <p class="text-normal">Text 2</p>
            <p class="text-normal">Text 3</p>
        </div>
        <script>
            const texts = document.querySelectorAll('p');

            texts.forEach(text => {
                text.addEventListener('click', function() {
                    texts.forEach(t => t.classList.remove('text-bold'));
                    this.classList.add('text-bold');
                });
            });
        </script>
    </body>
</html>

Answer №1

When faced with the challenge of implementing a feature like adding and removing classes in plain Javascript without using a selector engine such as jQuery, there is a straightforward approach that can be taken:

function addClass(elem, className) {
    if (elem.className.indexOf(className) == -1) {
        elem.className += " " + className;
    }
}

function removeClass(elem, className) {
    elem.className = elem.className.replace(new RegExp("\\s*" + className), "");
}

var lastSelected = null;

function initializeNavigationClickHandler() {
    var nav = document.getElementById('navigationText');
    var navItems = nav.getElementsByTagName('li');

    for (var i = 0; i < navItems.length; i++) {
        navItems[i].addEventListener('click', function() {
            addClass(this, "selected");
            if (lastSelected) {
                removeClass(lastSelected, "selected");
            }
            lastSelected = this;
        }, false);
    }
}

initializeNavigationClickHandler();

To style the selected items, you would need to define a CSS rule like this:

.selected {font-weight: 800;}

This method offers flexibility in styling as you can easily add or modify additional CSS rules within the .selected class without having to make changes directly in your code.

You can view a demo of this implementation here: http://jsfiddle.net/jfriend00/rrxaQ/

Answer №2

If you have knowledge of jQuery, solving this problem becomes easier. Allow me to demonstrate the jQuery method for highlighting and unhighlighting elements.

$("#navigationText li").click( function() { 
  $("#navigationText li").css("fontWeight", "100");
  $(this).css("fontWeight", "400");
});

You can achieve the same result without using jQuery as well. You can either use a global variable to store the currently bolded item and then remove the font weight or you can remove the font weight from all items (a brute force approach).

        //not tested yet with global variable to hold current selection
        var nav = document.getElementById('navigationText');
        var activeItem = null;

        var navItems = nav.getElementsByTagName('li');

        for (var i = 0; i < navItems.length; i++) {
            navItems[i].addEventListener('click', function() {
                if (activeItem) {activeItem.style.fontWeight = '100'; }
                this.style.fontWeight = '400';
                activeItem = this;
            }, false);
        }

        //I'm not inclined to write a brute force solution for you at the moment!

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

Javascript code to verify whether the page is currently positioned at the top

How can I use JavaScript to determine if the page is at scroll(0,0)? I have a full-page slider that needs to pause when the page is no longer at the top. The page may not be scrolled manually, as there are internal HTML # links that could load the page d ...

Issue: The error message "undefined variable 'angular'" appears when attempting to access offline files stored on a network drive

I have successfully developed offline forms using angular js v1.6.4, angular-ui-bootstrap, and angular-ui-router without the need for server hosting. When the package is saved on local storage, it functions perfectly on both IE and Chrome browsers. Howeve ...

What is the correct way to make an image adjust to changes in a browser's size?

I'm in a bit of a quandary: How can I ensure that an image resizes properly based on viewport size? So, here's the challenge - I have an image that is 400 pixels wide and 400 pixels tall. My aim is for it to occupy only 90% of the width of the v ...

Why isn't the customer's name a part of the CFCustomerDetails class?

Currently, I am utilizing the cashfree-pg-sdk-nodejs SDK to integrate Cashfree payment gateway into my application. Upon examining their source code, I noticed that the CFCustomerDetails class does not include the customerName attribute. https://i.stack.i ...

Transform stereo sound to mono using JavaScript

Recently, I encountered an audio file in stereo with a .raw extension that needs to be converted into mono using Node. Despite my efforts, I haven't been successful in finding examples or libraries outlining the process. Any assistance on this matter ...

Creating a vertical triangle pointing to the right as the border of a div element

Currently, I'm working on a mockup that includes the following elements. I am attempting to ensure that the triangular right end of the "Delay Your Payments" div matches the mockup exactly. To achieve this, I aim to use CSS without relying on sliced ...

Strange symbols keep appearing in my output from PHP

My current task involves generating a SQL query based on some inputs. I have a predefined SQL statement, in which I perform certain replacements, that will use these inputs to generate the required SQL through an ODBC connection. For now, I have stored th ...

An error has occurred in the callback function for the watcher "function () { return this._data.$$state }": "Error: [vuex] It is forbidden to modify the vuex store state outside of a mutation"

Here is a screenshot of the error I encountered in the console This is the method that I am using The issue seems to be happening in mounted I have also included MapState in the Computed section While my code is currently functional, I am puzzled by th ...

Using Express and Node.js to implement the Google Maps API

Currently working on creating a simple web application using the Google Maps API with express/node. At the moment, I have three main files that make up my project: server.js const express = require('express'); const bodyParser = require(' ...

The backend is serving HTML content, but the frontend is not initiating any redirects

After hitting an API endpoint and examining the network call responses, I identified that the HTML response returned with a status code of 302. Despite this, I am perplexed as I do not witness the expected redirect on the user interface. The intended redir ...

Encountering issues when adding information to a React table

Every time I try to submit data, I encounter an error message. Line 53: Expected an assignment or function call and instead saw an expression no-unused-expressions I am attempting to add user-submitted data onto a table as td elements. Could someon ...

Sending out a command does not equate to establishing Redux with an outcome

I've been grappling with this issue for the past 18 hours and I'm at a loss to figure out what's causing the problem. My redux setup is working smoothly as it dispatches actions and receives state correctly for other components. However, in ...

Looking to transform this PHP function into a jQuery function that generates all the possible combinations of values in an array?

I stumbled upon this PHP code on a programming forum. Here's the original code snippet: function everyCombination($array) { $arrayCount = count($array); $maxCombinations = pow($arrayCount, $arrayCount); $returnArray = array(); $conve ...

Extract Information from a Website

Is there a way to extract data from another website using JavaScript and save it into a .TXT or possibly an XML file? If JavaScript is not the best solution, I am open to other suggestions. I am specifically interested in extracting the price and item na ...

Has CSS3 been recognized as an official standard?

Can you confirm whether CSS3 has been officially recognized as a W3C standard or is it currently in the status of "CR" (Candidate Recommendation)? ...

Click on the hyperlinks one by one that trigger ajax events

There is a feature on the popular social media platform reddit.com where you can load more comments by clicking a link. I understand that comments may be hidden for performance reasons, but I would like to automatically expand all comments without having t ...

Tips for sending and retrieving parameters using the POST technique

Currently, I am in the process of building a user authentication form for my website using Javascript. I am utilizing Vue JS on the client-side and NodeJS with ExpressJS on the server-side. For the server-side functionality, I have implemented the followi ...

The Ajax request is not passing the values of the submit button as expected

In my current setup, I am using ajax code to send name/email/message parameters to a "messageaction.cfm" template and then display those same 3 parameters on the original submission page. The code works fine in achieving this functionality: <script ...

Launching Android Calendar app using Intent from a web browser (Chrome)

Did you know that you can use HTML links to open Android apps from within Chrome? Take a look at this resource. If you're trying to open the calendar app from an Android app, the intent should be content://com.android.calendar/time. Learn more about ...

Trouble with firing the click event using document.createElement('a') in Firefox

I wrote a function that fetches arraybuffer data from my API, generates a temporary anchor element on the webpage, and then triggers a click event to download the file. Interestingly, this function performs as expected in Chrome. @action async loadVouc ...