Display an image according to the text input

I am working on a static page where I need to showcase the percentage of a project spent on different practices. Is it possible to set a background image in the li element based on the value displayed? I believe javascript could provide a solution for this, but it's not my area of expertise.

There are 4 potential values (25 / 50 / 75 / 100) and each one should trigger the display of a different image within the li element.

The current HTML structure is as follows:

<div class="col-md-6">
  <ul class="list-inline stats">
    <li>25<small>Strategy</small></li>
    <li>25<small>Design</small></li>
    <li>25<small>Production</small></li>
    <li>25<small>Marketing</small></li>
  </ul>
</div>

I would greatly appreciate any guidance or assistance on how to achieve this. Thank you so much in advance.

Answer №1

If you want to dynamically add classes to elements using JavaScript based on certain numbers, you can achieve it by following this method:

$('.list-inline li').addClass(function() {
   return 'bg' + this.firstChild.nodeValue;
});

After adding the classes through JavaScript, make sure to declare corresponding styles in your CSS:

.bg25 { background-image: ... }    
.bg50 { background-image: ... }

For a different approach, you can create a JavaScript object and utilize the jQuery .css() method like so:

var bgs = {
   '25' : 'url(...)',
   '50' : 'url(...)',
   '75' : 'url(...)',
   '100': 'url(...)'
   // ...
}

$('.list-inline li').css('background-image', function() {
    return bgs[this.firstChild.nodeValue];
});

Answer №2

Is it possible to create a similar concept?

XHTML

<li class="progress_bar" data-value="50">50<span>Progress</span></li>

JavaScript

let current_value = 0;

$(".progress_bar").each(function(){
    current_value = $(this).data('value');
    $(this).css({'background-image':'url('images/'+current_value+'.png')'});
});

Answer №3

Are you looking at a static page? If so, consider adding unique styles to each list item based on their values. For example:

<li style="background-image:url('image1.gif');">
<li style="background-image:url('image2.gif');">
<li style="background-image:url('image3.gif');">
<li style="background-image:url('image4.gif');">

Answer №4

By adding a class to the li element, you can easily set your image using CSS.

$(document).ready(function(){
    var $elem = $('.list-inline li');
    var strClass = $elem.html().substr(0,2);
    $elem.addClass(strClass);
});

If there is no class name provided, it's recommended to add a custom string to avoid starting the class name with digits. Therefore, the last line should look something like this:

$elem.addClass('myNewStyle '+strClass);

Answer №5

To achieve this, you can utilize jQuery's :contains() selector. As demonstrated in this example fiddle:

$('.list-inline.stats li:contains(25)').css({background: 'red'})
$('.list-inline.stats li:contains(50)').css({background: 'green'})
$('.list-inline.stats li:contains(75)').css({background: 'blue'})

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

Do Scss mixins have the ability to adapt to different screen sizes

In my CSS, I set different font sizes for different devices: For example: @media only screen and (min-width: 480px) and (max-width: 599px) { t-heading { font-size:14px; } } @media only screen and (min-width: 600px) { t-heading { font-size:24px; } } I ...

What is the reason for nesting divs within each other?

Can anyone help me troubleshoot this Django template code? I have noticed that the main-card-faq div is being rendered inside the main-card div even though it's clearly outside. Any thoughts on what might be causing this issue? {% extends 'base.h ...

Unique style pattern for parent links with both nested and non-nested elements

I am in the process of designing a website and I have a specific vision for how I want my links to appear, but I am unsure of how to achieve it. Here is the desired outcome: a red link a green link a red link a green link … Below is the HTM ...

Transfer a table row between tables - AngularJS

I am seeking guidance on how to implement ng-repeat in order to transfer data from one table to another. Essentially, I have a "master" table that displays data fetched from an API request. Each row in this table has a button labeled "favorite-this-row". W ...

Applying CSS selectively based on conditions with the SELECT OPTION statement

