Is it possible to invoke a JavaScript function from within a CSS file?

Currently, I am focusing on developing responsive web design and looking for ways to avoid creating multiple versions of each page based on screen width variations. The struggle lies in managing font sizes effectively. While attempting to style them using vw units, I encountered issues with fonts appearing either too small on smaller screens or too large on larger screens.

To address this challenge, I devised my own font resizing function which accepts minimum and maximum values as parameters. For instance, setting min to 10px and max to 20px would result in a font size of 15px on a 1000px wide screen.

Unlike vw units, the unique aspect of my function is that it does not require the line to pass through (0,0). In essence, even on a hypothetical screen with 0px width, the calculated font size wouldn't necessarily be 0px (for example, it could be 4px in the case of 10-20 range).

I have shared a complete working example at the end of this passage.

The only setback I face is the inability to make the function work from a stylesheet. As an alternative workaround, I insert an iframe within the paragraph (though invisible) and leverage it to call the function on the parent element, i.e., the paragraph itself.

Although this method is functional, it lacks elegance. Ideally, I wish to define a few classes for better readability:

<style>

.fontSize_10_20 {
  font-size: setMinMaxFontSize(100vw, 10px, 20px);
}

</style>

Alternatively, I could employ the following approach:

<style>

.fontSize_10_20 { 
  font-size: calc(7px + 0.8vw);
}

</style>

However, styling the font size in the stylesheet tends to make the style.cssText unreadable. Even when attempting to display the content after calling a function, no output is generated at times. Upon running the code, you may notice that the final line displays "new element3 style.cssText is" without further information.

Another complication arises when trying to inspect the paragraph being written. Any modifications to the examined paragraph trigger the recreation of the iframe, repeated function calls, and continuous outputs until interrupting the cycle by clicking on the "stop loading" X button (specifically in Firefox).

Perhaps I am approaching this process from an incorrect angle. Instead of controlling JavaScript functions through HTML and CSS elements, maybe the conventional practice involves manipulating HTML and CSS via JavaScript functions. Could this be the more appropriate direction?

<!DOCTYPE html>
<html>

<head>
<style>

.up2 {
  font-size: 30px;
}
  
.up3 {
  font-size: 15px;
}
  
.up6 {
  font-size: calc(9px + 0.6vw);
}

</style>
</head>

<!--This triggers myFunction() upon page load or resize-->
<body onresize="reloadPage()">

<p id="up1" class="up2" style="font-size: 30px;">This represents the up1 paragraph showcasing the original font size defined by the up2 class.</p>

<p id="up2" class="up2" style="font-size: 30px;"><iframe style="display:none" onload="setFontSize(this.parentElement);"></iframe>Here is the up2 paragraph demonstrating the outcome of setFontSize(this.parentElement); currently adjusting the font size to 15px.</p>

<p id="up3" class="up3">This corresponds to the up3 paragraph describing element1.</p>

<p id="up4" class="up2" style="font-size: 30px;"><iframe style="display:none" onload="setMinMaxFontSize(this.parentElement, 10, 20);"></iframe>Displayed here is the up4 paragraph reflecting the result of setMinMaxFontSize(this.parentElement, min, max); presently adjusting the font size from 10px (on a 400px wide screen) to 20px (on a 1600px wide screen).</p>

<p id="up5" class="up3">This manifests as the up5 paragraph outlining element2.</p>

<p id="up6" class="up6"><iframe style="display:none" onload="showInfo(this.parentElement);"></iframe>This describes the up6 paragraph modified by font-size: calc(9px + 0.6vw) in the style sheet.</p>

<p id="up7" class="up6">Font information</p>

<script>

// Variable Declarations
var w = window.innerWidth;
var h = window.innerHeight;

var element1;
var element2;
var element3;
var min;
var max;
var fs; /*font size*/

function setFontSize(element1) {
  document.getElementById("up3").innerHTML += "<br>";
  document.getElementById("up3").innerHTML += "element1 is " + element1;
  document.getElementById("up3").innerHTML += "<br>";
  document.getElementById("up3").innerHTML += "element1 ID is " + element1.id;
  document.getElementById("up3").innerHTML += "<br>";
  document.getElementById("up3").innerHTML += "element1 style is " + element1.style;
  document.getElementById("up3").innerHTML += "<br>";
  document.getElementById("up3").innerHTML += "old element1 style.cssText is " + element1.style.cssText;
  element1.style.cssText = "font-size: 15px;";
  document.getElementById("up3").innerHTML += "<br>";
  document.getElementById("up3").innerHTML += "new element1 style.cssText is " + element1.style.cssText;
}

function setMinMaxFontSize(element2, min, max) {
  document.getElementById("up5").innerHTML += "<br>";
  document.getElementById("up5").innerHTML += "element2 is " + element2;
  document.getElementById("up5").innerHTML += "<br>";
  document.getElementById("up5").innerHTML += "element2 ID is " + element2.id;
  document.getElementById("up5").innerHTML += "<br>";
  document.getElementById("up5").innerHTML += "element2 style is " + element2.style;
  document.getElementById("up5").innerHTML += "<br>";
  document.getElementById("up5").innerHTML += "old element2 style.cssText is " + element2.style.cssText;
  document.getElementById("up5").innerHTML += "min =  " + min + " max = " + max;
  document.getElementById("up5").innerHTML += "<br>";
  fs = Math.round(((max * w) - (min * w) - (400 * max) + (1600 * min)) / 1200);
  document.getElementById("up5").innerHTML += "fs =  " + fs;
  element2.style.cssText = "font-size: " + fs + "px;";
  document.getElementById("up5").innerHTML += "<br>";
  document.getElementById("up5").innerHTML += "new element2 style.cssText is " + element2.style.cssText;
}

