Adjusting the text size of upcoming elements using JavaScript

Currently, I am in the process of developing a basic chat bot. Upon receiving a new message from the server, a fresh HTML element is generated and sent to the browser. For instance, when message 1 is received, it will appear as follows:

<div class="message-computer"><p>Hi, how are you?</p></div>

Subsequently, the user types or sends a response, which will display like this:

<div class="message-user"><p>I am good, thanks!</p></div>

This cycle continues with each exchange between the server and user. As part of the functionality, I implemented a slider interface that allows users to adjust the text size being transmitted through the chat bot. While this feature does currently work, it only alters the font size of existing HTML elements. The newly incoming messages still maintain the original size.

To provide uniformity in font size across all message elements, I crafted the following JavaScript code snippet:

$('input').on('change', function() {
  var v = $(this).val();
  $('.message-computer p').css('font-size', v + 'em')
  $('.message-user p').css('font-size', v + 'em')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="range" value="1" min="1" max="1.6" step=".1" id="slider" ondrag="changeSize()" />

If you have any suggestions or solutions on how to extend the font size adjustment functionality to encompass all new message elements, please do not hesitate to share your insights.

Appreciate it!

Answer №1

It seems like there may be a misunderstanding with your issue, as the code snippet you provided does not contain any text.

When using jQuery to update styles, each CSS statement is added individually to the style attribute of each element (you can check this in your browser inspector). As a result, newly added elements will not have their style attributes modified until you change the input value, causing them to inherit global CSS rules.

I recommend applying the font style to the parent elements .message-computer and .message-user. If that's not possible, you could wrap p elements in a dedicated div and apply the style to the div instead.

If you absolutely need to apply the style to each element individually, consider running $('input').trigger('change'); immediately after inserting new elements into the DOM.

Answer №2

If you wish to apply a CSS rule to all like-elements on a webpage, start by adding a class to the parent tag of your HTML. This way, any additional elements with the same class will be affected by the CSS rule.

For example, consider the following code snippet as a demonstration. It could be optimized for efficiency but serves to illustrate the concept:

$('input').on('change', function() {
var v = $(this).val();
    $('.parent').removeClass('font-1');
    $('.parent').removeClass('font-2');
    $('.parent').removeClass('font-3');
    $('.parent').removeClass('font-4');
    $('.parent').removeClass('font-5');
    $('.parent').addClass('font-' + v);
});
.parent.font-1 .message {
    font-size: 1em;
}
.parent.font-2 .message {
    font-size: 2em;
}
.parent.font-3 .message {
    font-size: 3em;
}
.parent.font-4 .message {
    font-size: 4em;
}
.parent.font-5 .message {
    font-size: 5em;
}
.message-computer {
    color: red;
}
.message-user {
    color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="range" value="1" min="1" max="5" step="1" id="slider" ondrag="changeSize()" />

<div class="parent font-1">    
    <div class="message-computer message"><p>I AM ROBOT</p></div>    
    <div class="message-user message"><p>Only human.</p></div>
</div>

Answer №3

When you need a new node to take on certain rules, instead of just modifying an existing node, you can create a JavaScript function that dynamically adds or updates a CSS node.

function adjustFontSize(v)
{
     var css = [
       ".message-computer p, .message-user p {font-size: "+v+"em;}"
    ].join("");

    var head = document.head || document.getElementsByTagName('head')[0];
    var style = null;

    if(!document.getElementById("customTextSize"))
    {
        style = document.createElement('style');
        style.id = "customTextSize";
        style.type = 'text/css';
        style.appendChild(document.createTextNode(css));
        head.appendChild(style);
    }
    else
    {
        style = document.getElementById("customTextSize");
        style.removeChild(style.firstChild);
        style.appendChild(document.createTextNode(css));
    }

}

Simply call the function in your change event:

adjustFontSize(v)

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

Techniques for simulating functions in Jest

I have a pair of basic components that I'm currently creating tests for using jest. My goal is to verify that when I click on a currencyItem, the corresponding array gets added to the select state. To achieve this, I am passing the handleCurrencyToggl ...

Unending cycle in React with a custom hook

After attempting to create a method using a custom react hook to streamline state logic across multiple components, I encountered an invariant violation labeled "prevent infinite loop". function useCounter(initial) { const [count, setCounter] = useState ...

Contrasting the impact of utilizing async:false in conjunction with a callback function versus utilizing jqXHR.done()

According to the jQuery documentation: Starting from jQuery 1.8, using async: false with jqXHR ($.Deferred) is deprecated. Instead, you should utilize the success/error/complete callback options instead of methods like jqXHR.done() or the deprecated jqX ...

Using CSS to style PHP function results

I am working on a shopping cart application and I want to incorporate a condensed version of the cart onto my home page. The main shopping cart page is called 'modcart.php' and I have managed to integrate it into my homepage using the following c ...

`How can a child component in Next.js send updated data to its parent component?`

Currently diving into Next.js and tinkering with a little project. My setup includes a Canvas component alongside a child component named Preview. Within the Preview component, I'm tweaking data from the parent (Canvas) to yield a fresh outcome. The b ...

Preventing the user from using the mouse wheel until the CSS animation finishes

I am working with multiple functions that are triggered by scrolling the mouse wheel up and down. These functions must be called in a specific order, but the issue arises when users scroll quickly causing the CSS animations from the previous function to ...

Unable to display service cost after passing ID through Ajax request for cost retrieval. The ID is successfully being passed, but the cost remains elusive

I've encountered an issue while trying to execute a seemingly simple ajax request. The goal is to send an "id" through ajax to fetch the service cost of an item with that specific "id". Although the ajax successfully sends the id to my "getcost.php" ...

Display a loading symbol when the iframe is being loaded and also when its source is being changed

Is it possible to have a loading.gif displayed when my iframe is loaded? I managed to do this using some code I came across here: Displaying a loading gif while iframe content loads However, there is a new issue on my website. I have checkboxes and radio ...

When a React CSS class is deployed to a production server, it may be automatically

I've encountered a strange CSS issue while working on my React project. One specific section of the JSX <div> has a class with style properties defined in the main .css file. During local development, everything appears as expected. However, aft ...

What advantages does utilizing an angular directive provide in the context of a comment?

Up to now, I have primarily used Directives in the form of Elements or Attributes. Is the Comment style directive simply a matter of personal preference for style? app.directive('heading', [function () { return { replace: true, ...

One web page featuring various query_posts

I'm in the process of developing a new template page for a WordPress theme that will feature 5 distinct "modules" embedded within the page's content section. These modules are designed to display the latest 4 posts from different categories, simi ...

Combining Ajax and Jquery with Symfony3

I can't figure out what's wrong with this code. There are no errors, but it just doesn't seem to work as expected. What I need is for a textarea to appear containing all the information when I click on a table row. <script> ...

Displaying a set through an express server cookie for the client to see

New to using Express and encountering issues with sending cookies. Created a basic express app that is supposed to set a cookie in the browser. Here's the server setup: const express = require('express'); const cookieParser = require(' ...

Customize the appearance of an ASP link button within a navigation menu

Just getting started with ASP.net and CSS, I want to customize my link button using CSS similar to other <a href> buttons, but I seem to be running into some issues. This is the code for my menu: <div id="templatemo_menu"> <ul ...

To change the font color to red when clicked, I must create a button using HTML, CSS, and Javascript

Currently, I am utilizing CodePen to assess my skills in creating a website. Specifically, I am focusing on the HTML component. My goal is to change the font color to blue for the phrase "Today is a beautiful sunny day!" Here is the snippet of code that I ...

Bootstrap resource failed to load

I successfully connected the most recent version of bootstrap.min.css to my webpage using <link rel="stylesheet" href="assets/css/bootstrap.min.css">. Initially, everything was running smoothly. However, I now encountered an issue where my browser is ...

Utilizing a confined environment to retrieve a value in order to conceal certain buttons

My goal is to utilize an isolated scope in order to access the hideButtons property within the directives named todo-cardui and todo-formui: app.directive("todoFormui",function(TodoService){ var dirDefObj = { restrict:'E', t ...

Stop the submission of a form using jQuery based on its unique identifier

When using the jQuery Ajax function to verify if a user email exists in the database during a jQuery change event, there are two possible outcomes in the Ajax response. If the user email does exist, an error message is displayed. In this scenario, I aim ...

Initiating a POST request to an ASP.NET Web API endpoint

I'm encountering an issue while trying to send a POST request to an ASP.NET Web API. Below is the snippet of code causing trouble, any assistance would be greatly appreciated: WebAPiConfig.cs public static class WebApiConfig { public static void ...

How to activate a button only if the specified conditions are met using VueJS 3

I'm currently facing challenges while working on a form to enable a button when certain conditions are met. The form I created includes fields for name, phone number, options, and a message. Once all requirements are filled, I aim to re-enable the di ...