Ensure that a div remains active even after it has been selected through AJAX using jQuery

I am currently utilizing ajax to display information from a database. The application I am working on is a chat app, where clicking on a specific conversation will append the data to a view.

The structure of my conversation div is as follows:

<div class="kt-widget__item">
  <span class="kt-media kt-media--circle">
      <img src="{{ asset('media/users/100_4.jpg') }}" alt="image">
  </span>
  <div class="kt-widget__info">
    <div class="kt-widget__section">
      <a href="#" class="kt-widget__username">Teresa Fox</a>
    </div>
    <span class="kt-widget__desc">
      PR Executive
    </span>
  </div>
  <div class="kt-widget__action">
    <span class="kt-widget__date">4 Days</span>
  </div>
</div>

Additionally, here is a demo CSS for this particular div:

   .kt-widget__item {
        cursor: pointer;
        background: darkgrey;
        border-radius: 8px;
        font-size: 15px;
        color: black;
        height: 100px;
        width: 100%;a
        display: flex;
        align-items: center;
}
    .kt-widget__item:hover {
        cursor: pointer;
        border-radius: 10px;
        border: 1px solid darkgrey;
        background:  rgb(187, 184, 184);
        font-size: 15px;
        color: black;
        height: 100px;
        width: 100%;
        margin: auto;
}
    .kt-widget__item:active {
        border-radius: 10px;
        border: 1px solid rgb(156, 155, 155);
        background: rgb(156, 155, 155);
        
}

My current goal is to highlight and make the selected div active when clicked. What would be the best approach to achieve this?

Best Regards Saad

Answer №1

Key Note: Javascript cannot change the :active pseudo-class of an element. The active state is triggered by user interaction, such as a mouse click.

To give the impression that a div is active, you can assign it a tabindex attribute to make it focusable.

For more information: tabindex

Next, create a CSS rule for div:focus that matches the appearance of div:active.

Toggle the "active" look using HTMLElement.focus() and remove it with HTMLElement.blur().

Example:

const fdiv = document.getElementById('focusable');
const btn = document.getElementById("addfocus");
btn.onclick = function() {
  fdiv.focus();
};
const btn2 = document.getElementById("removefocus");
btn2.onclick = function() {
  fdiv.blur();
};
div {
  border: 1px solid black;
  background-color: #ccc;
  width: 50%;
  height: 30px;
  margin: 12px 0;
}

div:active,
div:focus {
  background-color: dodgerblue;
  outline: none;
}
<div id="not-focusable">I'm clickable but not focusable, click me</div>
<div id="focusable" tabindex="0">I'm focusable, click me</div>
<button id="addfocus">Focus the div</button>
<button id="removefocus">Blur the div</button><br/>

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

React SlideMenu will not close when a link is clicked

I am facing an issue with my off-canvas menu, which slides in when the variable isOpen is set to true. However, the problem arises when trying to slide it back out upon clicking a Link to navigate to another page. Instead of sliding out, the mobile menu oc ...

Get the value of a CSS property in Python by parsing the rendered HTML

Currently, I am using Selenium and PhantomJS in conjunction with Python for the purpose of crawling rendered web pages. While it is a straightforward process to identify the presence of specific words within the HTML content (e.g. if "example" in html...), ...

How come the CSS for my angular ngx-mat-datetime-picker and mat-datepicker collide when they are both present on the same page?

Within the same form, I have two input fields stacked under each other. One is an ngx-mat-datetime-picker and the other is a mat-datepicker. Individually, they function correctly. However, when I open them for the second time, the one I opened first appear ...

Unable to host Express and React application on port 80

I have a React application compiled with Express serving as a static React site, and I want to host them on port 80. The challenge is that my VPS runs Ubuntu with Plesk Onyx supporting multiple applications as subdomains on vhosts using port 80: server.l ...

What is the functionality of this.$eval in Vue.js?

During the process of updating an unfamiliar old script from version 0.11 to 2.5.4, an alert popped up stating: To address the warning message saying 'Replace this.$eval('reportData | reportFilter false') with a solution using normal Java ...

