Adjust the size of the font in accordance with the value of the span text

I am looking to adjust the font size based on the value within the span element.

The numbers in the class name may vary.

Issue: using text() retrieves all values (e.g. 50020)

I want to incorporate each() and $this in some way. How can I do this?

Thank you

<span class="emo_vote-1">50</span>
<p>something.</p>
<span class="emo_vote-2">0</span>
<p>something.</p>
<span class="emo_vote-3">20</span>

jQuery

var voteNumberSpan = jQuery("span[class^=\"emo_vote\"]");
    var voteNumber = voteNumberSpan.text();
    //console.log(voteNumber);
    if (voteNumber <= 30) {
        voteNumberSpan.css("fontSize","10px")
    } else if(voteNumber == 50) {
        voteNumberSpan.css("fontSize","16px")
    } else  {
        voteNumberSpan.css("fontSize","24px")
    }
    //I tried also:
    //voteNumberSpan.each(function (i) {
        //var voteNumber = voteNumberSpan.text();   
        //if (voteNumber < 30) {
        //voteNumberSpan.css("fontSize","10px")
        //} else if(voteNumber == 50) {
        //voteNumberSpan.css("fontSize","16px")
        //} else  {
        //voteNumberSpan.css("fontSize","24px")
        //}
    //});

jsfiddle http://jsfiddle.net/lima_fil/5VTN4/2/

Answer №1

Visit this link to see the code snippet in action.

    When the document is ready,
    for each element with a class starting with "emo_vote",
    get the text content and store it as voteNumber.
    If the vote number is less than or equal to 30, set the font size to 10px.
    If the vote number is 50, set the font size to 16px.
    Otherwise, set the font size to 24px.

Answer №2

Check out this code snippet: http://jsfiddle.net/5VTN4/5/

This code snippet utilizes the each method and leverages the text value for determining size:

 jQuery(document).ready(function(){
     $("span[class^=\"emo_vote\"]").each(function(){
        alert($(this).text());
        $(this).css("fontSize", $(this).text() + "px")
     });
});

Answer №3

If you have multiple class names for different span elements, it's a good idea to add a generic class name to group all relevant spans together. This way, you can easily target them with jQuery using a single selector. Here is an example of how you can achieve this:

jQuery('span.emo-vote').css('font-size', function(){
    var size = parseInt($(this).text(), 10);
    if (size <= 30) {
        return '10px';
    }
    else if (size > 30 && size <= 50) {
        return '16px';
    }
    else {
        return '24px';
    }
});

Here is the corresponding HTML structure:

<span class="emo_vote-1 emo-vote">50</span>
<p>something.</p>
<span class="emo_vote-2 emo-vote">0</span>
<p>something.</p>
<span class="emo_vote-3 emo-vote">20</span>

You can view a demo of this code on JS Fiddle.

It's worth noting that you don't need to use the each() function in this case. The css() method can accept an anonymous function which will apply the style changes to each selected element individually.

For further information, you can refer to the following resource:

Answer №4

Follow this method:

  1. Specify the font size range: from 10px to 24px.
  2. Assign a rate to each span.

    <span class="emo_vote-1" data-i2="fontSize:[10,24],key:'k',rate:50" >50</span>
    <p>smth.</p>
    <span class="emo_vote-2" data-i2="key:'k',rate:0" >0</span>
    <p>smth.</p>
    <span class="emo_vote-3" data-i2="key:'k',rate:20">20</span>
    

View demo

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

The issue I am experiencing within my PHP code is that the redirection to the gratitude page is not functioning correctly when utilizing

As a newcomer to PHP, I have been struggling with an example code from a website that is not redirecting to the thank you page as expected. Moreover, the email functionality is not working properly either. The code was sourced from: Upon downloading the f ...

Bone Structure Styles - adaptable form

I'm currently working on a form using skeleton css and initially set it up with a three-column layout. However, I found that this created too much white space due to varying content lengths in each column. I would like to switch to a horizontal layout ...

Why is my backend sending two Objects in the http response instead of just one?

When I receive data from my Django backend, sometimes instead of one object I get two objects within the HTTP response. This inconsistency is puzzling because it occurs intermittently - at times there's only one object, while other times there are two ...

