user9375528
user9375528

Reputation:

click method not selecting contenteditable element in plain JavaScript only

I want to click on a indirect trigger that will select the contenteditable element AKA the edit-container

I tried to create this kind of affect with the .click() method but that isn't working and its not giving me the result that I want so how can I do this? If I have to use another method to do this then I don't mind that.

This is my code

 document.addEventListener('DOMContentLoaded',function(){
  
  document.querySelector('#indirect-trigger').addEventListener('click',indirectTrigger);
  
  function indirectTrigger(){
    document.querySelector('#edit-container').click();
  }
  
});
 #edit-container{
  background-color: red;
  height: 100px;
  width: 100px;
  margin-bottom: 25px;
}

#indirect-trigger{
  background-color: gray;
  color: white;
  display: inline-block;
  padding: 5px;
  border-radius: 8px;
  
    -webkit-touch-callout: none; /* iOS Safari */
    -webkit-user-select: none; /* Safari */
     -khtml-user-select: none; /* Konqueror HTML */
       -moz-user-select: none; /* Firefox */
        -ms-user-select: none; /* Internet Explorer/Edge */
            user-select: none; /* Non-prefixed version, currently
                                  supported by Chrome and Opera */
  
  cursor: pointer;
}
<div id='edit-container' contenteditable='true'>
  
</div><!--<edit-container>-->

<p id='indirect-trigger'>Indirect trigger</p>

Upvotes: 1

Views: 40

Answers (1)

Barmar
Barmar

Reputation: 780787

Clicking on a content-editable element is used to set the focus there. Call focus() directly.

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

  document.querySelector('#indirect-trigger').addEventListener('click', indirectTrigger);

  function indirectTrigger() {
    document.querySelector('#edit-container').focus();
  }

});
#edit-container {
  background-color: red;
  height: 100px;
  width: 100px;
  margin-bottom: 25px;
}

#indirect-trigger {
  background-color: gray;
  color: white;
  display: inline-block;
  padding: 5px;
  border-radius: 8px;
  -webkit-touch-callout: none;
  /* iOS Safari */
  -webkit-user-select: none;
  /* Safari */
  -khtml-user-select: none;
  /* Konqueror HTML */
  -moz-user-select: none;
  /* Firefox */
  -ms-user-select: none;
  /* Internet Explorer/Edge */
  user-select: none;
  /* Non-prefixed version, currently
                                  supported by Chrome and Opera */
  cursor: pointer;
}
<div id='edit-container' contenteditable='true'>

</div>
<!--<edit-container>-->

<p id='indirect-trigger'>Indirect trigger</p>

Upvotes: 1

Related Questions