CSS: Apply styles to an element when hovered over or when focused on, but not simultaneously

I am currently utilizing typeahead.js to generate a basic dropdown list.

The functionality I am aiming for is the ability for users to navigate through suggestions using the keyboard's down key and select a suggestion with the mouse. In both scenarios, the selected suggestion should be highlighted appropriately.

However, I am encountering an issue where both hovered states and selections made by scrolling with the arrow keys are being highlighted simultaneously.

This discrepancy is clearly demonstrated in the animated image provided below.

https://i.sstatic.net/y6Wnf.gif

To highlight hovered states, I have implemented the following CSS:

.tt-suggestion:hover {
  color: #f0f0f0;
  background-color: #0097cf;
}

For highlighting selections made while scrolling with the arrow keys, I've utilized the following CSS:

.tt-cursor {
  color: #f0f0f0;
  background-color: #0097cf;
}

Please note: The class .tt-cursor is automatically added to the suggestion div when scrolled to and removed when navigated away from.

For a better understanding of the situation, you can refer to this CodePen.

My implementation involves a rails backend, with most of the handling done through Javascript & jQuery.

Edit: To clarify further, I am looking to highlight only one suggestion at a time when it is either hovered over or scrolled to, instead of having multiple suggestions highlighted concurrently.

Answer №1

It appears that the solution you seek involves eliminating the hover css from your code.


  $('div').on("mouseover",'.tt-suggestion',function(){

    $('.tt-selectable').removeClass('tt-cursor')
    $('.tt-selectable').css( "color", '')
    $('.tt-selectable').css( "background-color", '')
    $(this).css( "color", '#f0f0f0')
    $(this).css( "background-color", '#0097cf')
  })
  document.onkeydown = checkKey;

function checkKey(e) {

    e = e || window.event;


    if (e.keyCode == '40') {
      $('.tt-selectable').css( "color", '')
      $('.tt-selectable').css( "background-color", '')
    }
   if (e.keyCode == '38') {
      $('.tt-selectable').css( "color", '')
     $('.tt-selectable').css( "background-color", '')
  }
}

Answer №2

The desired outcome you are aiming for is somewhat ambiguous, but if your goal is to indicate visually that an element is selected and being hovered over, you can achieve this by addressing both of these states in your CSS code:

.tt-cursor.tt-suggestion:hover {
  background-color: red;
}

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

Enhancing user experience with dynamically resized Jumbotron images based on screen sizes in HTML

I am experiencing an issue with the jumbotron images on my website where they become increasingly zoomed in as the screen size decreases, and are extremely zoomed in on mobile devices. Is this a normal behavior of jumbotrons? I do understand that the image ...

Enhancing the existing observable value by combining it with another observable

Looking for assistance with adding a value from one observable to another? The current results are unexpected, so I'm seeking guidance on whether I'm approaching this correctly. FIDDLE AT THE BOTTOM HTML: <div id="wrapper"> <ul cl ...

How to Customize Field Text in Django HTML Forms

I am utilizing a Django form: from django import forms from hello.models import Whisper class WhisperForm(forms.ModelForm): class Meta: model = Whisper fields = '__all__' When I display it on an HTML page, it looks like th ...

Ways to deactivate remaining buttons until a function call finishes after selecting one in a react render() function?

In order to prevent the overlap of results when multiple buttons are clicked simultaneously, I need to disable all toggle buttons until one function call is complete, including the reset button. Additionally, I'm looking for a way to display my functi ...

Guide to putting a new track at the start of a jPlayer playlist

I am currently working on a website that utilizes the jPlayer playlist feature. I am facing an issue, as I need to implement a function that adds a song to the beginning of the playlist, but the existing add function only appends songs to the end of the pl ...

Challenges in aligning images side by side within an XSLT document

My XML file is currently being transformed using XSLT to display tables, but I would like these tables to be displayed next to each other in rows of three columns. However, the current output shows them displaying one after another vertically. Here's ...

When attempting to read text from an HTML file, JTextPane fails to include a newline character in the output

I am currently working on a project that involves extracting text from an HTML file based on the element's id and displaying it in a JTextPane. However, I am facing an issue where the displayed text does not go to a new line. Here is a snippet of the ...

Encountering an error with an unknown variable while attempting to access a value from a JSON object

I had second thoughts about asking this question for fear of receiving a down-vote, but after extensive research and hours of typing, I have decided to go ahead. My goal is to retrieve the values 37 and exampleoffice from a json object: {"officeId":37,"o ...

Issue with Backbone model not properly processing JSON response during POST save operation

I am facing an issue with saving my model to the server and returning the ID along with other attributes. It appears that the response is being accepted as a string instead of a JSON object, leading to the entire string being added. I am using the express ...

A step-by-step guide on activating dark mode for the markdown-it-vue plugin while incorporating Vuetify styling

I'm looking to display some documentation in my Vue application. The documentation is in markdown format, so I have already integrated the markdown-it-vue plugin. However, I've run into an issue where the plugin doesn't support vuetify dark ...

Display the datepicker beneath the input field

I successfully integrated the datepicker, but I prefer for the calendar to display below the date input field rather than above it. HTML5 <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv=" ...

Combining ng-bind-html with highlight.js

I am currently working on implementing syntax highlighting for all code elements within dynamically added HTML content that will be appended to the existing page using ng-bind-html. <div ng-repeat="activity in activities"> <h3>{{activity.t ...

setting different iframe widths for desktop and mobile views

I am working with an iframe and facing a challenge. I want to make it full screen width on mobile devices, but only half the screen width on a normal monitor (100% and 50%, respectively). The minimum specification for the mobile device would be iPhone, alt ...

Is Websocket support automatically provided in Node.js?

Conflicting information has left me puzzled. While reading the node docs yesterday, I was under the impression that Node's 'net' and 'http' modules had web socket capabilities. However, today I came across an article claiming that ...

Combining JSON objects to form a new object within a JSON object using JavaScript

Here is the JSON data that I have: {"rows":[ {"shiftId":1,"shift":"Morning","item":"Tea","value":20}, {"shiftId":1,"shift":"Morning","item":"Coffee","value":30}, {"shiftId":2,"shift":"Evening","item":"Tea","value":40}, {"shiftId":2,"shift" ...

VueJS data is unresponsive upon mounting

My API is supposed to return all the currency rates. I am using a function called getRate() in the mounted section, but the value of rate['usd'] is showing as undefined. However, if I call the function again on that page, it returns the actual da ...

Scroll through the div to quickly find the relevant content

I have implemented the following HTML structure: <div style="height:200px;overflow-y:scroll;"> <table>.....</table> </div> By using this setup, I am aiming to replicate the functionality of an expanded <select> control wit ...

Deliver the Express.js: transmit outcomes post next() invocation

I have a unique app feature that allows users to create their own routes in real-time. I also want to show a custom 404 message if the route is not found, so I added this code to my last middleware: app.use((req, res, next) => { // ...normal logic ...

Attempting to transfer elements from an iteration into a separate array

Currently, I am attempting to insert an associative array into an object that is empty. However, I keep encountering the following error message: An undefined property '#<Object>' cannot be read Here is the code snippet that I am testing: ...

Is it possible to arrange buttons next to each other?

Here is the code for a specific page: HTML: <div class=main> <div class=bttn> <button>abcdef</div> <div class=content> <a href=#!>jksg</a> <a href=#!>jksg</a> & ...