Adjusting the appearance of a heading through CSS upon being clicked

My goal is to create a feature that highlights the border of a selected box in a different color. I attempted to achieve this by using classes in the TypeScript file and utilizing document.getElementById within the selectFlight method, which is called in the flight-viewer.html file with (click). Here's an example:

flight.viewer.component.ts:

@Component({
    selector: 'flight-viewer',
    templateUrl: 'app/flight-viewer.html',
    styleUrls: ['app/flight-viewer.css']
})
export class FlightViewerComponent  {
    name = 'FlightViewerComponent';
    errorMessage = "";
    stateValid = true;
    flights: Flight[];
    selectedFlight: Flight;
    flightToUpdate: Flight;
    flightClicked = false;
    @Output()
    onFlightUpdating = new EventEmitter<Flight>();

    constructor(private service: FlightService) {
        this.selectedFlight = null;
        this.flightToUpdate = null;
        this.fetchFlights();
    }

    flightSelected(selected: Flight) {
        console.log("Setting selected flight to: ", selected.number);
        this.selectedFlight = selected;
    }
    flightUpdating(selected: Flight) {
        console.log("Setting updateable flight to: ", selected.number);
        this.flightToUpdate = selected;
    }

    updateFlight() {
        console.log("Just selected ", this.selectedFlight.number, " for update");
        this.onFlightUpdating.emit(this.selectedFlight);
    }

    selectFlight(selected: Flight) {
    console.log("Just click on this flight ", selected.number, " for display");
   this.flightClicked = true;
   this.selectedFlight = selected;
    // add 'active' class
    alert(document.getElementById("getFlight"));
    document.getElementById("getFlight").className = "active";
}

    private fetchFlights() {
        this.selectedFlight = null;
        this.flightToUpdate = null;
        this.service
            .fetchFlights()
            .subscribe(flights => this.flights = flights,
                       () => this.raiseError("No flights found!"));
    }
}

Flight-viewer.html

<h3>Flights <=/h3>
<div >
    <ul class= "grid grid-pad">
        <a *ngFor="let flight of flights" class="col-1-4">
        <li class ="module flight" (click)="selectFlight(flight)" id="getFlight">
                <h4 tabindex ="0">{{flight.number}}</h4>
            </li>
        </a>
    </ul>
</div>


<div class="box" *ngIf="flightClicked">
          You have selected flight: {{selectedFlight.number}}<br>
          From: {{selectedFlight.origin}}<br>
          Leaving at: {{selectedFlight.departure || date }}<br>
          Going to: {{selectedFlight.destination}}<br>
          Arriving at: {{selectedFlight.arrival || date}}<br><br>
    <h3><span (click)="updateFlight(flight)">Update</span></h3>

</div>

flight-viewer.css:

   h3 {
    text-align: center;
    margin-bottom: 0;
}

h4:focus {
    position: relative;
    max-height: 120px;
    min-width: 170px;
    background-color:limegreen;
}

ul {
    width: 1600px;
    overflow-x: scroll;
    background: #ccc;
    white-space: nowrap;
    vertical-align: middle;

}

li {
    display: inline-block;
    /* if you need ie7 support */
    *display: inline;
    zoom: 1
}

.module {
    padding: 20px;
    text-align: center;
    color: #eee;
    max-height: 120px;
    min-width: 120px;
    background-color: #607D8B;
    border-radius: 2px;
}

.active {
    padding: 20px;
    text-align: center;
    color: #eee;
    max-height: 120px;
    min-width: 120px;
    background-color: #607D8B;
    border-radius: 2px;
    border: 5px solid #73AD21

}

.normal {
    padding: 20px;
    text-align: center;
    color: #eee;
    max-height: 120px;
    min-width: 120px;
    background-color: #607D8B;
    border-radius: 2px;
}
.module:hover {
    background-color: #EEE;
    cursor: pointer;
    color: #607d8b;
}

.box {
    text-align: center;
    margin-bottom: 0;
    margin: auto;
    width: 600px;
    position:absolute;
    top: 180px;
    right: 0;
    height: 100px;
    border: 5px solid #73AD21;
    text-align: center;
    display: inline-block;
}

I am still facing issues as when the alert box is closed, the green outline disappears. Any suggestions on how to keep the green outline until another box is clicked would be greatly appreciated. Thank you.

Answer №1

You have written :

document.getElementById("module").className = "active";

No element with id = "module" was found in the provided HTML.

//Replace this :

<li class ="module flight" (click)="selectFlight(flight)">
                <h4 tabindex ="0">{{flight.number}}</h4>
            </li>

With

<li class ="module flight" (click)="selectFlight(flight)" id="getFlight">
                <h4 tabindex ="0">{{flight.number}}</h4>    </li>

Then try :

 document.getElementById("getFlight").className = "active";

Answer №2

The approach of attempting to "add" a new class essentially overrides all existing classes within the .module element with just the class active

Perhaps what you are aiming for is more along the lines of

// Adding the 'active' class
document.getElementById("module").className = document.getElementById("module").className + " active";

// Removing the 'active' class
document.getElementById("module").className = document.getElementById("module").className.replace('active','');

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

