JSFiddle - React, Tailwind, and code Playground

by kacpaa

HTML

<div class="wrap" contenteditable="true">
    <p class="paragraph" id="parg1" onclick="createNewP('parg1');">  
        Press ENTER at the end of text - works!</p>
    <p class="paragraph" id="parg2" onclick="createNewP('parg2');">  
        Press ENTER in the middle of text - pargId is undefined!</p>
</div>
<div class="showPargId">
    newpargId:<br />
</div>

CSS

.wrap {
    width: 300px;
    height: auto;
    border: 1px solid #ff0000;
}
.paragraph {
    padding: 5px 10px;
    margin: 5px;
    background: #f0f0f0;
}
.paragraph.active {
    background: #e2e2e2;
}
.showPargId {
    width: 250px;
    position: fixed;
    top: 0;
    right: 0;
    border: 1px solid #00ff00;
}

JavaScript

function createNewP(pargId){ 
		$('.paragraph').removeClass('active');
		$('#' + pargId).addClass('active');
	}
	$(function(){
		$('.wrap').keyup(function(event) {
			var keycode = (event.keyCode ? event.keyCode : event.which);
			if (keycode == '13') { //create new <p> by pressing ENTER and renumber all <p> id's
				$('.paragraph').removeClass('active');
                var pSum = $('.paragraph').length;
				var i = 1;
			    if ( i < pSum ) {
					$('.paragraph').each(function(){
						$(this).attr('id' , 'parg' + i).attr("onclick" , "createNewP('parg" + i + "');");
					    i++;					
					});
				}
                var newpargId = window.getSelection().getRangeAt(0).endContainer.id; // id of paragraph where the cursor is placed
                $('#' + newpargId).addClass('active');
                $(function(){
                    $('.showPargId').append(newpargId + '<br />');                
                });
            } else { //do nothing
            }
		});
	});