The font remains the same despite the <Div style=> tag

I have a script that loads external HTML files, but I am facing an issue with changing the font to Arial. The script is as follows:

   <script type="text/javascript">
        $(document).ready(function(){
           $("#page1").click(function(){
            $('#result').load('140314F00604.htm');
             //alert("Thanks for visiting!");
           });

           $("#page2").click(function(){
            $('#result').load('140314F029.htm');
             //alert("Thanks for visiting!");
           });

           $("#page3").click(function(){
            $('#result').load('140221F193.htm');
             //alert("Thanks for visiting!");
           });
         });
    </script>
      <table cellpadding="0" cellspacing="0" style="width: 100%; border-size: 1px">
        <tr>
          <td><a id="page1" href="#">About</a></td>
          <td><a id="page2" href="#">Community</a></td>
          <td><a id="page3" href="#">Sponsor</a></td>
        </tr>
      </table>

    <div id="result" style="color:red; font-style:italic; font-family:Arial; font-size:12px;"></div>

While the script changes the color, italicizes and adjusts size correctly, it struggles to change the font to Arial.

The imported HTML generated by software cannot be edited in the program itself. Hence, I aim to load it and modify its formatting.

The initial script worked seamlessly. However, switching the font from courier messes up the spacing due to text alignment using spaces in the imported HTML. Is there a way to rectify this issue?

function applyPreFont(){
var oldHtml = $('#result pre').html();
$('#result pre').html('<div class="pre-div">' + oldHtml + '</div>');
}

function LoadExternalContent(pagename){
$('#result').load(pagename, function(data) {
    applyPreFont();
    // do other stuff
});
}

$(document).ready(function(){
$("#page1").click(function(){
    LoadExternalContent('140314F00604.htm');
});

$("#page2").click(function(){
    LoadExternalContent('140314F029.htm');
});

$("#page3").click(function(){
    LoadExternalContent('140221F193.htm');
});
});

Original html file

The output from the script

Answer №1

pre does not handle CSS font styling well. The properties of fonts will be ignored, even if they are inherited from parent elements. Applying them to the parent element will not have any effect.

UPDATE 1
Caution:
pre elements use a monospace font (where all glyphs have the same fixed width), making it suitable for tabular data. Most fonts like Arial, Helvetica, Verdana, and Times New Roman are not monospace, meaning each glyph has its own size based on width. As a result, applying a non-monospace font will disrupt the tabular structure. Learn more on MDN Docs.

To style the content within a pre element, you need to target a descendant element.

If you're using jQuery in a dynamic HTML environment, you can wrap the content of pre in a new div with jQuery and apply CSS styles to this new element:

var oldHtml = $('#result pre').html();
$('#result pre').html('<div class="pre-div">' + oldHtml + '</div>');

This will result in something like:

<pre>
    <div class="pre-div">
        Boland Athletics ...
        ...
    </div>
</pre>

I recommend structuring your code as follows:

function applyPreFont(){
    var oldHtml = $('#result pre').html();
    $('#result pre').html('<div class="pre-div">' + oldHtml + '</div>');
}

function LoadExternalContent(pagename){
    $('#result').load(pagename, function(data) {
        applyPreFont();
        // perform other tasks
    });
}

$(document).ready(function(){
    $("#page1").click(function(){
        LoadExternalContent('140314F00604.htm');
    });

    $("#page2").click(function(){
        LoadExternalContent('140314F029.htm');
    });

    $("#page3").click(function(){
        LoadExternalContent('140221F193.htm');
    });
});

CSS:

.pre-div {
    font-family: arial;
    font-weight: bold;
}

View an example in fiddle

** Tested only in Chrome.

Answer №2

The $.get function in jQuery offers another option that allows for a callback function to be included. According to the documentation, "If a 'complete' callback is provided, it will run after data has been retrieved and HTML content has been inserted."

I recommend updating your get functions to resemble this structure:

$('#output').load('140221G253.htm', function(){
   //alert("Welcome!");
   //add styling here
});

Answer №3

UPDATE:

To ensure proper alignment (since PRE uses a Mono Space font), consider downloading the Monospace version of Arial (Download Here, make sure to click the actual download on the right side of the font).

The implementation, based on the accepted answer without removing the pre tag, would be through CSS:

@font-face
{
font-family: arialMono;
src: url(/directory/locationOfFontFile.ttf);
}

.pre-div{
font-family: arialMono;
}

Once the font is added to a stylesheet, you can implement it using your JQuery function like this:

 function applyPreFont(){
    var oldHtml = $('#result pre').html();
    $('#result pre').html("")
    $("<div />",{
    "class": "pre-div",
    html: oldHtml,
    css: {
    "font-family": "arialMono"
    }
    }).appendTo($('#result pre'));
    $('#result pre').html('<div class="pre-div">' + oldHtml + '</div>');
    }

The issue lies with the <pre> tags (Preformatted Text). Styling may be problematic due to the nature of these tags. Consider removing the Pre tags using JQuery for smoother rendering:

$('#result').load('140221F193.htm', function(){
   $("#result pre").contents().unwrap()
});

This should successfully remove the PRE tags and render the HTML correctly :)

JSFidde Here

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

Update: When a variable changes during onUploadProgress in Vue.js, the DOM is not re