Learn how to implement form validation on a sliding form in just 5 easy steps using jQuery

I am new to programming and I struggle to comprehend complex JavaScript code written by others. Instead of using intricate code that I don't understand, I would like to request help in creating a simplified jQuery script for me to implement. Current ...

AngularJS is failing to update the shared service model

Utilizing AngularJS, my application contains two controllers that share a common service. When triggering an event controlled by the portalController function (specifically the setLang() function), I notice that the model of the applicationController does ...

Dialog box for confirmation/Alert box for SweetAlert before sending Ajax POST request

One issue I am encountering is with an Ajax POST function that submits a form. In the beforeSend() function, there is a sweetAlert dialog that prompts the user to either abort or continue the Ajax POST call. The problem arises when the success function tri ...

How can I properly specify the type of a function for a complex object with index signatures in TypeScript?

Problem with Retrieving Specific Data from Mixed Object I'm encountering an issue with a function that is supposed to retrieve a specific piece of data within an object. The object contains a combination of known indexes and index signatures, which s ...

Bulma - The Inline Imperative of Button Class

I recently started using Bulma and have been experimenting with creating a basic webpage using it. I've encountered an annoying issue where the "button is-large" class seems to be making elements on my page display inline. Below is a simple demonstr ...

Is it recommended to include the generated .js files in git when working with TypeScript code?

What is the best practice for handling generated .js files when writing a node.js application with TypeScript? Is it preferable to exclude generated .js files from version control by adding them to .gitignore and only committing the .ts files, or is it ac ...

manipulating child element's innerHTML with javascript

Is there a way to change my icon from expand_more to expand_less in the code below? <li class="dropdown-bt" onclick="dropdown('content');"> <a>dropdown-content <i class="material-icons">expand_more</i></a> </ ...

How can we guide the user to a different page when a particular result is retrieved by AJAX?

Whenever my PHP function makes a database call, I receive multiple results. The ajax then displays these results in a div element. My question is: How can I redirect the user to the next page once I obtain a specific result from the PHP function? Current ...

Exploring the method to reveal the password hidden field in MVC by utilizing the Html helper

@Html.Password("password", null, new { @class = "form-control frmField", placeholder = "Password" }) I want to incorporate a button that when clicked will make the password visible. I know this can be achieved using jQuery or Javascript, but I am unsure h ...

Centering Slides Vertically in Slick Carousel with Bootstrap 4 Beta

I have spent approximately 2 hours searching and attempting over 15 solutions, but none of them have been successful. The issue involves a slick-slider structured as follows: <section id="testimonial-section" class="pt-4 pb-0 px-4 bg-dark text-white"&g ...

State not properly updating in the most recent version of Next.js

"use client"; import { useState , useEffect } from "react"; import React from 'react' function form() { const [name, setName] = useState(""); const [email, setEmail] = useState(""); const [disable, ...

An issue with Destination-Out Composition in HTML5 Canvas

While working on a canvas, I have encountered an issue with deleting a portion of a curve I have drawn. Specifically, I need to remove the last 25% of the curve after it is complete and keep only the first 75%. However, when attempting to delete the lines ...

Troubleshooting the mysterious provider problem in Ui-router

I encountered this error message: "Module 'ui-router' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument." https://i.sstatic.net/o ...

Why hasn't the string been properly encoded?

Consider the scenario below: string text = "this is an example of formatted \"string\""; When I display this as a plain string in my web API method: return Ok(text) it will output: this is an example of formatted "s ...

A method for determining the quantity of <li> elements within a <ul> container while applying specific conditions

I am currently using document.querySelectorAll('ul > li').length to count the total number of items in my list. However, I am wondering if there is a way to count only those items that meet a specific condition. For example: <ul> < ...

Interactive calendar control for selecting dates in JavaScript

I have implemented two date inputs in my PHP form: Arrival Date Departure Date Currently, when the Date Icon is selected, it displays the CURRENT DATE AND MONTH. What I am looking for is that when the user selects the Arrival Date first and then the De ...

Analyzing a HTML variable against a CSV element using jQuery

In my project, I am working on comparing a user's checked out item with a csv file. The checkout item is retrieved from the div class item-options, and I need to check if the name matches any data in the csv file. Currently, the script is failing to d ...

Is it possible to adjust an attribute within a button based on specific conditions by using a flag in the controller with AngularJS?

<button type="button" class="btn btn-outlined" ng-click="vm.change()" data-modal-target="#add-save-all-alert-modal"></button> In my HTML, there is an attribute named "data-modal-target" that triggers a modal when ng-click is activated. I want ...

Using Typescript to intersect and define default props in React components

https://i.sstatic.net/Rw3e9.png Is it viable to utilize intersection in order to avoid explicitly listing every type of defaultProps, but rather derive it from a declared variable? My code example shows that even though myProp is declared as nullable, it ...

delivering targeted ads from Double Click For Publishers to a dynamic tag page URL

Is there a way to dynamically pull the tag or defined parameter from the current URL for display ads targeted through DFP? I have come across examples of how to specify which page certain ads should appear on ('tag', 'accountants'), but ...