Add CSS styling to a particular div element when a button is clicked

I have been working on a new feature that involves highlighting a div in a specific color and changing the mouse pointer to a hand cursor. I successfully achieved this by adding a CSS class:

.changePointer:hover {
    cursor: pointer;
    background-color: rgb(231, 222, 222);
}

The functionality works as expected when hovering over the div. However, my goal is to trigger this effect only upon clicking a button. I am using Angular 7 for this project. I attempted to utilize

[ngClass]="{'someClass': highlightText}"
, updating the highlightText boolean to true upon button click, but unfortunately, it did not produce the desired outcome. Does anyone have any suggestions?

Answer №1

Utilize the class in the following manner, with active being the class name used.

<div [class.active]="condition"></div>

In your css, include :hover for the active class,

.active:hover {
  background-color: red;
  cursor: pointer;
}

View Demo

Answer №2

Make use of Renderer2 for element's css manipulation.

Sample HTML:

<div class="container">
    <div class="container__item" *ngFor="let div of [1,2,3]" (click)="onClick($event)">
    </div>
</div>

Component Logic:

  import { Component, Renderer2 } from '@angular/core';


  constructor(private rndr2: Renderer2) {}

  onClick(ev) {
    this.rndr2.addClass(ev.target, 'changePointer')
  }

Check out the DEMO: https://stackblitz.com/edit/angular-gaa6zi?file=src/app/app.component.ts

Answer №3

If you're looking to achieve this functionality in JavaScript, utilizing an event listener is the way to go.

button.addEventListener('click', (e) => {
    div.style.backgroundColor = 'rgb(231, 222, 222)';
    div.style.cursor = 'pointer';
});

Answer №4

If you want to change the cursor style, simply add the class .changePointer to the element

function toggleTargets(){
  //Use dataset attribute for selecting targets
  let targets = document.querySelectorAll('[data-type=A]')
  targets.forEach(elem=>elem.classList.toggle('changePointer'))
}
.changePointer:hover {
    cursor: pointer;
    background-color: rgb(231, 222, 222);
}

div{border:1px solid black; margin:5px;}
<button type="button" onclick="toggleTargets()">CLICK</button>

<div data-type=A>A</div>
<div data-type=B>B</div>
<div data-type=C>C</div>
<div data-type=A>D</div>
<div data-type=B>E</div>
<div data-type=C>F</div>
<div data-type=A>G</div>
<div data-type=B>H</div>
<div data-type=C>I</div>

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

Stylishly Select with Bootstrap 4

Currently, I am utilizing Angular 2 with bootstrap 4 and have implemented the following select element: <div class="form-group"> <label class="col-md-4 control-label" for="OptionExample">Choose an option:</label> <div class="c ...

The function inside the subscribe block is failing to execute because the navigate function is not functioning properly

Issue with router.navigate not being called in Angular There seems to be an issue with the subscribe function not getting inside the subscribe method. I have properly mapped the http registeruser function in the auth.service file, but when I try to subscr ...

The border-color feature in Bootstrap 5 does not function properly when applying responsive border-start/end/top/bottom styles

My Objective: For mobile: I want to have borders only at the top and bottom. For desktop: I want borders only at the start and end, in a border-dark color. My Attempts: I have added custom responsive borders to my main.scss file // responsive borders @ ...

Validating Inputs with an Array of Values in my Angular 2 Application

I have been exploring ways to retrieve data from an array of values instead of a single value when using [(ngModel)] binding in my Angular 2 application. The current setup functions perfectly with a single value, as shown below. The data is pulled from the ...

The image is not appearing on the webpage even though the online URLs are functioning correctly

I am currently facing an issue with my Django portfolio website where I cannot get my photo to display even though the path is correct. However, online images are displaying properly on the site. <html lang="en"><head><link href="https: ...

Issue with the code flow causing nested function calls to not work as expected