Having a bit of an issue here. I'm working on an app where users can upload images using axios. In order to enhance the user experience, I'm trying to implement a loading bar. Here's what it looks like: <div class="loadingbox" :style="{ ...

executing several asynchronous requests upon loading the webpage in a single-page application

As a newcomer to front end development, I have a question about page rendering performance. In my single page application, I have utilized multiple Ajax calls to retrieve data for manipulation in order to enhance performance. However, I am concerned that ...

The operation of 'val' is not supported by HTMLInputElement

While working with a table row, I am iterating through each cell. Inside every cell lies a text box containing some value that I need to store in an array. function dothing() { var tds = $('#'+selected+' td'); var submi ...

Incorporate the key as a prop within a Child Component in a React application

I am trying to display a list of elements in React, where the key of each element is used as an index in front of the item. However, when I try to access props.key, it just returns undefined. Does anyone have any suggestions on how to access the key proper ...

Discover the key technique to modify the status of a different component in React

I'm working on developing a popup window component. Here is the initial code for the popup component: The component takes in two props, activity (which can be set to true or false) and content (a view component that will be displayed inside the popu ...

Ways to run evaluations on 'private' functions within an angular service using Karma and Jasmine

In my Angular application, I have a BracketService that consists of various functions for comparing weights and creating brackets based on weight groups. The service includes functions like compareByWeight, filterWeightGroup, and createBracketsByWeightGrou ...

How can I position text next to an input within a <td> element in a vertical arrangement?

Below is the HTML code: <fieldset><legend>Callout Report</legend> <table> <tr><td>Start Time</td><td> <input type="text" id="startTimeUI" autocomplete="off" /> </td></tr> <tr><td& ...

Ways to dynamically assign value to a checkbox using jquery

var sites = sites_str.split(","); $.each(sites,function(i,j) { $('.check').append("<input type=checkbox name=site_name value=sites[i]>"+sites[i] +"</br>" }) I am facing an issue when trying to retrieve the values of selected check ...

Deleting a tag from a Flask document

Styling my form has been a challenge with Flask, particularly in regards to the picture field. I'm struggling to remove the "No file chosen" text and style the upload button using CSS, despite incorporating Bootstrap into my file. When hovering over ...

What is the best way to toggle dropdown menu items using jQuery?

Upon clicking on an li, the dropdown menu associated with it slides down. If another adjacent li is clicked, its drop down menu will slide down while the previous one slides back up. However, if I click on the same li to open and close it, the drop down m ...

What is the best way to transfer JavaScript variable values to Drupal PHP variables?

I need assistance with passing a JavaScript variable to a Drupal PHP variable and displaying its value. Here is the code I currently have: $form['title'] = array( '#type' => 'select', '#title' => t('t ...

Attempting to modify information in vue.js

I have been facing an issue with overriding data in the App.vue component. It seems that every time I try to update the data in my main.js file, the component still takes the default data. I am working with webpack as well. App.vue <template> & ...

Mysterious error arises in Internet Explorer versions 7 and 8: An expected colon is missing

One of our websites is encountering a puzzling JS error in Internet Explorer. The console displays the following message: ':' expected javascript:false, Line 1 Character 24 When attempting to trace the source of the error, a notification appear ...

Unable to append item to document object model

Within my component, I have a snippet of code: isLoaded($event) { console.log($event); this.visible = $event; console.log(this.visible); this.onClick(); } onClick() { this.listImage = this.imageService.getImage(); let span = docu ...

Material-UI: The `paperFullWidth` key passed to the classes prop is not supported within the WithStyles(ForwardRef(Dialog)) component

When using Material-UI, please note that the key paperFullWidth provided to the classes prop is not implemented in WithStyles(ForwardRef(Dialog)). You are only able to override one of the following: root. <Dialog classes={{ paperFullWid ...

After attempting to refresh the webpage with the F5 key, I noticed that the jQuery progress bar was not functioning properly. Additionally, the webpage failed to display any

Trying to implement a web loading bar using jQuery on my website was initially successful, but I encountered an issue when reloading the page with F5. The progress bar would not work and the webpage displayed only a white background. Below is the code snip ...

What is the best way to apply changes to every class in JavaScript?

Check out this HTML and CSS code sample! body{ font-family: Verdana, Geneva, sans-serif; } .box{ width: 140px; height: 140px; background-color: red; display: none; position:relative; margin-left: auto; margin-right: auto; } .bold{ font ...

"Successfully rendering the map on the initial load, but encountering an error of 'cannot map undefined'

Having trouble displaying data retrieved from an API. Initially, the movie titles are shown without any issues. However, upon refreshing the page, an error message stating "cannot map undefined" appears. Here is the code snippet: const [media, set ...

A completely css-based interpretation of google images

I am in the process of trying to recreate the layout found in Google Photos and stumbled upon this intriguing page https://github.com/xieranmaya/blog/issues/6 . I am particularly interested in the final result of the project, which can be viewed here: . U ...

Effortlessly initiate the consecutive playback on SoundCloud

I'm currently working on my music blog and I'm looking for some guidance in implementing a feature where the widgets start playing one after the other. Specifically, I have both SoundCloud and YouTube widgets, but I would like to focus on achievi ...