Search code examples
javascriptjqueryfroala

JQuery, Froala - changing CSS on element where cursor is


Using Froala Rich Text Editor and want to change CSS for element where the blinking cursor is in the textbox. Have created a custom button I click to do this. The button works to initiate the callback function, but having trouble with JQuery code:

callback: function () {
    $(this).addClass('big');
}

This does not change anything. Using the code below changes all the 'P' elements rather than just the one where the cursor is on.

callback: function () {
  $('p').addClass('big');
}

How would I correct this code so when I move the mouse to click the button, only the element that has the blinking cursor on it changes the Class?

Thanks in advance.

EDIT: Inside the Froala texarea will be normal HTML, such as:

<p>one element</p>
<p>two element</p>
<p>three element</p>

WHAT I WANT TO HAPPEN: When your blinking cursor is on the last element, I click on the button to initiate the callback, and the CSS will be applied only to that last element and not the first two.


Solution

  • After a good amount of searching, found the most simple answer! On the Froala site, there is an option called "paragraphStyle.apply(value)". Can read it here.

    The callback is then very simple:

    callback: function () {
      this.paragraphStyle.apply('big')
    }
    

    "this." seems to track where the blinking cursor is and NOT where the mouse pointer is, which is what was desired.

    The completed Froala code to add a button with a book symbol, which is intended to format the paragraph to a css style called 'big' is shown below. In my case, big would be to colorize and make bigger, so the text stood out.

      //custom icon book quote button
      $.FroalaEditor.DefineIcon('quote', {NAME: 'book'});
      $.FroalaEditor.RegisterCommand('quote', {
        title: 'quote',
        focus: true,
        undo: true,
        refreshAfterCallback: true,
        callback: function () {
            this.paragraphStyle.apply('big')
        }
      });
    

    The Froala site doesn't give good examples, but just single line snippets that are hard to figure out for newbies. Hope this helps someone!