Guide to applying a class to a bar with jQuery

Is there a way to dynamically add a class to the bar element when a user hovers over it? The current code I have deployed is not producing the desired output.

In CSS, we can use ".bar:hover:before" to target elements in a similar manner. How can I achieve this with jQuery?

$(function() {
  $("#bars li .bar").each(function(key, bar) {
    var percentage = $(this).data('percentage');

    $(this).css('height', percentage + '%');

    $(this).animate({
      'height': percentage + '%'
    }, 1000);
  });
});


$(window).load(function() {
  $('.bar').prepend('class="lnr lnr-star"');

})
#chart {
  width: 650px;
  height: 300px;
  margin: 30px auto 0;
  display: block;
}
#chart #numbers {
  width: 50px;
  height: 100%;
  margin: 0;
  padding: 0;
  display: inline-block;
  float: left;
}
#chart #numbers li {
  text-align: right;
  padding-right: 1em;
  list-style: none;
  height: 29px;
  border-bottom: 1px solid #444;
  position: relative;
  bottom: 30px;
}
#chart #numbers li:last-child {
  height: 30px;
}
#chart #numbers li span {
  color: #eee;
  position: absolute;
  bottom: 0;
  right: 10px;
}
#chart #bars {
  display: inline-block;
  background: rgba(0, 0, 0, 0.2);
  width: 600px;
  height: 300px;
  padding: 0;
  margin: 0;
  box-shadow: 0 0 0 1px #444;
}
#chart #bars li {
  display: table-cell;
  width: 100px;
  height: 300px;
  margin: 0;
  text-align: center;
  position: relative;
}
#chart #bars li .bar {
  display: block;
  width: 70px;
  margin-left: 15px;
  background: #49E;
  position: absolute;
  bottom: 0;
  height: 0;
  -webkit-transition: height 1s ease-in-out;
  -moz-transition: height 1s ease-in-out;
  -o-transition: height 1s ease-in-out;
  transition: height 1s ease-in-out;
}
#chart #bars li .bar:hover {
  background: #5AE;
  cursor: pointer;
}
#chart #bars li .bar:hover:before {
  color: white;
  content: "\e814" attr(data-percentage);
  position: relative;
  bottom: 20px;
}
#chart #bars li span {
  color: #eee;
  width: 100%;
  position: absolute;
  bottom: -2em;
  left: 0;
  text-align: center;
}
.lnr.lnr-star {
  font-size: 13px;
  margin-right: 1px;
  color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link href="https://cdn.linearicons.com/free/1.0.0/icon-font.min.css" rel="stylesheet" />

<div id="chart">

  <ul id="bars">
    <li>
      <div data-percentage="56" class="bar"></div><span><i class="lnr lnr-star"></i></span>
    </li>
  </ul>
</div>

Answer №1

When working with jQuery, the .addClass() method is what you need to use. Instead of prepending an item, you can achieve the same result by using:

$('.bar').addClass('lnr lnr-star');
It's important to note that when you prepend items, they are not added inside the tag but rather as another item before the selected object. To trigger a function on mouse hover using jQuery, the .hover() method comes in handy. In your HTML code, since jQuery will add classes to the icon, you can remove its existing classes. Bringing it all together would look something like this:

$(function() {
  $("#bars li .bar").each(function(key, bar) {
    var percentage = $(this).data('percentage');

    $(this).css('height', percentage + '%');

    $(this).animate({
      'height': percentage + '%'
    }, 1000);
  });
});


$('.bar').hover(function() {
  $('.bar-icon').addClass('lnr lnr-star');
}, function() {
  $('.bar-icon').removeClass('lnr lnr-star');
});
#chart {
  width: 650px;
  height: 300px;
  margin: 30px auto 0;
  display: block;
}
#chart #numbers {
  width: 50px;
  height: 100%;
  margin: 0;
  padding: 0;
  display: inline-block;
  float: left;
}
...
your CSS continues here
...
.lnr.lnr-star {
  font-size: 13px;
  margin-right: 1px;
  color: yellow;
}
<link href="https://cdn.linearicons.com/free/1.0.0/icon-font.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<div id="chart">

  <ul id="bars">
    <li>
      <div data-percentage="56" class="bar">
        <i></i> 
      </div>
    </li>
  </ul>
</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

Uploading images using the Drag and Drop feature in HTML

Hello, I'm having an issue with the drag and drop functionality. I want to expand the size of the input to cover the entire parent div, but for some reason, the input is appearing below the drag and drop div. Can anyone assist me with this? https://i. ...

The issue I'm facing with Angular 8 is that while the this.router.navigate() method successfully changes the URL

As someone who is relatively new to Angular, I am currently in the process of setting up the front end of a project using Angular 8. The ultimate goal is to utilize REST API's to display data. At this point, I have developed 2 custom components. Logi ...

