Event handler fired when add a event listener

  addeventlistener, dom, events, javascript

Extract page.html:

<div id="46" class="cont-text-profile">
<span class="data"># March 4, 2021, 5:17 p.m.</span>
<p class="text">Tutto ok!!!!!!!111111111222222233333334444444</p>
<div class="edit"><a id="edit-46" href="javascript:void(0)" class="edit_post">Edit</a></div>
<div id="like" class="like"><a id="ilike-46" href="javascript:void(0)"  class="like_post ">Like it?</a> (<span id="nlike-46">1</span>  like)</div>
<div class="spacing"></div>
</div>  

Extract script.js

document.addEventListener('DOMContentLoaded', function() {

    const edit=document.getElementsByClassName('edit_post');
    if (edit != null){
        for (const ele of edit)
        {ele.addEventListener('click',edit_post)}
    }

});

function edit_post(e){
    const id=parseInt(e.target.id.split('-')[1]);
    const parent=document.getElementById(id);
    if (parent != null){
      const p=parent.querySelector('p')
      const form=document.createElement('TEXTAREA');
      form.id='d_textarea_'+id;
      form.maxLength=260;
      form.cols=52;
      form.rows=4;
      form.required;
      form.classList.add('d_textarea');
      form.value=p.innerHTML;
      parent.replaceChild(form,p);
      const all_edit_a=document.getElementsByClassName('edit_post');
      for (let a of all_edit_a){
        if (a.id == e.target.id){
          e.target.innerHTML='Save';
          e.target.addEventListener('click', save_post);
          continue;}
        a.removeEventListener('click',edit_post)
        a.addEventListener('click', alert)
      }
      
    }
  }

  function save_post(e){
    const id=parseInt(e.target.id.split('-')[1]);
    const textarea = document.getElementById('d_textarea_'+id);
    const edited_post = textarea.value;
    if (edited_post == ''){
      alert('The post cannot be empty, please write something.');
      return false
    }
    fetch('/modify/' + id, {
      method : 'PUT',
      headers: {'Content-Type': 'text/html'},
      body : edited_post
      })
        .then(response =>{
          if (response.status != 200)
          {
            alert('Error. Please refresh page e retry. Err : '  + response.status);
          }else{
            const all_edit_a=document.getElementsByClassName('edit_post');
            for (let a of all_edit_a){
              if (a.id == e.target.id){
                a.removeEventListener('click', save_post);
                a.addEventListener('click',edit_post);
                a.innerHTML='Edit';
                continue;}
              a.removeEventListener('click', alert);
              a.addEventListener('click',edit_post);            
            }
            const parent=document.getElementById(id);
            const p=document.createElement('p');
            p.classList.add('text');
            p.innerHTML=edited_post;
            parent.replaceChild(p,textarea);
  
          }
        })
        .catch(error => {console.log('Error while processing the request:' , error);
    })
  }

  function alert(){
    alert('Save changes before leave please.');
  }

The script works but it trown this error:

scripts.js:46 Uncaught TypeError: Cannot read property ‘innerHTML’ of null
at HTMLAnchorElement.edit_post

when i click on "Save" (and hence the handler again edit_post)
It seems the the handler "edit_post" will fired after a.addEventListener(‘click’,edit_post);

Source: Ask Javascript Questions

LEAVE A COMMENT