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

Conflicting Angular controller names within different modules

I'm facing an issue where two modules (A and B) with controllers of the same name are conflicting when imported into module C. Is there a recommended solution to prevent this conflict, such as using a naming convention like "module.controller" for ea ...

Transferring data between Javascript and PHP with AJAX and JQuery

I'm currently working on a basic web page that involves sending data from an HTML page to a PHP script and receiving some data back. My approach involves using AJAX, but for some reason, the PHP script doesn't seem to execute at all. Here's ...

Incorporating video responses into an HTML player using Node.js with the req.pipe(res) method

I have successfully implemented ytdl-core to play a video and it is working as expected. Below is the code snippet: app.get('/',function(req,res) { var fs = require('fs'); var ytdl = require('ytdl-core'); ...

Tips for accessing arrayList data within a loop in JavaScript and displaying it in an HTML <c: forEach> tag

I have an array list stored inside a javascript code block. I am looking to extract this array list and iterate through it using the html tag <c:forEach>. How can I achieve this? Currently, I am able to display the array list using <h:outputText&g ...

An error persists in Reactjs when attempting to bind a function that remains undefined

I recently tested this code and everything seems to be working correctly, but the compiler is throwing an error saying 'onDismiss' is undefined. Can someone please assist me with this issue? import React, { Component } from 'react'; c ...

Gallery tiled with images enclosed in <a> tags

I've been experimenting with pure CSS (Bootstrap 4) to create a tiled gallery layout. To achieve this, I've been utilizing the flexbox capabilities provided by Bootstrap through classes like d-flex and flex-wrap. While everything seems to be wor ...

Audio waves visualization - silence is golden

I am attempting to create a volume meter, using the web audio API to create a pulsation effect with a sound file loaded in an <audio> element. The indicator effect is working well with this code; I am able to track volume changes from the playing aud ...

Issue with Material UI Textfield functionality on mobile Safari browser

UPDATE: Resolved the problem by including this code in index.css input { -webkit-user-select:text;} In my application, I am using a Material UI box that contains text fields with an onChange handler. While the TextFields function correctly on most bro ...

Displaying JQuery dialogs briefly show their contents before the page finishes loading

Utilizing jquery 1.10.3, I am creating a dialog that is quite intricate. When I say 'intricate', I mean that the dialog's content includes data from a database, such as dropdown lists populated by the results of database queries, alongside s ...

Differences between Vue.js onMounted and watching refsVue.js offers

When it comes to calling a function that requires an HTMLElement as an argument, the element in question is rendered within my page template and therefore I need to ensure it is actually in the DOM before making the call. Two potential methods for waiting ...

Guide to decoding JSONP data sent from a remote server

Working on retrieving data using JSONP. After observing the returned data in Firebug, I can confirm that it is being returned correctly. However, I am facing a challenge in figuring out how to parse it. Is the data returning as a nested array? The callback ...

The premature firing of the fireContentLoadedEvent in Internet Explorer is causing issues

I've encountered a strange issue with IE8 recently. My code has been functioning properly for a while and still works perfectly in Firefox, but all of a sudden Prototype has stopped calling my event listeners for dom:loaded. I typically attach them u ...

Struggling with retrieving the $id variable from the view in both the controller and the database through Ajax

While checking my view, I noticed that the variable $id is visible. However, when I send it through Ajax, it ends up as NULL in the database. The way I'm sending the variable $id from the view using Ajax is like this: $.ajax({ url:'{ ...

Does setInterval consume a significant amount of CPU resources?

Recently, I came across an article stating that setInterval is considered to be CPU intensive. To verify this claim, I developed a script utilizing setInterval and closely monitored the CPU usage. Surprisingly, I did not observe any significant changes in ...

Which JavaScript library or template engine would be most suitable for this scenario?

I am tasked with creating an invite your Facebook friends module that will display the names and photos of your friends, allowing you to message them. It is essential that this feature seamlessly integrates into my website's design, so I need to style ...

The text color is being influenced by the transparent background behind it

I have a box with a transparent background color. Below is the CSS and HTML code that I'm using: CSS: #box { color: black; text-align: center; margin: 50px auto; background: blue; opacity: 0.1; border-radius: 11px; box-sh ...

Loading screen while all files and audio are being loaded

My JavaScript code is responsible for displaying and playing audio on my website. Unfortunately, the load time of the page is quite slow. To address this issue, I decided to follow a tutorial on installing a preloader, which can be found at . Although I ...

Executing a function on the window object in JavaScript

I have come across the following code and am seeking guidance on how to get the last line to function correctly. The API I am using currently employs _view appended as its namespacing convention, but I would prefer to switch to something like arc.view.$f ...

Bringing in LESS variables to Rails 3

In my assets folder, I have a global.less file where I have defined various site-wide variables. Currently, in order to use these variables in other less files, I have to add this line at the beginning of each file: @import 'global'; While thi ...

Troublesome update: Migrating XState's Reddit example from Vue 2 to Vue 3

Recently, I delved into the XState documentation and decided to explore the Reddit sample provided in the official guide. You can find it here: As I attempted to upgrade the sample implementation to Vue 3 following the work of Chris Hannaby, I encountered ...