The state update does not seem to be affecting the DOM

I've implemented this component in my React app. It updates the state every second, but oddly enough the value <p>{this.state.time}</p> is not changing as expected. When I print the state value, it does change every second. import React f ...

Files with extensions containing wildcards will trigger a 404 error when accessed from the public folder in NextJS

I have successfully set up my public folder to serve static files, however I am encountering an issue with files that have a leading dot in their filename (.**). Specifically, I need to host the "well-known" text file for apple-pay domain verification, wh ...

Ways to resolve the error message "TypeError: 'setOption' is not a function on type 'MutableRefObject' in React"

CODE export default function EChart({ option, config, resize }) { let chart = useRef(null) let [chartEl, setChartEl] = useState(chart) useEffect(() => { if (resize) { chartEl.resize() } if (!chartEl.cu ...

Error: The value is null and cannot be read

My external application is set up within a const called setupRemote, where it starts with the appConfig in the variable allowAppInstance. export const setupRemote = () => { if (isRemoteAvailable) { try { ... const allowAppInstance = S ...

The sequence of elements within a React.addons.createFragment object

Currently, I am exploring the documentation on creating fragments in React from https://facebook.github.io/react/docs/create-fragment.html. It appears that the engineers at Facebook place a significant emphasis on the object memory layout, specifically the ...

Combining arrays that run parallel in Jquery

Seeking a solution similar to looping through multiple arrays in parallel using jQuery, but this time to construct an HTML page. I have three sets of parallel objects with arrays, potentially forming a 2D array. {"images":["Bellevue\/images\/1. ...

Why are my video files exhibiting inconsistent behavior?

I've encountered an issue with the code on my website where I'm trying to display a 40-second video. The video converter I used seems to have added extra video types, which may be causing the problem. Here's what the HTML code looks like: ...

Designing borders for tables

My current table styling approach is as follows: #content table { width: 100%; margin-top: 1em; border-collapse: collapse; border: 1px solid #222; } #content table td { border: 1px solid #888; padding: .3em; } I aim to create tab ...

Having trouble with e.preventDefault() not working on submit() in Javascript?

I'm facing an issue with submitting a form using JavaScript submit() LIVE ACTION : https://jsfiddle.net/98sm3f3t/ HTML : <form id="myForm" action=""> First name: <input type="text" name="fname"><br> <button id="myButton ...

"Creating a dynamic dropdown menu and sub-menu in PHP using MySQLi with unique slug values

I need to generate a dynamic menu from the database, including main menus and submenus. For instance: <li class="<?= ($pg == 'departments') ? 'active':''; ?>"> <a href="departments">Departments</a> ...

Turn off the background of a div

Greetings! I am working on a webpage that includes a button. Upon clicking the button, I would like to display a div and disable the content behind it. The div will also contain a button that can be clicked to hide the div. As a newcomer to Web Programmi ...

Vertically arrange the table for better visibility

I need help with changing the table layout from horizontal to vertical. Currently, all fields are displayed horizontally and I want them to be displayed vertically. Also, I'm trying to add a functionality where the current date is added to the databas ...

Can we include intricate items within a redux store?

As I delve into developing a React application with Redux, I encountered an unexpected scenario. At one point, we inserted a DOM element within the store, causing issues with the Redux extension that freezes when the action is triggered. Despite this compl ...

What is the best way to implement a scrollbar in a specific div rather than the entire window?

Hey everyone! So, I have this window in electronJS with a div where I'm dynamically adding elements using Javascript and the function --> document.createElement('section'). Here's the loop in Javascript to add these elements: for ( ...

Filtering controls within a table are not displayed in VueJS

I have been attempting to implement date filtering in my data table based on a demo I followed. Despite meeting the filter requirements, no results are being displayed which is perplexing. Below are the imports and data from the file containing the table: ...

SASS - issue with font face not displaying correctly due to incorrect file path

I've recently delved into the world of SASS and I'm encountering a dilemma with importing two specific fonts: Montserrat and Open Sans. Typically, in regular CSS, you would use something like this: @font-face { font-family: 'Montserrat& ...

Using the combination of PHP, AJAX, and MySQL, one can create a select filter that utilizes xmlhttp.open

After following the example from http://www.w3schools.com/php/php_ajax_database.asp, I successfully created a table echoing data from a database. However, my attempts to implement the datatables plugin on the table have been unsuccessful. Despite setting ...

Adhesive strip attached inside a flex box container

Within my parent container, I am using flex-box to organize the layout. One of the child divs (.child-two) needs to stick out 60px from the top once it reaches the header. Unfortunately, setting position: sticky doesn't work when the parent containe ...