lewis
lewis

Reputation: 89

contentEditable span - preventDefault not working

Trying to stop enter from creating
when editing an editable span. I've tried searching but had no luck. Key presses are being detected fine, tested with alerts but just the preventDefault(); doesn't seem to work. I have searched and this seems to be the way that other people have prevented
from being created on enter.

$(document).on('focus', '.note>span', function(){ //edit notes
        var storedNote = $(this).text();
        var storedNoteIndex = notes.indexOf(storedNote);
        $(this).keyup(function (e) { //edit notes
            var newNote = $(this).text();
            if(newNote != "" && newNote != " " && newNote.charAt(0) != " ") {
                if (e.keyCode == 13 && e.shiftKey) {
                    alert('enter+shift');
                }
                else if(e.keyCode == 13){
                    e.preventDefault();
                }
                var newNote = $(this).text();
                notes.splice(storedNoteIndex, 1, newNote);
                chrome.storage.sync.set({'notes':notes});
            }
            else{
                notes.splice(storedNoteIndex, 1);
                chrome.storage.sync.set({'notes':notes});
            }
        });
    })

Here is the html to match the js:

        <div id="icon-wrapper">
            <div id="notes-icon" class="icons glyphicon glyphicon-list-alt"></div>
            <div id="bg-left" class="icons glyphicon glyphicon-chevron-left"></div>
            <div id="bg-right" class="icons glyphicon glyphicon-chevron-right"></div>
            <div id="refresh" class="icons glyphicon glyphicon-refresh"></div>
            <div id="pin" class="icons"></div>
        </div>

        <div id="time-wrapper">
            <div id="time"></div>
            <div id="date"></div>
        </div>

        <div id="input-wrapper">
            <input type="text" id="input-box" placeholder="Create a note">
        </div>

        <div id="notes-wrapper">
            <div class="note">
               <span contenteditable="true"></span>
               <div class="remove glyphicon glyphicon-remove"></div>
            </div>
        </div>

Upvotes: 1

Views: 1005

Answers (1)

CascadiaJS
CascadiaJS

Reputation: 2495

I believe forms are submitted on keydown so by the time your keyup event happens the form has already been submitted. Try changing it to

$(this).on('keydown keyup', function(e) {
  console.log(e);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body contenteditable>Change Me</body>

Upvotes: 2

Related Questions