What is the best way to determine the location of just one element?

I am currently working on a rating application where only the selected circle should remain green, not all of them.

$('#rating-container').click(function () {
    var element = $('#target');
    var container = $('#rating-container');
    var index = container.children().get(element);
    var foundElement = container.children().get(index);
    var jQueryObject = $(foundElement);
    jQueryObject.addClass('rating-chosen');
});

This is the HTML structure:

<div id="rating-container">
  <div class="rating-circle"></div>
  <div class="rating-circle"></div>
  <div id="target" class="rating-circle"></div>
  <div class="rating-circle"></div>
  <div class="rating-circle"></div>
</div>

You can view the Codepen demo at the following link:

https://codepen.io/CasaDeOrellana/pen/JqqJxZ

Answer №1

To change the class of an element, you can utilize the .removeClass() combined with .toggleClass() as shown in the code snippet below. Additionally, you can determine the index using the .index() method.

$("#rating-container div").click(function(index, item) {
  $('#rating-container div').removeClass('rating-chosen'); // Comment (Delete) this line if you don't want to remove class from previous selection
  $(this).toggleClass('rating-chosen');
  console.log($(this).index());
});
body {
  font-family: Verdana;
}

h1,
h2,
h3 {
  color: darkblue;
}

.rating-circle {
  height: 2em;
  width: 2em;
  border: 0.1em solid black;
  border-radius: 1.1em;
  display: inline-block;
  margin: 0;
  padding: 0.1em;
}

.rating-hover {
  background-color: yellow;
}