Set a restriction on the Bootstrap DatePicker to only show dates within a

My application features StartDate and EndDate datepickers, and I need to implement a 30-day limit on the selection range to prevent performance issues caused by loading too much data. I'm looking for a functionality where if the user picks today as t ...

Establishing a connection between the socket and the currently authenticated user through socket.io

My website consists of multiple pages, and when a user logs in, I need to establish a connection between their user ID (stored in MongoDB) and the socket for real-time messaging. Currently, user details are saved in the express session variables upon login ...

Attempting to modify the audio tag's src attribute with JavaScript

I've been doing online research for the past few weeks and have come across similar solutions to what I'm trying to achieve. However, due to my limited knowledge of javascript, I am struggling to implement them effectively. My goal is to have an ...

Having a problem with file uploads in node.js using multer. The variables req.file and req.files are always coming

I am encountering an issue with uploading a file to my server, as both req.file and req.files are consistently undefined on my POST REST endpoint. The file I'm attempting to upload is a ".dat" file, and my expectation is to receive a JSON response. ...

Creating input fields similar to the Mail app on OSX

Is there a way to create input fields similar to those in the Mail App on OSX? Take a look at this screenshot - I'm looking to group text as shown in the image above. Instead of having multiple individual input fields (e.g. like in the mail app for ...

Utilize ng-bootstrap in an Angular CLI project by integrating it with npm commands

I've been attempting to set up a project using Angular CLI with ng-bootstrap, but I'm having trouble getting the style to work properly. Here are the exact steps I followed (as outlined in the get-started page): Create a new project using `ng n ...

Guide on implementing hover effects in React components

Within my component SecondTest, I have defined an object called useStyle which sets the background color to red. Is it feasible to add a hover effect to this object? const useStyle = { backgroundColor: "red", }; function SecondTest() { return < ...

Having trouble sending data from AJAX to PHP

My goal is to implement a "load more" feature in my web app that automatically calls a PHP file to load additional products as soon as the page is fully loaded. In order to achieve this, I am using AJAX to call the PHP file: $(document).ready(function() { ...

Calendar complete: ActiveRecord::RecordNotFound (Event with 'id' = update not found)

I'm currently facing an issue with integrating FullCalendar into my rails application. Specifically, I am encountering difficulties with saving after performing drag-and-drop actions. Within my application, I have two models - Event and Workout. The ...

Adding several entries into mysql with the assistance of php

I've been attempting to input multiple records into my database table, but every time I try, all I see are zeros(0) inserted into the fields. Here's what I attempted: I used a foreach loop for insertion, but unfortunately it doesn't seem to ...

Struggling to achieve proper alignment for a series of div tags

I have implemented a code block to read in an image pixel by pixel and display it as a series of div tags arranged in a table-like fashion. The code is mostly inspired by a comment on PHP.net (http://www.php.net/manual/en/function.imagecolorat.php). This i ...

Issue encountered: Trying to deploy firebase functions and hosting with vue-cli v3 and node.js leads to an error "No npm package found in functions source directory

My plan is to utilize Vue.js for the Frontend and Firebase Functions (Express.js) + Firestore for the Backend. Step 0: I initiated a new project on Google Firebase, then created a new Service Account with Owner's permissions to be used with Admin SDK ...

The illumination in three.js failed to display properly when viewed on Chrome through an Apache server

this illustration shows the issue at hand const directionalLight = new THREE.DirectionalLight(0xffffff, 0.65, 0); directionalLight.position.set(100, -50, 200); scene.add(directionalLight); const ambientLight = new THREE.AmbientLight(0xfff5f3); ...

Is it possible to center content with Bootstrap?

Is there a different method to center content with empty space on either side? For instance: <div class="col-md-3"></div> <div class="col-md-6"> <div class="form-group"> .... </div> </div> <div class="col ...

Running into difficulties while attempting to sort through an object utilizing an array

My task is to filter a collection of objects based on an array of Fids. I have an object, $target = $('#tableA tr[data-id="' + elm.id + '"]'); // Collection of tr And I also have an array, var fids = $("#tableB tr .New.selected").pa ...