5
\$\begingroup\$

I am running through an app idea to help improve my knowledge of Javascript. The code attached performs the following:

  • Performs a regex on the input field to check it is value 0-9 If not,
  • it clears the field and shows a warning (Although this only seems to work on FF)

  • If it passes, updates the styles of the preview box on keyup

  • Adds the styles to a text area that the user can copy when selecting the button

I am looking for suggestions where I can improve in terms of writing more efficient code. Or pointers where I have possibly used the wrong method to perform a task. One area where I struggled was getting the value of the input field.

This is the first stage for this application as in the near future I plan to add in the ability modify each corner.

Feedback is welcomed

"use strict"

const masterField = document.getElementById('masterField');
const box = document.getElementById('box');
const warn = document.getElementById('warn');
const styleSheet = document.getElementById('styleSheet');

const WARNING_TIME = 2000;
var warningTimer;

masterField.addEventListener('keyup', updateCss);

function updateCss() {
    let inputVal = this.value;
    console.log(this.value);
    const expCase = /[0-9]/;

    if (expCase.test(inputVal)) {
        box.style.borderRadius = inputVal + 'px';
        styleSheet.textContent = 'border-radius: ' + inputVal + 'px';
    } else {
        this.value = '';
        showWarning();
    }
}

function hidewarning() {
    warn.classList.add('hide-warning');
}

function showWarning() {
    clearTimeout(warningTimer);
    warningTimer = setTimeout(hidewarning, WARNING_TIME);
    warn.classList.remove('hide-warning');
}

function copyStyles() {
    styleSheet.select();
    document.execCommand('copy');
}
#box {
            width: 300px;
            height: 175px;
            background-color: red;
        }

        #warn {
            display: block;
        }

        #warn.hide-warning {
            display: none;
        }
<div id="box"></div>
    <div>
        <label for="masterField">All Corners</label>
        <input id="masterField" class="radius-field" type="number">
        <span id="warn" class="hide-warning">Only numbers 0 - 9 are allowed</span>
    </div>

    <button onclick="copyStyles()">Copy Styles</button>

    <textarea id="styleSheet"></textarea>

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.