Using jQuery's .load() function to exclusively receive image bytecodes

I am utilizing jQuery's .load() function to receive the bytecode of loaded images. Could it be due to a lack of specified MIMEType? because I'm using an image URL without a file extension? necessary to wrap the entire operation somehow? Here& ...

An easy guide to accessing a data attribute using the .on function!

In my quest to retrieve the HTML data attribute labeled productId, I attempted the following code snippet: $('body').on("click", '.myButton', function () { var productId = (this).dataset.productId; }); I have multiple but ...

Identifying when two separate browser windows are both open on the same website

Is it possible to detect when a user has my website open in one tab, then opens it in another tab? If so, I want to show a warning on the newly opened tab. Currently, I am implementing a solution where I send a "keep alive" ajax call every second to the s ...

The file import is restricted based on the user's input

I am facing an issue with my small vue.js app. My goal is to import a specific json file based on user input. import content from "@/posts/posts/" + new URL(location.href).searchParams.get('id') + ".json"; Every time I attem ...

How can you modify two distinct append values individually in AngularJS?

I am facing a challenge with two-way binding. I want to be able to change the name of each appended value from the displayed field options. When I try to append two additional fields, I am unable to change the name of each multiple field from the single fi ...

How can we prevent floating li elements from overlapping the parent div element?

What could be causing the yellow stripe (#header) to disappear when I apply "float left;" to "#header ul li"? Despite setting a fixed size for "#header ul li", I anticipated that the list items would line up next to each other horizontally, not exceeding t ...

utilizing jQuery to deliver a $.post request to a .aspx file

Recently, I started following a jQuery tutorial on the phpAcademy channel hosted on thenewboston. In this tutorial, they demonstrate how to create an email validation form using ASP.net instead of PHP. However, despite following all the steps in the tutor ...

Tips for personalizing Ion text area in Ionic?

Seeking assistance on how to effectively utilize ion-textarea. As a novice in the realm of Ionic, I am encountering various challenges while working with this feature. The issue lies in the fact that instead of displaying a scrollbar on the right side, the ...

Using border-spacing on table body rows exclusively

In my table, I have 2 header rows and multiple body rows. To create a spacing of 10 pixels between body rows, I used the following CSS: border-collapse: separate; border-spacing: 10px; However, this also affected the spacing in the header rows, which I w ...

My jQuery Ajax seems to have a glitch, can someone help me figure out

Looking for some help with this HTML code: <section id="login"> <form> <input type="text" name="username" size="10" placeholder="username" /> <input type="password" name="password" size="10" placeholder="password" ...

jquery button returned to its default state

Jquery Form Field Generator |S.No|Name|Button1|Button2| When the first button is clicked, the S.No label and name label should become editable like a textbox. It works perfectly, but if I click the second button, the field becomes editable as expected, ...

What could be causing the misalignment of my select box in Bootstrap framework?

I'm currently trying to replicate the layout of the second image shown below, as seen in the first image. However, I'm facing an issue with the positioning of the selection box and I can't seem to figure out why. I've experimented wit ...

What steps can I take to use CSS to disable a webpage?

Is there a way to create a disabled web page using CSS where users cannot click on any content and only view the content below the screen? ...

Having trouble with sending information to the PHP server, unable to determine the root cause

Can someone help me figure out why the data from a form being sent to a php script for sending an email isn't working correctly? It's part of a template code but I suspect there might be an error. Specifically, I believe the {'userName' ...

Retrieve data from an ASP.NET Web API endpoint utilizing AngularJS for seamless file extraction

In my project using Angular JS, I have an anchor tag (<a>) that triggers an HTTP request to a WebAPI method. This method returns a file. Now, my goal is to ensure that the file is downloaded to the user's device once the request is successful. ...

Importing external components from the parent directory in Next.js is a seamless process

I am trying to import react components from an external directory called common into the web-static directory while using nextjs. However, I keep encountering an error that says: Module not found: Can't resolve 'react' in '/Users/jakub ...

CSS Float issue on resizing: avoid element displacement due to margin or padding (responsive layout)

Having an issue that I need help with: My header includes a menu, news sliding with flexslider, and a search input: The problem occurs when I resize the browser manually or reload it with a smaller width; the right element jumps down, causing a pushdown ...