For my array of locations, I am attempting to style location two in a unique way - with a deleted look featuring a red background and white text that is crossed out. When this option is selected by the user, I want the closed dropdown to display the same r ...

Beginner tips for adding padding in CSS

Could anyone clarify a discrepancy in the material provided here: w3schools.com code example According to the code : th,td { padding:5px; } Also, based on their explanation here: http://www.w3schools.com/cssref/pr_padding.asp The explanation states tha ...

Angular 14 debug error: Incorrect base path setting

Whenever I go for a run, I have to specify a starting point such as /pis/ ng serve --serve-path /pis/ Even after following these instructions, nothing seems to load. Can anyone lend a hand with setting a starting point in the ng serve process? ...

Is it possible to insert a variable into a span or v-tooltip tag?

I am currently using vue 2 along with vuetify 2, and I seem to be encountering an issue when attempting to display data from a table. Whenever I insert curly braces between the v-tooltip tags, it results in a blank page. Below is an example of the code: &l ...

Unable to successfully implement the CSS not selector

My webpage's code was created through the use of Wordpress. <div class="header-main"> <h1 class="site-title"><a href="http://wp-themes.com/" rel="home">Theme Preview</a></h1> <div class="searc ...

Injecting scripts into Joomla templates

Recently, I've been facing a strange issue on multiple Joomla websites that I manage. Mysterious scripts have started appearing out of nowhere. One such script looks like this: Despite deleting them manually, these scripts just keep coming back. Can ...

Filter JavaScript elements by conditions and true/false values

I can't quite recall the answer to this at the moment. Consider an array of Vendors (this is just placeholder data): [ { "user_updated": null, "user_created": "128a84b5-275c-4f00-942e-e8ba6d85c60e", "d ...

Display or conceal several buttons using ReactJS

Currently, I am working on implementing a feature in ReactJS that involves showing and hiding different buttons for multiple view options, but I have hit a roadblock. Specifically, my task involves executing queries based on user input using reactJS. My g ...

In Bootstrap 4, IE 11 struggles with images overflowing within a d-flex div containing an img tag

My webpage utilizes the bootstrap 4 grid system and appears correctly on most browsers, except for IE 11. If you check out this snippet on jsfiddle in IE 11, you'll notice that the image gets stretched inside a d-flex container. How can I resolve this ...

Transition from traditional class-based components to functional components

I am utilizing the ref from the parent class to access the child class. However, in this scenario, I want to access the child functional component from the parent class. In the parent class: class Waveform extends Component { constructor(props){ s ...

The art of placing images using CSS

I'm having trouble aligning the images into two rows of three, with the news section on the right side below the navigation bar. I've tried different methods but can't seem to get it right. Both the image and link should be clickable, but I& ...

What is the method to stop the interval in JavaScript?

[UPDATE: I appreciate the assistance from everyone. I can see that my question received some criticism for lack of research and other factors. My apologies for any oversights, and thank you for your understanding. As a newcomer to coding and stackoverflow, ...

Upon submission in Vue, the data variable becomes undefined

I set isError to false in the data, but when there is an error from Laravel, I receive a 422 error. I want to then set isError to true, but when I do, I get an error in the console saying that isError is undefined even though it has been defined. What coul ...

Issue with peculiar circumstances regarding the JSON object and generating a chart, can you pinpoint what's amiss?

When sending data (values and dates) from a hard-coded function, everything works fine - the JSON file is populated and the chart is displayed. However, when I send data from the database, the JSON file is populated but the chart does not appear. Here is ...

Best Practices for Integrating PHP Code into an HTML File for Contact Form Placement

My current setup involves an html file named index.html, which contains the code for my contact form fields such as name and email. Is there a way to include PHP code in this file without converting it to index.php? ...

Implement a fade-in animation with opacity on the background image when the page is loaded

Is there a way to create a background image that fades in from invisible opacity to 50% opacity and remains there using only CSS, without any JavaScript? I came across a similar question on Stack Overflow, but the solution seemed too complicated for me. Pe ...