Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript How to rewrite code?

ig21

Coder
Hello!
I've got task keyboard. I did it (but there are some bugs). But I'm interested in how can i rewrite javascript code to make it look more 'professional'
Thank You!


HTML:
<body >
    <div class="wrapper">
        
            <textarea name='' readonly></textarea>
            
            <div class="wrapper-keyboard">
                    <div class='letter'>`</div>
                    <div class='letter'>1</div>
                    <div class='letter'>2</div>
                    <div class='letter'>3</div>
                    <div class='letter'>4</div>
                    <div class='letter'>5</div>
                    <div class='letter'>6</div>
                    <div class='letter'>7</div>
                    <div class='letter'>8</div>
                    <div class='letter'>9</div>
                    <div class='letter'>0</div>
                    <div class='letter'>-</div>
                    <div class='letter'>=</div>
                    <div class='backspace '>Backspace</div>
                    <div class='tab '>Tab</div>
                    <div class='letter'>q</div>
                    <div class='letter'>w</div>
                    <div class='letter'>e</div>
                    <div class='letter'>r</div>
                    <div class='letter'>t</div>
                    <div class='letter'>y</div>
                    <div class='letter'>u</div>
                    <div class='letter'>i</div>
                    <div class='letter'>o</div>
                    <div class='letter'>p</div>
                    <div class='letter'>[</div>
                    <div class='letter'>]</div>
                    <div class='letter'>\</div>
                    <div class='CapsLock '>CapsLock</div>
                    <div class='letter'>a</div>
                    <div class='letter'>s</div>
                    <div class='letter'>d</div>
                    <div class='letter'>f</div>
                    <div class='letter'>g</div>
                    <div class='letter'>h</div>
                    <div class='letter'>j</div>
                    <div class='letter'>k</div>
                    <div class='letter'>l</div>
                    <div class='letter'>;</div>
                    <div class='letter'>'</div>
                    <div class='Enter '>Enter</div>
                    <div class='shiftLeft '>shift</div>
                    <div class='letter'>z</div>
                    <div class='letter'>x</div>
                    <div class='letter'>c</div>
                    <div class='letter'>v</div>
                    <div class='letter'>b</div>
                    <div class='letter'>n</div>
                    <div class='letter'>m</div>
                    <div class='letter'>,</div>
                    <div class='letter'>.</div>
                    <div class='letter'>/</div>
                    <div class='shiftRight '>shift</div>
                    <div class="space  "></div>
            </div>
        
    </div>


[CODE=javascript]let get=elem=>document.querySelectorAll(elem)

let divs = get('.letter')

let textarea = document.querySelector('textarea')
let tab = document.querySelector('.tab')
let capslock=document.querySelector('.CapsLock')
let shiftRight = document.querySelector('.shiftRight')
let shiftLeft = document.querySelector('.shiftLeft')
let Enter = document.querySelector('.Enter')
let backspace = document.querySelector('.backspace')
let space = document.querySelector('.space')

window.addEventListener('keydown', function (event) {
    
    if (event.keyCode == 20) {
        capslock.classList.toggle('pressed')
    }
    if (event.code == 'ShiftLeft') {
        shiftLeft.classList.add('pressed')
    }
    if (event.code == 'ShiftRight') {
        shiftRight.classList.add('pressed')
    }
    
      
    for (let div of divs) {
            if (event.key == div.textContent) {
            div.classList.add('pressed')
                textarea.value += div.textContent

        }
        if (capslock.classList.contains('pressed')||shiftRight.classList.contains('pressed')||shiftLeft.classList.contains('pressed')) {
            if (event.key.toLowerCase() == div.textContent) {
                div.classList.add('pressed')
                textarea.value += div.textContent.toUpperCase()
            }
        }
    }
  

    if (event.keyCode == 8) {
        textarea.value = textarea.value.slice(0, -1)
        backspace.classList.add('pressed')
    }
    if (event.keyCode == 9) {
        textarea.value += '\t'
        tab.classList.add('pressed')
    }
    if (event.keyCode == 13) {
        textarea.value += '\n'
        Enter.classList.add('pressed')
    }
    if (event.keyCode == 32) {
        textarea.value += ' '
        space.classList.add('pressed')
    }


})
window.addEventListener('keyup',function(event){
    
    for (let div of divs) {
        if (event.key == div.textContent) {
            div.classList.remove('pressed')
            
        }
        if (capslock.classList.contains('pressed')||shiftRight.classList.contains('pressed')||shiftLeft.classList.contains('pressed')) {
            
            div.classList.remove('pressed')
        }
    }
    if (event.code == 'ShiftLeft') {
        shiftLeft.classList.remove('pressed')
    }
    if (event.code == 'ShiftRight') {
        shiftRight.classList.remove('pressed')
    }
    if (event.keyCode == 9) {
        tab.classList.remove('pressed')
    }
    if (event.keyCode == 8) {
        backspace.classList.remove('pressed')
    }
    if (event.keyCode == 13) {
        Enter.classList.remove('pressed')
    }
    if (event.keyCode == 32) {
        space.classList.remove('pressed')
    }
})



<script src="script.js"></script>
</body>[/CODE]
 
Solution
D
Well, I've been having quite some fun with this, it being a perfect small project to refresh my JS and CSS ! Initially I only wanted to get rid of all the static <div>'s (by generating them dynamically) and change all the if..else's in the handlers to switch statements. But I ended up almost completely rewriting the whole thing ! Here is a list of things small and big I did. Others might not agree with all of them.

-) Added semicolons wherever missing (they are mandatory, officially !)

-) Change bracketing to my preferred style, which I think is called "Horstmann style". I feel deeply uncomfortable when not all of the curly braces are lined up. This process also greatly helps me to understand someone else's code.

-) Removed the "let"...
I love optimizing code ! Can you post the complete page, including any css files needed ?
And what are the "some bugs" you mention ?
 
I love optimizing code ! Can you post the complete page, including any css files needed ?
And what are the "some bugs" you mention ?
Thank You!
I've got folowing bug: when I press both shift keys, the pressed style of one of the shift key does not disappear.

I send all the code:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
    
</head>
<body >
    <div class="wrapper">
        
            <textarea name='' readonly></textarea>
            
            <div class="wrapper-keyboard">
                    <div class='letter'>`</div>
                    <div class='letter'>1</div>
                    <div class='letter'>2</div>
                    <div class='letter'>3</div>
                    <div class='letter'>4</div>
                    <div class='letter'>5</div>
                    <div class='letter'>6</div>
                    <div class='letter'>7</div>
                    <div class='letter'>8</div>
                    <div class='letter'>9</div>
                    <div class='letter'>0</div>
                    <div class='letter'>-</div>
                    <div class='letter'>=</div>
                    <div class='backspace '>Backspace</div>
                    <div class='tab '>Tab</div>
                    <div class='letter'>q</div>
                    <div class='letter'>w</div>
                    <div class='letter'>e</div>
                    <div class='letter'>r</div>
                    <div class='letter'>t</div>
                    <div class='letter'>y</div>
                    <div class='letter'>u</div>
                    <div class='letter'>i</div>
                    <div class='letter'>o</div>
                    <div class='letter'>p</div>
                    <div class='letter'>[</div>
                    <div class='letter'>]</div>
                    <div class='letter'>\</div>
                    <div class='CapsLock '>CapsLock</div>
                    <div class='letter'>a</div>
                    <div class='letter'>s</div>
                    <div class='letter'>d</div>
                    <div class='letter'>f</div>
                    <div class='letter'>g</div>
                    <div class='letter'>h</div>
                    <div class='letter'>j</div>
                    <div class='letter'>k</div>
                    <div class='letter'>l</div>
                    <div class='letter'>;</div>
                    <div class='letter'>'</div>
                    <div class='Enter '>Enter</div>
                    <div class='shiftLeft '>shift</div>
                    <div class='letter'>z</div>
                    <div class='letter'>x</div>
                    <div class='letter'>c</div>
                    <div class='letter'>v</div>
                    <div class='letter'>b</div>
                    <div class='letter'>n</div>
                    <div class='letter'>m</div>
                    <div class='letter'>,</div>
                    <div class='letter'>.</div>
                    <div class='letter'>/</div>
                    <div class='shiftRight '>shift</div>
                    <div class="space  "></div>
            </div>
        
    </div>

    <script>
        let get=elem=>document.querySelectorAll(elem)

