How to dynamically adjust font size using Javascript

Is there a way to adjust the font size of the left-column using JavaScript?

<div id="left-column">
    <a href="">1</a><br>
    <a href="">2</a><br>
    <a href="">3</a><br>
    <a href="">4</a><br>
    <a href="">5</a><br>
    <a href="">6</a><br>
</div>

This is my current attempt:

<script>
    document.write(document.body.clientWidth);
    if (document.body.clientWidth > 400)
         document.getElementById('left-column').style.letterSpacing="0px";              
    }
 </script>

Answer №1

To apply styling properties using JavaScript, use the same property name as you would in CSS, but without the hyphen and with camel casing, against the 'style' object. For example, instead of using 'font-size' in CSS, you would use 'fontSize' when applying it to elements via JavaScript. One thing to keep in mind is that certain properties like 'font-size' are inherited, meaning they will affect descendant elements as well. So, you can apply the style to a parent element instead of each individual child element to avoid affecting unnecessary elements. However, if you do apply it to a parent element, all descendant elements will be affected and you may need to reset the styles on elements you don't want to change.

document.querySelector("button").addEventListener("click", function(){

  var iw = window.innerWidth;
  
  document.getElementById("outputArea").textContent = "The usable width of the page is: " + iw + "px";

  if(iw > 400){
    
    var a = document.querySelectorAll("#leftcol > a");
  
    for(var i = 0; i < a.length; i++){
      a[i].style.fontSize = "3em"; 
    }
    
  }

});
<div id="outputArea"></div>
<div id="leftcol">
  <a href="">1</a><br>
  <a href="">2</a><br>
  <a href="">3</a><br>
  <a href="">4</a><br>
  <a href="">5</a><br>
  <a href="">6</a><br>
</div>
<button>Click Me</button>

Furthermore, it's recommended to avoid using 'document.write()' in JavaScript unless you are dynamically creating an entire DOM structure. Instead, consider injecting content into existing DOM elements for better practice.

Answer №2

To adjust font size based on page width, it is recommended to use CSS instead of javascript. Media queries are a great way to achieve this. For more information, you can refer to this page: https://www.w3schools.com/css/css3_mediaqueries_ex.asp

Here's an example:

#leftcol{
    font-size: 20px;
}

@media screen and (max-width: 400px) {
    #leftcol {
        font-size: 12px;
    }
}

In the above scenario, the default font size is set to 20px. If the page width is 400 pixels or less, the font size will be reduced to 12px.

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

Facing an issue with sending data in AJAX Post request to Django View

I have been trying to send data from the frontend to the backend of my website using AJAX. Below is the post request view in my Django views: def post(self, request): id_ = request.GET.get('teacherID', None) print(id_) args = {} ...

Tips for implementing Bootstrap pagination in VueJS 2

Here is how my website appears: Jobs.vue: <div id="jobs" class="job-item" v-for="(item, index) in showJobs" :key="index" > <router-link ...

Oops! Looks like there was a hiccup in processing your query. Please review the MySQL manual for guidance on fixing the SQL syntax error

After being pressured to update to MySQL 5 and PHP 5 due to my service provider no longer supporting older versions, I encountered a problem with my MySQL search. The query was functioning properly on the server, but when included in the user's listin ...

The iteration of an ajax POST handler, looping endlessly

Attempting to implement a basic ajax submit handler for modifying a form as part of a lesson on CSRF vulnerabilities, but encountering an issue with the page looping. Below is the code snippet being worked on, inspired by http://api.jquery.com/jQuery.post/ ...

Several JavaScript functions require a confirmation dialog to be displayed before they can be executed

There are three separate javascript/jquery functions in my code, all triggered by a button click. One function posts to a form handler, another creates a new tab, and the third one sends new data into the tab through an ajax call. These functions are inter ...

Sophisticated method in JavaScript to conceal and reveal div elements

My knowledge of front-end web development is strongest in HTML and CSS, but when it comes to JavaScript, I feel like there must be a more efficient way to achieve the functionality I want. On my website, I have a set of <li> items that, when clicked ...

Why is Selectpicker failing to display JSON data with vue js?

After running $('.selectpicker').selectpicker('refresh'); in the console, I noticed that it is loading. Where exactly should I insert this code? This is my HTML code: <form action="" class="form-inline" onsubmit="return false;" me ...

Invoke a JavaScript function from a dynamically inserted nested function

My primary application loads JavaScript files based on the page being visited: var MainApp = (function() { function loadPage(folder, template) { $.getScript('scripts/' + template + '.js') .done(function() { ...

cusel.js encountered an error due to attempting to use the 'in' operator to search for 'using' within the specified error

I attempted to implement the cusel.js (styled selects) library on my select elements, but unfortunately it's not functioning as expected. The selects change visually, however when I try to scroll through the options using jscrollpane, an error that I ...

Activate the checkbox if the value matches the data retrieved from the database using JavaScript

Hello everyone, I could really use some assistance. I am new to JavaScript and currently have a checkbox with a random value. My goal is to automatically check the checkbox when the data from the database matches the value in the checkbox. This is how my ...

Angular does not display a loading indicator in the header

When handling service calls, I have implemented a loading indicator to provide feedback to the user. However, it appears that this indicator is not effectively preventing users from interacting with header items before the loading process is complete. My ...

Error: Unable to retrieve the specified ID

One unique aspect of my backbonejs app is the model structure: var Store = Backbone.Model.extend({ urlRoot: "/stores/" + this.id }); This is complemented by a router setup like so: var StoreRouter = Backbone.Router.extend({ routes: { 's ...

Customizing the active state of a Dropdown Item in Bootstrap version 4.5

Recently, I've embarked on the journey of creating my own theme using a combination of SASS and Bootstrap. However, I've hit a little snag when it comes to achieving the desired active appearance for a dropdown item within a navbar. To be complet ...

Error with YouTube API in Internet Explorer 8: Video not found

While using the iframe youtube api to handle video, everything runs smoothly on Chrome and Firefox. However, when trying to implement it on Internet Explorer 8, an error saying 'video' is undefined pops up. Any suggestions on how to resolve this ...

Is the position relative malfunctioning when using display table-cell?

I have designed a horizontal menu consisting of buttons that I want to resize in width so that together they occupy 100% of the menu container. I need them to function like TD elements inside a TABLE. Here is the code snippet I have developed: <div id ...

React Timer App: The setInterval function is being reset after each render operation

I'm currently working on a straightforward timer application that will begin counting seconds when a button is clicked. To implement this, I am utilizing react hooks. import React, { useState } from 'react' function Timer() { const [sec ...

Difficulty Aligning Header Elements - Combining Navigation and Logo on the Same Line

I am currently facing an issue with positioning a logo and navigation links within a <header> element. When I apply the CSS property text-align:center;, the logo aligns to the center on one line while the navigation links appear on another line direc ...

Retrieve the latest information and update the database with just one ajax request

I am attempting to update a row in the database and retrieve the updated row one at a time using an AJAX call. JavaScript inside the ready function $("button[name='teacher_lock_exam']").on(ace.click_event, function () { var current_exams_id ...

Could someone provide clarification on this particular line of Apex code for me?

I'm completely new to Oracle Apex and I could use some guidance in understanding the code snippet I came across in a tutorial about app creation. After digging around, I suspect it might be JavaScript, but I'm not entirely certain. The scenario ...

Concealing a CSS element within another one

Hey there, I've got a little issue I could use some help with. So, I've created a progress bar for my portfolio website, but there's a small hiccup. The #ability div is causing some trouble - when I adjust the width property to 1%-3%, it e ...