Combining the functionality of a number input with a resizable element using JS/CSS

As I develop a typography app, I have encountered a hurdle. The core code has been extracted into a pen, where there are various inputs and buttons in the user interface. This is why I am utilizing querySelectorAll('input[type="number"]') to target specific elements.

The objective is for the draggable element to dynamically update the text measure (line length) and BIND it to the number input by modifying the CSS property: --_typecsset-text-measure

Although I have implemented a resize observer that logs the draggable element to the console, I am currently feeling overwhelmed!

I have created a Pen: https://codepen.io/timpish/full/abMdBay

// font, leading, measure (line length) input resizers
        const numberInputs = document.querySelectorAll('input[type="number"]');
        function updateProp(event) {
            const uom = this.dataset.uom || '';
            document.documentElement.style.setProperty(`--_${this.name}`, this.value + uom);
        }
        numberInputs.forEach((input, index) => {
            input.addEventListener('input', updateProp);
        });

        // measure drag (.resizable) an update #measure
        let observeMeasure = new ResizeObserver(function (mutations) {
            const sizeInRem = mutations[0].contentRect.width / parseInt(getComputedStyle(document.documentElement).fontSize); document.documentElement.style.setProperty('--_typecsset-text-measure', sizeInRem + 'rem');
            const input = document.getElementById('measure');
            input.value = sizeInRem.toFixed(1);
        });
        let drag = document.querySelector(".resizable");
        observeMeasure.observe(drag);