let divs = get('.letter')

let textarea = document.querySelector('textarea')
let tab = document.querySelector('.tab')
let capslock=document.querySelector('.CapsLock')
let shiftRight = document.querySelector('.shiftRight')
let shiftLeft = document.querySelector('.shiftLeft')
let Enter = document.querySelector('.Enter')
let backspace = document.querySelector('.backspace')
let space = document.querySelector('.space')

window.addEventListener('keydown', function (event) {
    
    if (event.keyCode == 20) {
        capslock.classList.toggle('pressed')
    }
    if (event.code == 'ShiftLeft') {
        shiftLeft.classList.add('pressed')
    }
    if (event.code == 'ShiftRight') {
        shiftRight.classList.add('pressed')
    }
    
      
    for (let div of divs) {
            if (event.key == div.textContent) {
            div.classList.add('pressed')
                textarea.value += div.textContent

        }
        if (capslock.classList.contains('pressed')||shiftRight.classList.contains('pressed')||shiftLeft.classList.contains('pressed')) {
            if (event.key.toLowerCase() == div.textContent) {
                div.classList.add('pressed')
                textarea.value += div.textContent.toUpperCase()
            }
        }
    }
  

    if (event.keyCode == 8) {
        textarea.value = textarea.value.slice(0, -1)
        backspace.classList.add('pressed')
    }
    if (event.keyCode == 9) {
        textarea.value += '\t'
        tab.classList.add('pressed')
    }
    if (event.keyCode == 13) {
        textarea.value += '\n'
        Enter.classList.add('pressed')
    }
    if (event.keyCode == 32) {
        textarea.value += ' '
        space.classList.add('pressed')
    }


})
window.addEventListener('keyup',function(event){
    
    for (let div of divs) {
        if (event.key == div.textContent) {
            div.classList.remove('pressed')
            
        }
        if (capslock.classList.contains('pressed')||shiftRight.classList.contains('pressed')||shiftLeft.classList.contains('pressed')) {
            
            div.classList.remove('pressed')
        }
    }
    if (event.code == 'ShiftLeft') {
        shiftLeft.classList.remove('pressed')
    }
    if (event.code == 'ShiftRight') {
        shiftRight.classList.remove('pressed')
    }
    if (event.keyCode == 9) {
        tab.classList.remove('pressed')
    }
    if (event.keyCode == 8) {
        backspace.classList.remove('pressed')
    }
    if (event.keyCode == 13) {
        Enter.classList.remove('pressed')
    }
    if (event.keyCode == 32) {
        space.classList.remove('pressed')
    }
})
    </script>
