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

"Is there a way to initiate a Date Picker with the current date using Javascript in an AngularJS application

I am having an issue with my date picker where the month starts from the current month and goes up to the next 12 months. However, I only want to display dates from the current date to the last date of the current month. I believe I need to set a limit so ...

Ways to access a JavaScript object beyond the function scope

Using the code below, I am able to retrieve JSON data when an element is clicked. This data is then used to create a table, fill the cells with images, and append the table to a specific div. function LoadImagesByCategory() { $.getJSON("/Service/GetJs ...

Is there a way to create a function that is able to return both a value and a promise

Assume I need to fetch a value only if an object is already present in my model. Otherwise, I should retrieve the output of an endpoint service: model.getDoohkyById = function( id ){ if( this.data ) { if( this.data.length > 0) { ...

"Step-by-step guide on showcasing a specific blog post using its unique identifier in an Angular/Express/MongoDB application

I'm struggling to figure out how to retrieve a single blog post by its ID, especially since I am new to this. Currently, my main blog application has an ng-repeat functionality that fetches all posts. What I really want is the ability to click on a p ...

Ways to access a DOM element in Next.js when the class name is dynamically generated

I am currently developing a Next.js app (version 12.1.0) and facing an issue in my Nav component. I am attempting to select a DOM element using const nav = document.querySelector('.nav'); However, this is triggering an error message: TypeError: ...

Is it possible to successfully pass a parameter from a servlet to a JavaScript function, but encounter issues when trying to view the database

In my view servlet, I am displaying user data from the database in a table. Each row of the table has buttons that allow users to change the cells in that row to text boxes. The issue I am encountering is that when I retrieve the data and loop through to ...

Switching from jquery's $.animate to $.velocity is not effective

I have a smooth animation implemented in jQuery for scrolling to a specific element. However, the animation is quite laggy. When I click on it, it smoothly scrolls down to the desired element. $('#aboutMenu').click(function(){ $('html, body ...

Restrict the height of a division based on the adjacent division

Within the parent div, I have two child div elements that are meant to be positioned side by side. The first element contains an image which loads dynamically, meaning its height is unknown in advance. I want the parent div's total height to match the ...

CSS creates captivating image hover transitions with span elements

<a href=""><img src=""><span>content</span></a> When I hover over the image, the content within the span appears using relative positioning with display set to none and absolute positioning in the span tag. My query is regard ...

Tips on updating service variable values dynamically

I need to update a date value that is shared across all controllers in my website dynamically. The goal is to have a common date displayed throughout the site by updating it from any controller and having the new value reflected on all controllers. Can yo ...

Contradictory jQuery extensions

After exploring this site as part of my web coding self-study, I decided to register so I could ask a specific question. Currently, I am in the process of developing my new website and ran into an issue on a test page (www.owenprescott.com/home.html). The ...

Reverse the order of jQuery toggle animations

Looking for something specific: How can I create a button that triggers a script and then, when the script is done, reverses the action (toggles)? (I am currently learning javascript/jquery, so I am a beginner in this field) Here's an example: ...

Viewing all album titles simultaneously using the Flickr API

After trying a different approach due to lack of responses to my previous question, I am still facing the same issue. My code successfully retrieves all album names and corresponding photos from Flickr API, but it displays all album names at once followed ...

Implementing Next.js in a live production environment

I've been using next.js for some time now, but I'm still trying to wrap my head around how it operates in a production environment. As far as I understand it, when a request is made to the server, the server retrieves the requested page from the ...

The data in the ASP.NET MVC Model is failing to updateап

Check out the ASP.NET MVC fiddler here: https://dotnetfiddle.net/W5Nr0a. I started with 2 records in the output. After saving, if there are still 2 records displayed, the result count should also show as 2. However, even after dynamically adding rows throu ...

Which medium is the optimal choice for file manipulation in Node.js and JavaScript?

Is there a simple way for JavaScript to receive incoming data from Node.js that was obtained from an external server? I've been searching for a solution to this problem for days now. Here's my current approach: I plan to have both the server-sid ...

What is the process for encrypting and decrypting image files over the internet?

I'm currently developing a web application that requires loading images into a canvas object, followed by extensive manipulation. My goal is to conceal the original source image file (a jpeg) in such a way that users on the client side cannot access i ...

Choose the div without a class

I currently have several divs displayed on my website. <div class="slide bx-clone"></div> <div class="slide"></div> <div class="slide"></div> <div class="slide bx-clone"></div> <div class="slide bx-clone" ...

I'm feeling overwhelmed by trying to send data from Jquery to php and then successfully retrieving the data

Here's the HTML snippet I'm working with: <form action="http://localhost/xiuno" method="post"> <h1>TEST</h1><br/> <input type="submit" value="submit" id="submit"/> </form> <script type="text/javasc ...

Saving Files in Your React Web Application: Tips and Tricks

Currently, I am working on a React web application that requires the temporary storage of Torrent pieces for streaming purposes using a web player. Any recommendations on how to properly store this data temporarily in order to facilitate the streaming pro ...