Assign a class to each element that the mouse hovers over while simultaneously clicking the mouse

I am faced with a scenario where I have three boxes:

div {
  display: inline-block;
  width: 100px;
  height: 100px;
  border: 1px solid black;
  cursor: pointer;
}

div.selected,
div:hover {
  background-color: red;
  color: white;
}
<div>A</div>
<div>B</div>
<div>C</div>

I would like to click on one of the boxes and as I move my mouse while holding it down, the div should be assigned the "selected" class. Is this achievable?

Thank you.

Answer №1

Utilize jQueryUI's $.selectable() function for efficient selection: Visit link

$(function() {
  $("#selectable").selectable();
});
#feedback {
  font-size: 1.4em;
}

#selectable .ui-selecting {
  background: #FECA40;
}

#selectable .ui-selected {
  background: #F39814;
  color: white;
}

#selectable {
  list-style-type: none;
  margin: 0;
  padding: 0;
  width: 60%;
}

#selectable li {
  margin: 3px;
  padding: 0.4em;
  font-size: 1.4em;
  height: 18px;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<ol id="selectable">
  <li class="ui-widget-content">Item 1</li>
  <li class="ui-widget-content">Item 2</li>
  <li class="ui-widget-content">Item 3</li>
  <li class="ui-widget-content">Item 4</li>
  <li class="ui-widget-content">Item 5</li>
  <li class="ui-widget-content">Item 6</li>
  <li class="ui-widget-content">Item 7</li>
</ol>

Answer №2

$('.choice').click(function() {
$(this).addClass('selected');
});
div {
display: inline-block;
width: 50px;
height: 50px;
border: 1px solid #000;
}

div:hover {

background: red;
}

