javascriptpythondjangowebsocketdjango-channels

Space is not sliced from my text in front-end


So here is my front-end JS code for the keyHandler:

let snippet = document.getElementById('snippet'); 
let remaining = document.getElementById('remaining'); 
let typed = document.getElementById('typed');
let result = document.getElementById('result');

const keydownHandler = (event) => {
    let key = event.key;

    if (key.length === 1 && /[a-z .]/i.test(key) ) {
        if (key === snippet.innerText[typed.innerText.length]) {
            if(key == " "){            
                console.log('its space !!!!!!');
                typed.innerText +=  ' ';
            }else{
                typed.innerText +=  key.toLowerCase();
            }
            remaining.innerText = snippet.innerText.slice(typed.innerText.length);
            result.innerText = '';
        } else {
            result.innerText = 'Incorrect key pressed!';
        }
    }

    let message = JSON.stringify({
        'snippet_text':snippet.innerText,
        'typed_text': typed.innerText,
        'remaining_text': remaining.innerText,
    });

    if (socket.readyState === WebSocket.OPEN) {
        console.log('Sending message:', message);
        socket.send(message);
    }
};

The problem is that when I type the ' ' (spacebar) , it does not get removed from my remaining text on the front-end.

Here is the back-end consumer:

def receive(self, text_data):
    data = json.loads(text_data)
    typed_text = data.get('typed_text', '').lower()
    snippet_text = data.get('snippet_text', '').lower()
    
    is_correct = typed_text == snippet_text
    if is_correct:
        self.current_snippet_index += 1
        self.player_score += 1
        self.send(json.dumps({
            'is_correct': is_correct,
            'player_score': self.player_score,
        }))
        self.send_new_snippet() #send new snippet with full details
    else:
        remaining_text = snippet_text[len(typed_text):]
        self.send(json.dumps({
            'snippet_text': snippet_text,
            'typed_text': typed_text,
            'remaining_text': remaining_text,
        }))

Here is an image of the results: results


Solution

  • Since you are using .innerText and not .value, I'll assume that you are using div or span for your elements. In which case, your problem is that .innerText returns the rendered text content from the DOM (which removes trailing whitespace).

    The fix is simply to use .innerHTML in place of .innerText. Or of course, you could use input elements and their .value properties.

    Run the code snippet to see it working:

    let snippet = document.getElementById('snippet');
    let remaining = document.getElementById('remaining');
    let typed = document.getElementById('typed');
    let result = document.getElementById('result');
    
    
    const keydownHandler = (event) => {
        let key = event.key;
    
        if (key.length === 1 && /[a-z .]/i.test(key) ) {
            if (key === snippet.innerHTML[typed.innerHTML.length]) {
                if(key == " "){
                    console.log('its space !!!!!!');
                    typed.innerHTML +=  ' ';
                }else{
                    typed.innerHTML +=  key.toLowerCase();
                }
                remaining.innerHTML = snippet.innerHTML.slice(typed.innerHTML.length);
                result.innerHTML = '';
            } else {
                result.innerHTML = 'Incorrect key pressed!';
            }
        }
    
        let message = JSON.stringify({
            'snippet_text':snippet.innerHTML,
            'typed_text': typed.innerHTML,
            'remaining_text': remaining.innerHTML,
        });
    
        // if (socket.readyState === WebSocket.OPEN) {
        //     console.log('Sending message:', message);
        //     socket.send(message);
        // }
    
        console.log( message )
    };
    
    document.addEventListener( "keydown", keydownHandler )
    label {
      display: block;
      margin-bottom: 1rem;
    }
    
    label span {
      display:  inline-block;
      border: solid 1px orange;
      height: 1.2rem;
      width: 15rem;
    }
            <label for="snippet">Snippet <span id="snippet">Test for spaces</span> </label>
            <label for="remaining">Remaining <span id="remaining"></span> </label>
            <label for="typed">Typed <span id="typed" contentEditable="true"></span> </label>
            <label for="result">Result <span id="result"></span> </label>