function showInfo(element3) {
  document.getElementById("up7").innerHTML += "<br>";
  document.getElementById("up7").innerHTML += "new element3 style.cssText is " + element3.style.cssText;
}

function reloadPage() {
  document.location.reload();
}

</script>

</body>
</html>

Answer №1

Implement the clamp function for adjusting font size: clamp(minimum, preferred, maximum); This allows you to specify the minimum and maximum font sizes, as well as the preferred size it should scale to.

h1 {
 font-size: clamp(2rem, 4vw + 1rem, 3rem);
}
<h1>Example using CSS clamp with a large h1 tag</h1>

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

Tips on adjusting the size of a Materialize CSS datepicker to perfectly fit within a card

Currently, I am developing a login page in html utilizing the materialize css framework. In my design, I created a card where Login and Register are displayed as tabs within the card. However, one of the forms includes a datepicker from materialize which ...

Try utilizing querySelectorAll() to target the second item in the list

As I delve into the world of HTML and JS, I came across the document.querySelectorAll() API. It allows me to target document.querySelectorAll('#example-container li:first-child'); to select the first child within a list with the ID 'exampl ...

"Enhance your online shopping experience with a React.js popup modal for

In the midst of developing a shopping cart, I find myself facing a challenge in making the modal pop up when clicking on the shopping cart icon. The semantic-ui documentation for modals has not provided clear instructions on achieving this functionality, s ...

Toggle the ASP validation control using JavaScript

I am looking to control the validation of my form using JavaScript. When a user clicks on a radio button in a list (yes or no), 2-3 rows are displayed. If the user selects "Yes," they must enter input into a textbox in one of those rows. To enforce this, ...

Implementing dynamic title rendering based on image in vue.js

This is the code I'm working with, aiming to display slider data. My goal is that if image[0] appears on the slider, it should return title [0]. I'm quite curious about what could be missing in my setup.code-image ...

Transforming the primary image to the thumbnail image when hovering over it with JSON objects

Currently, I am facing an issue with my single-page web application project that involves using jQuery, JSON Bootstrap. So far, I have successfully created a category page, product selection page, and item page. The problem arises on the item page where ...

Tips for altering the appearance of a dropped item using JQueryUI sortable

I have a straightforward website where I need to implement the ability to drag and drop styled DIV elements between two containers. Utilizing JQueryUI's sortable function, this behavior was successfully achieved with the following code: $("#active-co ...

extract element from a string with the help of jquery

When using AJAX to request HTML from a page, the process involves sending a request like this: function getHTML() { //set ajax call var options = { url: '/Controller', type: 'GET', d ...

Is there a way to prevent the context menu from appearing when tapping on an image on a mobile phone?

When attempting to move an image on the screen with a touch event, a popup appears in Chrome when pressing and holding the image. This popup usually includes options to save the image. Is there a way to disable this popup so I can freely move the image w ...

The stylesheet is linked, but no changes are taking effect

I've linked my template.php to style.css, and when I make changes in template.php, they show up fine. However, if I make changes in the stylesheet, nothing happens. What should I do? My website is not live; I'm working on it using a WAMP server. ...

Navigating the dynamic components in Vue using dynamic routing

I'm currently developing an application that helps users manage maintenance tasks. I have successfully created a component to display all the data stored in an array of objects. However, I am facing a challenge in redirecting users to different pages ...

Tips for locating a webpage element with Selenium?

click here for image driver=webdriver.Chrome() driver.get("https://compass.tinkoff.ru/") driver.maximize_window() driver.implicitly_wait(20) elem = driver.find_element(By.XPATH, '//button[text()="Open Full Map"]').click() tim ...

PHP Newsletter Creator

Recently, I created a unique php newsletter script in CakePHP that allows users to utilize an in-place editor to generate HTML content for newsletters. While the functionality works well, I have encountered some challenges with a new newsletter design that ...

Having trouble sharing content from my React next.js website on social media due to issues with open graph meta tags

I'm currently facing an issue with my Next.js application when trying to share content on Facebook and Twitter. I've made sure to include the necessary open graph meta tags in the document's head section and I'm using React Helmet to dy ...

React Native Function fails to return a value

Within my React Native app, there's a page called RepsPage that displays a scroll view using an array of IDs. I'm passing this array to a function named renderRep, attempting to create a view for each item in the array. However, the return statem ...

Ways to properly exit a function

What is the best way to pass the apiKey from the createUser function in User.ts to Test.ts in my specific scenario? User.ts interface User { url: string, name: string, } class User{ async createUser( user: User ):Promise<void> { le ...

Ways to eliminate header and footer data while printing a webpage

In my attempt to implement the code displayed below, I am encountering an issue where the header and footer continue to appear on the printed page. Despite numerous attempts with various CSS elements, I have been unsuccessful in removing the header and fo ...

CSS - Retain z-index until the transition is complete

Looking at this basic grid layout: <html> <head> <style> .grid { display: grid; grid-gap: 5px; grid-template-columns: repeat(13, 3fr); } .box { position: relat ...

Guide to Binding a JSON Property (Set or Array) to an Interactive Input Form in AngularJS

My input form is structured like this: <div> <div class="form-group"> <label for="inputQuestion" class="col-sm-2 control-label">Question</label> <div class="col-sm-10"> <input data-ng-model="publication.qu ...

Enhance webpage speed by enabling browser caching for embedded iframe CSS and Javascript files

Imagine having a file named main.html. Inside this file, there's an iframe that points to another file called sub.html. Additionally, there's a button on main.html that, when clicked, refreshes the content of sub.html. This sub.html file relies o ...