The program is triggered 1 time

When you click on a text block, textarea should appear in its place. Then, when the focus is lost, the tag changes to the original one. The code is triggered correctly only on the first click. Then nothing happens. There are no errors in the console.

var blockInfo;
var textareaBlock;

$("p, h1").click(
  function() {
    blockInfo = $(this);
    start();
  }
);

function start() {
  textareaBlock = $("<textarea>", {
    'class': blockInfo.attr("class"),
    'text': blockInfo.text(),
    "style": "width:" + blockInfo.css('width') + "; height:" + blockInfo.css('height') + ";"
  });
  textareaBlock.keydown(
    function(event) {
      if (event.key == 'Enter') {
        this.blur();
      }
    }
  );

  textareaBlock.blur(
    function() {
      end();
    }
  );

  blockInfo.replaceWith(textareaBlock);
  textareaBlock.focus();
  textareaBlock[0].selectionStart = textareaBlock.val().length;
}

function end() {
  blockInfo.text(textareaBlock.val());
  textareaBlock.replaceWith(blockInfo);
}

$("*").click(
  function() {
    console.log($(this).prop('nodeName'));
  }
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>


<body>
  <H1 class="Header" id="view">Lorem ipsum dolor sit.</H1>
  <p class="text" id="gert">Lorem ipsum dolor sit amet consectetur adipisicing elit. Quibusdam voluptas doloribus impedit voluptatem nisi! Beatae nulla deleniti fugiat id quibusdam laudantium, tempora ut, consequatur odio quis atque saepe nam sequi.</p>
  <p class="text" id="ger">Lorem ipsum, dolor sit amet consectetur adipisicing elit. Ex voluptate repellat aperiam harum. Veritatis repellendus voluptatibus voluptatem veniam eum provident! Alias perferendis quaerat nostrum? Inventore aliquid consequuntur quo laboriosam consequatur?</p>
  <script src="../logic.js"></script>
</body>

I noticed one thing. If you try to define the tag using .prop(‘nodeName’), then it will be determined only during the first run. After using the .replace With() function, the tag seems to disappear.

>Solution :

I think this is named function delegation

and the problem is in this section

$("p, h1").click(
  function() {
    blockInfo = $(this);
    start();
  }
);

You can delegate you click on document so document know that when you click on a specific tag you start to execute your function start

$(document).on('click', 'p, h1', function() {
    blockInfo = $(this);
    start();
  })

Leave a Reply