.selected {
background: red;
border: 3px solid green;
color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="choice">A</div>
<div class="choice">B</div>
<div class="choice">C</div>

Answer №3

$(document).on('click','div',function(e){
     $(this).toggleClass('selected');
});

Check out the live example:

https://jsfiddle.net/hrvn8y1d/

Answer №4

To address your query, it seems like you are looking for a solution using only CSS. By adding an extra property in your CSS, you can achieve the desired effect.

div {
      display: inline-block;
      width: 100px;
      height: 100px;
      border: 1px solid black;
      cursor: pointer;
    }

    div:hover {
      background-color: red;
      color: white;
    }    
    div:focus {
      background-color: red;
      color: white;
    }
<div tabindex="1">A</div>
    <div tabindex="2">B</div>
    <div tabindex="3">C</div>

Answer №5

To toggle the class selected on and off with a mouse click, you can utilize jQuery's toggleClass() function.

If you wish to permanently apply the class selected to the element, you should opt for the addClass() method instead.

$(function(){
  $("div").click(function(){
    $(this).toggleClass("selected");
  });
});
div {
  display: inline-block;
  width: 100px;
  height: 100px;
  border: 1px solid black;
  cursor: pointer;
}

div.selected,
div:hover {
  background-color: red;
  color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>A</div>
<div>B</div>
<div>C</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

Grab cell information from a dynamic table using Ruby and Selenium

I am attempting to retrieve a property of cells within a table. <table id="m-103" class="m-row" cellspacing="0"> <a name="2"></a> <table id="m-108" class="m-row " cellspacing="0"> <a name="3"></a> <table id="m-191" ...

Exploring React's Primary Button Color Implementation

I am attempting to customize the buttons in my theme for various states such as contained, primary, and hover. However, my current approach is not yielding the desired results. VIEW CODESANDBOX DEMO: CLICK HERE theme/overrides/MuiButton.js import palet ...

Reactive Form value is not displaying in view because of FormControlName issue

I have successfully retrieved data from the database and need to pre-fill an update form with preset values. The issue I am facing is that when I add FormControlName to the input field, it removes the preset values. I have tried using setValue and patchV ...

passing a variable from PHP to JavaScript

When I attempted to transfer variables from PHP to JavaScript, I found myself quite confused. It was straightforward for me to retrieve values using an ID, like this: var name = $("#name").val(); However, my question is if I want to convert a variable li ...

What is the recommended way to update radio button labels using jQuery?

Currently I am working with jQuery version 3.5.1 and have the following HTML code snippet. <form> <div><input type="radio" id="radio0" name="choice" >Option 1</div> <div><input type=&qu ...

The multi-level dropdown feature in the BootStrap-4 navbar extends off the screen when the dropdown menu is opened

I have been struggling to make this work. I used BS4 for responsiveness, and my navigation items are aligned to the right in the navbar. Despite trying various methods to position the submenu on the left of the parent menu, I still can't get it to dis ...

Is there a way to decrease the jQuery UI file size?

Hey everyone! I recently downloaded a search box suggestion from this link. However, I noticed that the .js file at is quite large at 426kb. Does anyone know of a way to reduce the code within the file or have any simpler coding suggestions for creating ...

What is the best way to swap out a div element with a text area when I press a button, all

I recently used a Fiddle found at http://jsfiddle.net/GeJkU/ function divClicked() { var divHtml = $(this).html(); var editableText = $("<textarea />"); editableText.val(divHtml); $(this).replaceWith(editableText) ...

Tips for changing the height of a table row with font-awesome icons in bootstrap 4

Every time I try to integrate a font-awesome icon into my table, the row height increases unexpectedly. My setup includes bootstrap 4 and font-awesome 4.7.0 <table class="table table-bordered table-condensed table-stripped"> <thead> ...

Python: Mimicking Splinter/Selenium Functionality to Test a JavaScript-Driven Website

My automated bot interacts with a dynamic website using Splinter and Selenium. Despite its effectiveness most of the time, it occasionally encounters exceptions due to random events. Debugging these occurrences is quite challenging, especially since the we ...

Is there a way to transform a Phaser 3 game into an android-game application?

As someone who is new to Phaser, I am curious about the possibility of converting a Phaser game into an Android game. Currently, I am utilizing Phaser with NPM for my projects. Any insights or advice on this matter would be greatly appreciated. Thank you! ...

What could be causing my AJAX code to fail in retrieving information from an API?

Hey everyone, I'm new here and hoping to get some help with an issue I'm facing. I've written a code to fetch data from an API and display it on my HTML page, but for some reason the AJAX code isn't working. There's nothing showing ...

Ensuring Input Accuracy with jQuery Form Validation

I have implemented a form validation code that is currently functioning correctly. Below is the snippet of the code I used: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script> <script ...

Having trouble adding a value to a specific location in Javascript

I have a JavaScript code that retrieves HTML markup or text data from the user and submits it to the server. Now, I have added a dialog box that collects descriptions about the code from the user on button click and sends this data to the server as a desc ...

Send the JSON output of a MySQL query as an argument to my EJS template in a Node.js/Express application

I've been using res.json(rows) to display my users on the screen, but now I want to pass the object obtained from the query to an ejs file for display. However, when I try to do this as shown in my code below, the passed object becomes a string and I& ...

Using Javascript libraries on a Chromebook: A comprehensive guide to getting started

Doing some coding on my chromebook and wondering if it's possible to download and utilize libraries such as jQuery. Would really appreciate any assistance with this! ...

A common inquiry regarding Vue: How to effectively incorporate fullpage.js wrapper with additional functionalities

Having recently delved into Vue, I am currently tackling a project that involves the Fullpage.js Vue wrapper. While I have successfully implemented the Fullpage functionality, integrating additional features like an animation-on-scroll function has proven ...

What is the most effective way to utilize forms in order to send information from both an input field and a dropdown selection menu with just one button click

Currently utilizing Material UI and React for my project. I am dealing with data from a text field and a drop down select that I want to be 'submitted' when a button is clicked https://i.sstatic.net/fvxo0.png Below is the code with unnecessary ...

Styling the React Material UI DataGrid with the MuiDataGrid-window class using createMuiTheme or makeStyles / styled-components

I've been putting in a lot of effort to customize the css for the .MuiDataGrid-window in MaterialUi's DataGrid. I've been referencing css rules from https://material-ui.com/api/data-grid/ I managed to get it working within createMuiTheme fo ...

Dropdown list remains open despite a selection being made

My problem arises when I attempt to select an item from the list, as the dropdown menu does not populate automatically and the list remains open. Here is the HTML code for the dropdown list: <label id='choose' for='options'>Sele ...