</body>
</html>

CSS:
body{
    background-color: lightgray;
    height: 100vh;
    overflow: hidden;
}
.wrapper{
    background-color:white;
    width: 500px;
    margin: 0 auto;
    background-color:inherit;
}
textarea:active,textarea:focus {
    outline:none;
}

     textarea{
         box-sizing: border-box;
         padding: 5px;
         width: 496px;
         margin: 0 auto;
         height: 100px;
         border:none;
         border-radius: 10px;
         resize: none;
         display: block;
         margin-bottom: 10px;
     }
     .wrapper-keyboard{
         display: flex;
         flex-wrap: wrap;
         justify-content: center;
        
     }
     .letter{
         width: 30px;
     }
 .wrapper-keyboard div{
    margin: 2px;
    background-color: white;
    
    text-align: center;
    line-height: 30px;
    height: 30px;
    border-radius: 5px;
    font-size: 10px;
    }
  
    div.backspace{
        width: 54px;
    }
    div.tab{
        width: 54px;
    }
    div.CapsLock{
        width: 58px;
    }
    div.Enter{
        width: 60px
    }
    div.shiftLeft,div.shiftRight{
        width: 76px;
    }
    
    .space{
        height: 30px;
        background-color: white;
        border-radius: 5px;
        width: 500px;
       }
    .pressed{
        background-color: darkgray !important;
        color: white;
    }
    .big{
        text-transform: capitalize;
    }
 
Ok ! This is a nice little project to debug and streamline the code. I'll be back 😎
As for the "bug", I am not sure pressing both shift keys at the same time is any different from pressing just one of them. But will have to investigate further, seeing as there are separate keycodes for the two.
 
Ok ! This is a nice little project to debug and streamline the code. I'll be back 😎
As for the "bug", I am not sure pressing both shift keys at the same time is any different from pressing just one of them. But will have to investigate further, seeing as there are separate keycodes for the two.
Thanks a lot!
 