/* globals */
*,
*::before,
*::after {
...
/*debugger */
* {
  outline: cornflowerblue dotted 0.5px;
}
<body class="center">

   ...
    
</body>

</html>

Answer №1

Update the CSS variable to match the width of the draggable element in pixels:

let observeMeasure = new ResizeObserver(function (mutations) {
  document.documentElement.style.setProperty(
    "--_typecsset-text-measure",
     mutations[0].contentRect.width + "px"
  );
});

Check out the demo below:

// font and lead resizers
const numberInputs = document.querySelectorAll('input[type="number"]');
//const measure = document.getElementById("measure");
//const labels = document.querySelectorAll('label');

function updateProp(event) {
  const uom = this.dataset.uom || "";
  document.documentElement.style.setProperty(
    `--_${this.name}`,
    this.value + uom
  );
  //const label = labels[Array.from(rangeSliders).indexOf(this)];
  //label.textContent = parseFloat(this.value).toFixed(3);
}
numberInputs.forEach((input, index) => {
  input.addEventListener("input", updateProp);
  //labels[index].textContent = parseFloat(input.value).toFixed(3);
});

// measure (line length)
let observeMeasure = new ResizeObserver(function (mutations) {
  document.documentElement.style.setProperty(
    "--_typecsset-text-measure",
     mutations[0].contentRect.width + "px"
  );
});
let drag = document.querySelector(".resizable");
observeMeasure.observe(drag);
/* globals */
*,
*::before,
*::after {
  box-sizing: border-box;
}

*:not(main p) {
  margin: 0;
  padding: 0;
}

... (Remaining code omitted for brevity) ...

</body>

</html>


To convert to rem and adjust the input accordingly:

let observeMeasure = new ResizeObserver(function (mutations) {
  const sizeInRem =
    mutations[0].contentRect.width /
    parseInt(getComputedStyle(document.documentElement).fontSize);

  document.documentElement.style.setProperty(
    '--_typecsset-text-measure',
    sizeInRem + 'rem'
  );

  const input = document.querySelector('input');
  input.value = sizeInRem;
});

You may need to modify the code to target specific inputs and elements as needed. This approach allows you to dynamically set the input value based on the draggable element's width.

Explore the live demo shown below:

// font and lead resizers
const numberInputs = document.querySelectorAll('input[type="number"]');
//const measure = document.getElementById("measure");
//const labels = document.querySelectorAll('label');

function updateProp(event) {
  const uom = this.dataset.uom || "";
  document.documentElement.style.setProperty(
    `--_${this.name}`,
    this.value + uom
  );
  //const label = labels[Array.from(rangeSliders).indexOf(this)];
…

… (Remaining code omitted for brevity) …

</body>

</html>

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

Ways to split JSON information into several pages?

I am currently facing an issue with my HTML code. It works perfectly fine for a small JSON file, displaying the data in an HTML table as expected. However, when I try to load a larger JSON file with around 15,000 rows of data, my page becomes unresponsiv ...

React - The ._id received by the Modal inside the map function is incorrect

My map is generating edit and delete buttons. The delete button requires confirmation, so I implemented a modal. When I use console.log(additive._id) on the first delete button, I get the correct ._id, but when I click the confirm button inside the modal, ...

Tips on reducing the size of a display:block

Beginner in programming. I'm having trouble with my signature design. The block in the background is sticking out on both sides. How can I adjust its size? <td> <a href="https://twitter.com/TEST" color="#252e42" class="sc-hzDkRC kpsoy ...

I am looking to incorporate a scroll feature into my form, as it is being displayed within a modal that is a separate component

Due to the size of my employee form exceeding the screen capacity, I need to incorporate a scroll property into my modal content. The form contains numerous fields that cannot be modified. Could you assist me in resolving the scrolling issue? Thank you! ...

Creating Tailored Breakpoints with Bootstrap for a Unique Design

Currently, I am delving into the world of front-end web design and taking advantage of Bootstrap for creating a responsive layout. However, I have noticed that Bootstrap only offers 5 predefined breakpoints. I am curious to know if there is a way to cust ...

The concept of CSS "preload" animation

When working with CSS, I encountered an issue with lag while loading 24 different mask images for a transition effect. To address this, I tried using a div called "preload" to cache the images and prevent lag on playback: <div class='trans' s ...

Passing an ID in Next.js without showing it in the URL

I am looking to transfer the product id from the category page to the product page without showing it in the URL Category.js <h2> <Link href={{ pathname: `/product/car/${title}`, query: { id: Item.id, }, }} as={`/p ...

Warning: An error occurred with undeclared variables... missing variable declaration

Hey everyone, I recently made a post but it seems like my explanation was not clear enough. So here's the issue - I have a products page with a URL structure like http:.......rest_id=3/area='Enfield'. I've been using a similar query on ...

Troubleshooting issue with jQuery/Javascript custom email validation not functioning as expected

I attempted to create my own email validation without using a plugin, but it's not functioning correctly. The code I wrote always returns false. Here is the snippet: var regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i; ...

Clients using Socket.io are known to establish connections with various sockets housed within the same server

Hello, I am currently managing a standard chatroom using socket.io but have encountered an issue that I am struggling to troubleshoot. The chatroom appears to be operating normally as clients can send and receive messages. However, there is an occasional ...

Struggling with creating an html file that is responsive on mobile devices

I am currently utilizing bootstrap 4 for the construction of a website. I have encountered an issue where my homepage does not display properly on handheld devices when using Google Chrome's device toggle toolbar. The homepage requires scrolling to vi ...

HTML - Navbar and Sidebar Only Partially Spanning the Width

Hey there! I am trying to make my sidebar and navbar full width, but for some reason, they are not extending all the way. Can anyone help me figure out why? Below is the code I'm using: I have included an image to illustrate the issue: https://i.sst ...

When working with AngularJS' ng-repeat in IE8, JQuery may encounter difficulties reading the innerHTML of a table row

I am attempting to implement a hover effect on table rows that changes the color when the mouse enters the row. I am utilizing JQuery and the on() method for this purpose, while the table is generated using AngularJS' ng-repeat. Everything works smoo ...

Ways to retrieve a webpage component that has multiple values within its class attribute

My dilemma lies in this HTML snippet: https://i.sstatic.net/E7zj0.png Within the code, there are two instances of <div class="sc-fjhmcy dbJOiq flight-information"></div>. I am trying to target these elements using their class attribu ...

Windows authentication login only appears in Chrome after opening the developer tools

My current issue involves a React app that needs to authenticate against a windows auth server. To achieve this, I'm hitting an endpoint to fetch user details with the credentials included in the header. As per my understanding, this should trigger th ...

Combining Bootstrap Vue: utilizing class names alongside HTML tags

(Bootstrap-Vue 2.0, Vue.js 2.5) Is it possible to combine traditional CSS Bootstrap 4 classes with Bootstrap-Vue? For example, can I use the following code snippet: <section id="introduction"> <b-container class="h-100"> & ...

Customize the bootstrap carousel to show multiple slides at the same time

I am looking to customize the bootstrap 3 carousel in order to show multiple slides at once. I understand that I could place several thumbnails in a single slide (div .item), but the issue is that the carousel will progress through them all at once, moving ...

Accessing an object from multiple React components

I am working with a MapboxMap React component that initializes and displays a Mapbox map (stored in the map const variable), and requires rendering of MapMarker components within it. This is the structure of the MapboxMap component: import React from &ap ...

ES6 import of CSS file results in string output instead of object

Too long; Didn't read I'm facing an issue where the css file I import into a typescript module resolves to a string instead of an object. Can someone help me understand why this is happening? For Instance // preview.ts import test from './ ...

Determining the browser width's pixel value to enhance responsiveness in design

Lately, I've been delving into the world of responsive design and trying to grasp the most effective strategies. From what I've gathered, focusing on content-driven breakpoints rather than device-specific ones is key. One thing that would greatl ...