Adjust the text size within a div element

I'm having trouble adjusting the font size of the bodytext div. When using the code snippet below on a page with various formatting styles, and nested inside a <div id="bodytext">, it doesn't seem to work as intended. It ends up altering line spacing instead of the font size itself.

Functioning Code:

var $affectedElements = $("#bodytext");

$affectedElements.children().each( function(){
  var $this = $(this);
  $this.data("orig-size", $this.css("font-size") );
});

$("#btn-increase").click(function(){
  changeFontSize(1);
})

$("#btn-decrease").click(function(){
  changeFontSize(-1);
})

$("#btn-orig").click(function(){
  $affectedElements.children().each( function(){
        var $this = $(this);
        $this.css( "font-size" , $this.data("orig-size") );
   });
})

function changeFontSize(direction){
    $affectedElements.children().each( function(){
        var $this = $(this);
        $this.css( "font-size" , parseInt($this.css("font-size"))+direction );
    });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<button id="btn-decrease">A-</button>
<button id="btn-orig">A</button>
<button id="btn-increase">A+</button>

<div id="bodytext">
  <p style="font-size : 30px">This text is initially 30px</p>
    <p style="font-size : 20px">This text is initially 20px</p>
    <p style="font-size : 10px">This text is initially 10px</p>
    
  </div>  
</div>

Issue (that requires correction):

var $affectedElements = $("#bodytext");

$affectedElements.children().each( function(){
  var $this = $(this);
  $this.data("orig-size", $this.css("font-size") );
});

$("#btn-increase").click(function(){
  changeFontSize(1);
})

$("#btn-decrease").click(function(){
  changeFontSize(-1);
})

$("#btn-orig").click(function(){
  $affectedElements.children().each( function(){
        var $this = $(this);
        $this.css( "font-size" , $this.data("orig-size") );
   });
})

function changeFontSize(direction){
    $affectedElements.children().each( function(){
        var $this = $(this);
        $this.css( "font-size" , parseInt($this.css("font-size"))+direction );
    });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<button id="btn-decrease">A-</button>
<button id="btn-orig">A</button>
<button id="btn-increase">A+</button>

<div id="bodytext">

Suitable alongside several formatting styles that require modifications for consistency.
Fetching the original data tied to sizing elements allows for easy reset options.

Offer valid clues or insights rather than encrypted guesswork potential.
Encourage team playing and positive reinforcements when formerly faced with distress.

Answer №1

After some discussion in the comments, it became clear that the root of the issue lies within the

var $affectedElements = $("#bodytext");
selector. This specific selector is targeting only the blockquote element because it happens to be the direct sibling of the #bodytext element.

What this essentially means is that any changes to the font size would only affect the blockquote element. Since CSS follows a cascade effect within the browser's DOM, if you set a font size of 13px for the blockquote but then have an inline style applied later down the hierarchy to one of its siblings, that inline style will take precedence.

To address this issue, I've modified the selector by adding a *, which selects all elements inside the #bodytext. This adjustment serves as a demonstration of where the problem with the selector lies. However, it's advisable to consider better ways of selecting the specific elements required or removing any inline styles directly from the HTML.

It's worth noting that the only alterations made to the HTML were to tidy up any broken tags.

var $affectedElements = $("#bodytext *");

$affectedElements.children().each( function(){
  var $this = $(this);
  $this.data("orig-size", $this.css("font-size") );
});

$("#btn-increase").click(function(){
  changeFontSize(1);
})

// Additional functionality...
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<button id="btn-decrease">A-</button>
<button id="btn-orig">A</button>
<button id="btn-increase">A+</button>

<div id="bodytext">
  
<blockquote>
    <h1 dir="ltr" align="center">
    <span style="font-size: 35pt" lang="ar-sa">title page</span></h1>
    // More content...
  </blockquote>   
</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

The appearance of the React user interface in my app does not match what is displayed in the inspect element tool

Strange issue at hand. The progress bar in question appears like this: 1 export default function PercentageBar(props) { 2 return ( 3 <div className="w-full h-1 my-1 bg-stone-200"> 4 <div className={`h-1 bg-orange- ...

Having issues setting a property value on a Mongoose result in a Node.js application

Hello there, I am currently working with a MongoDB object retrieved via a findById method, and I need to convert the _id within this object from an ObjectID type to a string. I have developed the following function: student: async (parent, { _id }, ...

Alter the URL and CSS upon clicking an element

Currently, I am faced with a challenge on my website where I have multiple pages that utilize PHP to include content and jQuery to toggle the display of said content by adjusting CSS properties. However, I am encountering difficulty in implementing this ...

Having trouble locating the componentwillunmountafterInteraction in the React Native deck swiper

I've been utilizing react native deckSwiper in my project, but I'm having trouble unmounting it from the screen due to an error that says "ReferenceError: Can't find variable componentWillUnmountAfterInteractions". The error stack trace is s ...

Hovering over the top menu items in AngularJS will reveal dropdown submenus that will remain visible even when moving the cursor

I am facing an issue where my top menu has links that display a dropdown of additional menu items upon hovering. I have attempted to use onmouseover and onmouseleave events to control the visibility of the sub menu. However, I have encountered a problem ...

The compatibility between an Ajax client and a Django server across different domains is only possible when using JSONP

Currently, our Django application is functioning on tomcat with Basic Authentication. I am interested in making cross-domain requests, and have found that it only works when using $.ajax({...dataType: 'JSONP',...}). The use of dataType: JSON does ...

Using Javascript to link various arrays filled with file paths and transforming them into an object in a distinctive manner

I've tried countless times to make it work, but it just doesn't seem to work... I have an array that contains multiple other arrays: let arr = [ ["Users"], ["Users", "john"], ["Users", "john", "Desktop"], ["Users", "john", "Docum ...

The AWS lambda function is experiencing difficulties with the AWS.HttpClient handleRequest operation

In my Node.Js lambda function, I am utilizing AWS HttpClient's handleRequest to search an ElasticSearch URL using the AWS SDK. I am following the guidelines provided in the AWS Documentation. Click here for more information on ES request signing. Pl ...

Implementing JSON data presentation in Laravel: a step-by-step guide

I have implemented an AJAX call to retrieve data from the database in JSON format, but I am facing difficulties displaying it on the view. Below is my AJAX code: $(document).ready(function() { $("#inProgress").click(function(e) { e.prevent ...

How can I adjust the width of a handle/thumb for NoUiSlider?

Looking to adjust the width of a NoUiSlider using CSS: .noUi-horizontal .noUi-handle { width:8px; height:25px; left: 0px; top: -8px; border: 0px solid #000000; border-radius: 0px; background: #000; cursor: default; box- ...

Converting JS carousel to TS for showcasing multiple items

I am currently working on integrating a bootstrap carousel into my Angular project and I need to convert my JavaScript file to a TypeScript file. As someone who is new to this, I'm unsure of the process for converting and implementing it in a .ts file ...

Troubleshooting Problems with Angular ng-include

I'm having trouble with including a file using ng-include. I've tried various variations, but it keeps returning a 404 error in the console. The directory structure is as follows: -App --Layout ---Partials ----Navigation.tpl.html(File) --Layout. ...

Choosing multiple items using ng-checked and ng-model in AngularJS

I am working with an Ionic application and encountering a minor issue, much like AngularJS. <ion-list class="list-inset subcategory" ng-repeat="item in shops"> <ion-checkbox class="item item-divider item-checkbox-right" ng-model="selectAll" ...

Assistance with Parallax Mouse Movement, Using JQuery, HTML, and CSS

As a newcomer to JQuery, I decided to experiment with creating a parallax background effect using the mousemove function. By utilizing event.pageX to generate a variable for adjusting the background position, I was able to achieve the desired result. Alth ...

Analyzing various PHP $_POST keywords for validation

Currently, I am facing an issue with a page where a script is supposed to check if the POST request contains a certain keyword when a link is called. However, no matter how I arrange the code, it does not seem to work as expected. <?PHP if($_POST[&apo ...

Promise Pending awaiting response from function

Could someone please explain why the code I have written below is returning a Promise pending value for the 'out' variable? var out = dbConn.connect().then(function (){ var request = new sql.Request(dbConn); request.input("termin ...

React app's setTimeout function fails to execute at the designated time specified

I have a function set up in my React app to handle user authentication and signup. The function is supposed to display an alert message saying "Account Created" upon successful signup, and then redirect the user to their profile page after a 1-second delay ...

current date validation in time picker

I am looking to implement JavaScript in a time field so that it does not allow the selection of current or past times for the current date. Additionally, I want to restrict the selection of times that are more than 4 hours ahead of the current time on th ...

instructions on sending the complete product quantity to the payment gateway

I am currently in the process of developing an ecommerce website using Django. When a user clicks on checkout, an HTML billing form appears prompting them to enter their address and email information. Previously, I successfully passed data such as email t ...

Why does the map function in JavaScript not allow for a function argument?

I encountered an issue while calling a function and passing an array of objects as the first argument, with the second argument being an object property of the first argument. Strangely, the map function was not accepting the second argument property. He ...