Well, I've been having quite some fun with this, it being a perfect small project to refresh my JS and CSS ! Initially I only wanted to get rid of all the static <div>'s (by generating them dynamically) and change all the if..else's in the handlers to switch statements. But I ended up almost completely rewriting the whole thing ! Here is a list of things small and big I did. Others might not agree with all of them.

-) Added semicolons wherever missing (they are mandatory, officially !)

-) Change bracketing to my preferred style, which I think is called "Horstmann style". I feel deeply uncomfortable when not all of the curly braces are lined up. This process also greatly helps me to understand someone else's code.

-) Removed the "let" commands. Being old-fashioned, I did not see the point of them.

-) Moved all the scripting (except for two function calls) to the <head> section, to keep the HTML small and tidy.

-) Dynamically write all the key div's to the page rather than declaring them. Input is a string with all the captions. With the exception of ShiftLeft, ShiftRight, and Space, the class names are now equal to the key captions.

-) Changed keycap font resp. weight to Consolas resp. bold, which looks a lot better.

-) Totally reworked the event handlers, removing the use of keyCode (which is deprecated).

-) Added a number of small utility functions

-) Tried to prevent the Tab from bubbling up to the browser, by adding event.stopPropagation(); Unfortunately it does not seem to work well.

-) Removed stuff that was unnecessary after (or even before) my modifications.

I think this is as good as I can make it. The Tab remains troublesome, and the left and right shift keys remain odd bedfellows. Although they no longer remain pressed and you no longer get double keys (lower and uppercase at the same keypress). I did not change much to the CSS, except to make the class names same as the key captions. I did change "letter" to "char" though, because digits are not letters. While my version of the HTML has considerably more lines than yours, it has considerably less characters ! I call that airy programming 😀

So, I hope you can use some or all of my ideas.

HTML:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mock Keyboard</title>
    <link rel="stylesheet" href="style.css">

    <script>

    //----------------------------------------------------------------------
    // Define the keyboard contents.
    // The layout is determined by the sizes of the div's in ths CSS.
    //----------------------------------------------------------------------

    var keynames
        ="` 1 2 3 4 5 6 7 8 9 0 - = Backspace "
        + "Tab q w e r t y u i o p [ ] \\ "
        + "CapsLock a s d f g h j k l ; ' Enter "
        + "ShiftLeft z x c v b n m , . / ShiftRight "
        + "Space";


    //----------------------------------------------------------------------
    // Display the key with the specified caption
    //----------------------------------------------------------------------

    function displayKey(caption)
    {
        var clazz;

        if ( caption.length == 1 )
        {
            clazz = "char";
        }
        else
        if ( caption.substring(0, 5) == "Shift" )
        {
            clazz = caption;
            caption = "Shift";
        }
        else
        if ( caption == "Space" )
        {
            clazz = "Space";
            caption = " ";
        }
        else
        {
            clazz = caption;
        }

        document.writeln("<div class='" + clazz + "'>" + caption + "</div>");
    }


    //----------------------------------------------------------------------
    // Display the entire keyboard.
    //----------------------------------------------------------------------

    function displayKeyboard()
    {
        keynames.split(" ").forEach(displayKey);
    }


    //----------------------------------------------------------------------
    // Add key listeners
    //----------------------------------------------------------------------

    function addKeyListeners()
    {
        window.addEventListener('keydown', keyDownListener);
        window.addEventListener('keyup',   keyUpListener)
    }


    //----------------------------------------------------------------------
    // Find the div that corresponds to the key event's code and key.
    //----------------------------------------------------------------------

    function findDiv (key, code)
    {
        if ( code == 'Space' )
        {
            return document.querySelector('.Space');
        }

        if ( key.length == 1 )
        {
            for (div of document.querySelectorAll('.char'))
            if ( div.textContent == key.toLowerCase() )
            {
                return div;
            }
        }
        else
        {
            return document.querySelector('.' + code);
        }

        return null;
    }


    //----------------------------------------------------------------------
    // Set a key div to the pressed or not pressed state.
    //----------------------------------------------------------------------

    function setPressed (div, pressed)
    {
        if (pressed)
        {
            div.classList.add('pressed');
        }
        else
        {
            div.classList.remove('pressed');
        }
    }


    //----------------------------------------------------------------------
    // Toggle a key div between pressed and not pressed state.
    // Cuurently used only for CapsLock.
    //----------------------------------------------------------------------

    function togglePressed (div)
    {
        div.classList.toggle('pressed');
    }


    //----------------------------------------------------------------------
    // The keyDownListener
    //----------------------------------------------------------------------

    function keyDownListener (event)
    {
        div = findDiv(event.key, event.code);
        textarea = document.querySelector('textarea');

        switch (event.code)
        {
            case 'Backspace':
                setPressed(div, 1);
                textarea.value = textarea.value.slice(0, -1);
                break;

            case 'Tab':
                setPressed(div, 1);
                textarea.value += '\t';
                event.stopPropagation();    // Meh, doesn't work...
                break;

            case 'CapsLock':
                togglePressed(div);
                break;

            case 'Enter':
                setPressed(div, 1);
                textarea.value += '\n';
                break;

            case 'ShiftLeft':
            case 'ShiftRight':
                setPressed(div, 1);
                break;

            case 'Space':
                setPressed(div, 1);
                textarea.value += ' ';
                break;

            default:
                setPressed(div, 1);
                textarea.value += event.key;
        }
    }


    //----------------------------------------------------------------------
    // The keyUpListener
    //----------------------------------------------------------------------

    function keyUpListener (event)
    {
        div = findDiv(event.key, event.code);

        switch ( event.code )
        {
            case 'Backspace':
                setPressed(div, 0);
                break;

            case 'Tab':
                setPressed(div, 0);
                event.stopPropagation();    // Meh, doesn't work...
                break;

            case 'CapsLock':
                break;

            case 'Enter':
                setPressed(div, 0);
                break;

            case 'ShiftLeft':
            case 'ShiftRight':
                setPressed(findDiv('', 'ShiftLeft') , 0);
                setPressed(findDiv('', 'ShiftRight'), 0);
                break;

            case 'Space':
                setPressed(div, 0);
                break;

            default:
                setPressed(div, 0);
                break;
        }
    }
    </script>
