toddash
toddash

Reputation: 187

select currently focused contenteditable div using jquery

hi i would like to select the parent div of currently placed cursor in a contenteditable div.

the process is, there are multiple contenteditable div in a page. i'd like to select the div which the caret/ cursor is currently positioned. so that using jquery i could change the css.

following is my html code of the div:

     <button id="changer">change color</button>
     <div id="container">
          <div class="section" contenteditable="true">
          <p>this is my editable paragraph</p>
      </div>

      <div class="section" contenteditable="true">
         <p>this is my editable paragraph 2</p>
      </div>
    </div>

following is my jquery code so far:-

        $('#changer').click(function(){
             document.activeElement.css({'background':'black'}); 
        });

but this gives me the error :- Uncaught TypeError: undefined is not a function

edit:-

the process is when the user clicks a button a color palette lightbox will appear. on click of any of the color on the color palette. the jquery is going to select the currently focused contenteditable div. and change the css. i want to know how to select the currently focused contenteditable div using jquery.

Upvotes: 2

Views: 2147

Answers (2)

ali404
ali404

Reputation: 1153

So the code below console logs the text inside the contenteditable div which is focused. if you write $(this) inside the event handler it will reference the currently div focused

$('[contenteditable="true"]').focus(function(){
  console.log($(this).text()); // for example, do whatever you please here
  // you said you want to find the parent div of the element focused
  var $parent = $(this).parent();
  // now $parent is a reference of the parent div of the focused element
});

The tricky thing is that when the user clicks the button, the contenteditable is not focused anymore. so let's make a variable where we store our last focused contenteditable div , and when the user clicks a button, the changes will be made on that very variable.

like so :

var lastFocused;

$('[contenteditable="true"]').focus(function(){
  lastFocused = $(this);
});

$('#changer').on('click', function(){
  console.log(lastFocused);
  lastFocused.css('background-color', 'red');
})

see codepen : here

Upvotes: 5

Alfred Huang
Alfred Huang

Reputation: 18235

So I think what you are trapped is how to get the div[contenteditable] which was focused.

The idea is to store the item when it was trigger by a focus event.

$(function() {
    var $focus_item = null;
    $('[contenteditable]').focus(function() {
        $focus_item = $(this);
    });
    $('#changer').click(function(){
         $focus_item.css({'background':'black'}); 
    });
});

Upvotes: 3

Related Questions