I'm experiencing an issue with my code: The problem arises when param.qtamodificata is set to true, causing the code to return "undefined" due to asynchronous calls. However, everything works fine if params.qtamodificata is false. I am seeking a sol ...

Choosing nested elements using CSS

Looking to target a specific element within a shared class, I'm struggling to find the right method to pinpoint the exact entry of this element. What I need to do is hide the current photo (pic2.jpg) and replace it with another image (pic3.jpg) in the ...

Duplicate routing configuration causing ngOnInit to be triggered twice

Here is my route setup: { path: 'menu/:level/:parent', component: MenuComponent, pathMatch : 'full' }, { path: 'menu', component: MenuComponent, }, I am trying to make it so that if the URL is menu/2/test, it will use ...

run a function once ngFor has completed rendering the data

I'm attempting to run a function every time my ngFor finishes loading data from the API. However, the callback only works on the initial load of the ngFor. How can I make sure that the callback is executed whenever my ngFor data changes? I found a ...

Ways to position an image in the middle of a Div

I am currently working with PHP and Smarty, attempting to display a slideshow's images in the center of a specific div, but I am encountering difficulties achieving this. Below you will find the code snippet. Can anyone help me figure out what I migh ...

Angular HTTP requests are failing to function properly, although they are successful when made through Postman

I am attempting to send an HTTP GET request using the specified URL: private materialsAPI='https://localhost:5001/api/material'; setPrice(id: any, price: any): Observable<any> { const url = `${this.materialsURL}/${id}/price/${price}`; ...

What is the best way to enhance the appearance of a list item that includes a visited hyperlink?

Currently, I am utilizing Stylebot in Chrome to modify certain styles on a webpage that I frequently browse. My goal is to conceal elements in a list that have links I have already visited. For instance, there is a <tr> with the class table-row, and ...

Trouble Viewing Fonts on Mobile Devices like iPhones

I am experiencing a frustrating issue on my website. While using Agency FB and Calibri fonts, they appear correctly on all desktop browsers. However, when accessed from my iPhone, a different standard font is displayed instead. Both the logo and text with ...

Develop an engaging billboard carousel using jQuery

After coming across a tutorial on tympanus, I decided to make some modifications to create a rotating billboard effect. However, something seems to be going wrong and it's driving me crazy trying to figure out the problem! $(function() { $('#ad_ ...

Ionic 5 Error: Unable to access 'subscribe' property of undefined object

Working with IONIC 5 service: import { HttpClient } from '@angular/common/http'; . . . getPlaces(placeId: string) { return this.httpClient.get( `https://test.com/offered-place/${placeId}.json`) } . . . Encountering an issue when tryin ...

What is the best way to gradually transform a continuously shifting text color into a single, consistent hue?

Hey there, wonderful people of StackOverflow! I am absolutely stumped and cannot figure out how to smoothly transition this color-changing text from its current state into a different solid color when the submit button is clicked. Is there a skilled indiv ...

Struggling with the functionality of Angular Material Layout Directives

Looking to implement the Child-Alignment feature in Angular Material but running into some issues. Details available here: https://material.angularjs.org/latest/layout/alignment Despite trying to import import { LayoutModule } from '@angular/cdk/l ...

Tips on maintaining and hiding the vertical scrollbar when a popup is open, alongside the navigation bar positioned at the top of the page

After reviewing this pen, my goal is to create a popup that maintains access to the navigation bar (hence avoiding Bootstrap's Modal). However, I am facing the challenge of keeping the scrollbar visible while preventing scrolling in the background whe ...

Implementation of Asp.Net core identity combined with Angular 2

Recently, I developed a web-app using Asp.Net with angular2. To kickstart the project, I utilized generator-aspnetcore-spa. Now, my next step is to integrate identity management into the application. After some consideration, I have decided to go with Asp ...

The div inside an iframe is not displaying the desired background color as intended from the parent page

The code snippet below is included in the <head> section of the main page: <script type="text/javascript"> $(document).ready(function () { $('#innerframe').load(function () { $(this).contents().find($(".TitleB ...