</head>

<body >
    <div class="wrapper">
        <textarea name='' readonly></textarea>
        <div class="wrapper-keyboard">
        <script>
            displayKeyboard();
            addKeyListeners();
        </script>
        </div>
    </div>
</body>

</html>

CSS:
body
{
    background-color: lightgray;
    overflow: hidden;
}

.wrapper
{
    background-color: white;
    width:            500px;
    margin:           0 auto;
    background-color: inherit;
}

textarea:active,
textarea:focus
{
    outline:          none;
}

textarea
{
    box-sizing:       border-box;
    padding:          5px;
    width:            496px;
    margin:           0 auto;
    height:           100px;
    border:           none;
    border-radius:    10px;
    resize:           none;
    display:          block;
    margin-bottom:    10px;
}

.wrapper-keyboard
{
    display:          flex;
    flex-wrap:        wrap;
    justify-content:  center;
}

.wrapper-keyboard div
{
    margin:           2px;
    background-color: white;
    text-align:       center;
    line-height:      30px;
    height:           30px;
    border-radius:    5px;
    font-size:        10px;
    font-family:      Consolas;
    font-weight:      bold;
}

.pressed
{
    background-color: darkgray !important;
    color:            white;
}
    

 
.char
{
    width:            30px;
}

.Backspace
{
    width:            54px;
}

.Tab
{
    width:            54px;
}

.CapsLock
{
     width:           58px;
}

.Enter
{
    width:            60px
}

.ShiftLeft,
.ShiftRight
{
    width:            76px;
}
    
.Space
{
    width:            200px;
}
 
Solution
Wow,great job, i really like how you did this task as it allows me to look at this task from another angle and thus improve my programming skills. Also thank you for the detailed explanation of each of your steps. I really like your approach 'airy programming' as my version is really very cumbersome.
I did not know how to solve the problem with tab as well, but still thank you for your work!
 
Wow,great job, i really like how you did this task as it allows me to look at this task from another angle and thus improve my programming skills. Also thank you for the detailed explanation of each of your steps. I really like your approach 'airy programming' as my version is really very cumbersome.
I did not know how to solve the problem with tab as well, but still thank you for your work!
Glad to help, it was useful for me too. I find that being meticulous in matters of spelling, layout, naming, indentation, etc... helps me greatly to understand and gain control of code. My code may not be the most compact or clever, but I believe it is optimally transparent and can't get any easier to understand and modify.
 
Last edited by a moderator:

New Threads

Latest posts

Buy us a coffee!

Back
Top Bottom