.rating-chosen {
  background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="rating-container">
  <div class="rating-circle"></div>
  <div class="rating-circle"></div>
  <div id="target" class="rating-circle"></div>
  <div class="rating-circle"></div>
  <div class="rating-circle"></div>
</div>

Answer №2

Take a look at this, I just approached it from a slightly different angle:

$(function() {
  $(".rating-circle").click(
    (e) => {
      event = e || window.event;
      var target = event.target || event.srcElement;

      $(".rating-circle").removeClass("rating-chosen");

      $("#" + target.id).addClass("rating-chosen");
    }
  )
});
body {
  font-family: Verdana;
}

h1, h2, h3 {
  color: darkblue;
}

.rating-circle {
  height: 2em;
  width: 2em;
  border: 0.1em solid black;
  border-radius: 1.1em;
  display: inline-block;
  margin: 0;
  padding: 0.1em;
}

.rating-hover {
  background-color: yellow;
}

.rating-chosen {
  background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="rating-container">
  <div class="rating-circle _1" id="1"></div>
  <div class="rating-circle _2" id="2"></div>
  <div class="rating-circle _3" id="3"></div>
  <div class="rating-circle _4" id="4"></div>
  <div class="rating-circle _5" id="5"></div>
</div>

Answer №3

$(document).ready(function() {
  $(".rating-circle").click(function() {
    // reset all
    $(this).parent().find('div').removeClass("rating-chosen");
    // Set selected
    $(this).addClass("rating-chosen");
  });
});

Here is a working example

$(this).index() - Retrieves the index of the clicked circle

$(this).toggleClass("rating-chosen");
- Switches the class - adds class if it is not present, removes class if it is already there.

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

What is the best way to ensure that <div> elements adapt well within a <nav> element to be responsive?

While creating a dashboard page for a bot, I encountered an issue where the page looked great on desktop but lacked responsiveness on mobile devices. Here's how the page looked on desktop: https://i.sstatic.net/ADsXv.jpg And here's how it appe ...

Use Google script to input drop down options directly into a Google spreadsheet

After gathering coding advice from various StackOverflow examples, I've hit a roadblock while attempting to take my script to the next level. The task seems simple enough, but for some reason, I just can't figure it out. Here's the situati ...

Transferring data from JavaScript variables to PHP function through AJAX requests

Within my dashboard.php, there is a JavaScript function triggered by a button click event named getTeamMembers. This function receives values from the user's interaction and passes them to a PHP function also present in dashboard.php. Despite my effo ...

Retrieve the ID from the database and showcase the content on a separate page

My database has a table named "apartments," and I am using the following code to display its contents on a single page: $connect = mysqli_connect("localhost","root","","db_dice"); $query = "SELECT * FROM apartment ORDER BY ID DESC"; $records = mysqli_quer ...

The issue arises when the logout component fails to render even after the user has been authenticated. This problem resembles the one discussed in the React Router

While attempting to run the react-router docs example on the browser, I encountered an issue with the AuthButton component. The problem arises when the isAuthenticated value changes to true but the signOut button fails to display. import React from ' ...

Ensure the function has completed setting state before proceeding to the next function

async componentDidMount() { this.loadSelectors(); this.useSelectors(); }; loadSelectors = () => { this.setState({"Selector": "Test"}); } useSelectors = () => { console.log(this.state.Selector); } Is there a way to ensure that loadS ...

Unable to assign changing content to iframe within fancybox on completion

Struggling to add dynamic content to a dynamically created iframe within the onComplete method of fancybox? The same issue arises with static iframes. Is there a way to update the content of an iframe during runtime? $(document).ready(function() { $(" ...

Is it possible to use an input value to rotate an element?

I'm attempting to rotate a red circle with the ID of outer using Input[type=range]. I've tried selecting the circle's style, then transforming it based on the input value, but it needs to be within the parentheses of rotateZ(), which require ...

Challenges with JavaScript fetching JSON information

Resolved: To enable AJAX functionality, I needed to upload the files to my server. Currently, I am attempting to retrieve stock information from a JSON file, but no data is being displayed. Upon alerting ajax.status, it returned 0 as the result, indicatin ...

Accessing an Android device from localhost using a hostname with ever-changing IP addresses

SCENARIO: I am currently running a local webpage on a WAMP server from my computer, which is connected to a wireless network. Additionally, I have an Android tablet also connected to the same network. OBJECTIVE: My goal is to access the local webpage on ...

Steps to ensure your Bootstrap side menu spans the entire height of the page

Welcome to my side menu <template> <div class="p-3 text-bg-dark shadow"> <div class="dropdown"> <a href="#" class=" align-items-center text-white text-d ...

Flask not serving Favicon and images to a React application

I am currently working with a Flask server and have it set up in the following manner: app = Flask(__name__, static_folder="dist/assets", static_url_path='/assets', template_folder="dist") ...

How can I prevent the div from occupying space using CSS?

Below is the CSS that I am currently using. I am a beginner when it comes to CSS. I want to add a property to the CSS that will make the div take up only the necessary width, not more. For example, even if the text within the div is short (like "hi"), se ...

Using AngularJS to encapsulate an externally loaded asynchronous library as a service

Is there a way to wrap a 3rd party library that loads asynchronously into an Angular service? What is the best practice for incorporating such libraries as services in Angular? Currently, I am approaching it like this: angular.module('myAPIServices ...

Transitioning between carousel slides will reveal a clean white backdrop

I'm currently facing an issue with my html website. It seems that when I navigate through the carousel slides on my Bootstrap-5 based site, white spaces keep popping up. How can I resolve this issue? Here is a snippet of my code: HTML <!doctype h ...

Displaying Errors from Controllers in React Hook Forms

Currently, I am attempting to generate required errors for my input element that is enclosed within a Controller component from react-hook-form version 7. The Input consists of a Material-UI TextField structured like this; <Controller ...

Limit access to route in ExpressJS only to internal redirects

I'm managing an ExpressJS application that includes specific routes which I intend to only function when redirected to from my code, rather than input directly into the URL. Essentially, if a user attempts to enter "myapp.com/url" it should not be ac ...

Troubleshooting a Hover Problem in Firefox

Chrome is rendering the following code perfectly fine, but Firefox seems to be having trouble applying the hover effect. HTML <!DOCTYPE html> <html> <head> <link type="text/css" rel="stylesheet" href="stylesheet.css"/> ...

Utilizing Google Places Autocomplete to tailor search outcomes

I'm currently working on customizing the output of my Google Places autocomplete code. Specifically, I want to change the displayed result when a user selects an address from the list. For example, one of the results is: '45 Alexandra Road Holi ...

Toggle the font weight in a text area by clicking a button

I need help with creating a button that will change the font-weight to bold when clicked and then revert back to normal when un-clicked. However, I only want the specific part of the text area where the user clicks the button to be bolded, not the entire t ...