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

Continuously transmitting PNG files to a server. I intend to instruct the receiving browser to automatically refresh at set intervals

I have a continuous task where my code is uploading a png to an http server every few seconds. I am looking for a way to implement some kind of marker that will trigger the browser to automatically refresh every 500ms, either through browser-side javascrip ...

The process of initializing the Angular "Hello World" app

Beginning with a simple "hello world" Angular app was going smoothly until I attempted to add the controller. Unfortunately, at that point, the expression stopped working on the page. <!doctype html> <html ng-app='app'> <head> ...

Encountering issues with integrating interactjs 1.7.2 into Angular 8 renderings

Currently facing challenges with importing interactive.js 1.7.2 in Angular 8. I attempted the following installation: npm install interactjs@next I tried various ways to import it, but none seemed to work: import * as interact from 'interactjs'; ...

What is the most elegant way to retrieve a new item from Firebase and read it?

My goal is to display the result of a successful read on a page, with only one attempt available before the headers are set and the page is sent. I am looking to retrieve one new value, generated after a listener was initiated so as not to pull existing da ...

Python Selenium - The Select method can only be used with <select> tags, not <div> tags

Seeking guidance on selecting an element from a dropdown box on a work website using web scraping and selenium. As a newcomer to this technology, I am struggling and looking for some assistance in the right direction. Unlike other scenarios I have come acr ...

Guide on merging the root route with child routes using react router v6

When a user visits "/", I want it to automatically redirect them to "/todo", but this functionality is not working as expected. let router = createBrowserRouter([ { path: "/", element: <Layout />, children: ...

In React Js, the state is being updated correctly when console logging, however, the user interface is not reflecting

Recently, I encountered an issue with updating the UI after clearing the input states in my object. Despite setting the input values to empty strings upon clicking the clear all button, the UI does not reflect these changes as expected. The initial state ...

Column-oriented and Slim-fit packaging

I have been working on designing a layout with a fixed height that will display multiple columns of specified size to accommodate flowing text. While I have successfully implemented this, I am facing an issue where the enclosing div does not adjust its siz ...

Is there a way to extract an ID from a URL using PHP?

Hey there, I have a link that looks like this: I also have similar links and I'm looking to extract the ID from each one. The challenge is that the characters surrounding the ID vary for each link, so simply cutting out characters from the left and r ...

Exploring the data-* attribute in jQuery

Currently, I have a form structured as follows: <div data-role="page" data-last-value="43" data-hidden="true" data-bind='attr : {"name":"John"}'></div> My objective is to modify the name attribute from "John" to "Johnny". I am att ...

Exploring the process of web scraping from dynamic websites using C#

I am attempting to extract data from using HtmlAgilityPack. The website is dynamic in nature, displaying content after the page has fully loaded. Currently, my code retrieves the HTML of the loading bar using this method, but encounters a TargetInvocation ...

Using the not operator in Selenium IDE XPath for waitForElementNotPresent seems to be ineffective

I am facing an issue with an XPath in Selenium IDE. In a table, there are multiple records. Above the table headers, there are filtering dropdown menus and a funnel icon that triggers an AJAX function to retrieve filtered data. The problem is that Seleniu ...

Tips on transitioning from Modal1 to Modal2 in Ionic after a successful submit button press?

My survey app requires users to fill out a form and click the Submit Feedback button. Upon successful submission, a message saying "Feedback submitted successfully" should be displayed in Modal2, which is inside another modal named (Modal1). However, being ...

Set up an array data by extracting values from an array prop within a Vue component

Within my Vue component, I am dealing with an array prop called selectedSuppliers that consists of objects. My goal is to set up a data property named suppliers and initialize it with the values from selectedSuppliers. However, I do not want any modificati ...

Updating the text of an element will occur only when the specified condition has been met

I am trying to dynamically change the text within the <span data-testid="recapItemPrice">ZADARMO</span> element from 'ZADARMO' to 'DOHODOU' only when the text inside the parent element 'INDIVIDUÁLNA CENA PREP ...

The peculiar effect of a CSS element's border on surrounding elements is quite unusual

I'm experiencing a strange issue that I can't quite figure out. To demonstrate the problem, I've created a fiddle. What's puzzling me is why applying a border to one of the three canvases causes my other two .headerMainDiv elements to ...

React 18 doesn't trigger component re-rendering with redux

In my code, I have implemented a custom hook to handle global data fetching based on user authentication. Here is an example of the hook: const userState = useSelector(state => state.user.state) useEffect(() => { if(userState === "authentic ...

Increasing an element in an array of objects using MongoDB and Mongoose

In my possession is a document structured as follows: { "id": "12345", "channels": [ { "id": "67890", "count": 1 } ] } My objective is to increase the count of a specific channel by one. When a user sends a message, I must locat ...

Issues with jQuery autocomplete functionality on certain elements are not uncommon

I've been experimenting with creating a user script for Opera using Greasemonkey to implement autocomplete functionality on input elements within web pages. However, I've encountered some issues with the script not working as expected. Initially ...

Filtering dynamically generated table rows using Jquery

I'm currently working on a project that involves filtering a dynamic table based on user input in a search bar. The table contains information such as name, surname, phone, and address of users. Using jQuery, I have created a form that dynamically ad ...