Search code examples
javascripthtmlwysiwyg

HTML simulate textarea with div container


I want to create a little WYSIWYG editor. The idea: First I want to add the feature to write and change text. So I add an onClick and onKeyBoard Listener to my div container. When I click the div I set a varaible named "focused" to true. When an key event is fired I check if focused is true. In case focus is false nothing will happen else the new charater will be added on the cursor's position.

My questions: Is this the right way? I tried to check how other editors handle the text input but I wasnt able to get it.

In case this is the right way - how can I simulate a blinking cursor. In a textarea the cursor will blink but who about a div container? The cursor will hide immideatly after clicking.


Solution

  • I'm assuming you're doing this for fun/practice. If you're doing this for professional reason then I HIGHLY recommend you don't reinvent the wheel and use something like Ckeditor, tinyMCE or YUI.

    That being said; you need to look into event handling. Specifically, for your question about focusing, you can look here. The way you're describing (setting a variable to true/false) seems like it is going to just run into problems. If you use the standard events attribute (as opposed to setting a "focus" variable onclick) you should define functions to execute and then set them as an onfocus/onblur attribute for the element you're listening to.

    That is if you aren't using a javacript library like mootools, jquery, extJS, etc. If you're using one of those they likely have their own way of handling events, so you should search their respective documentation for how to implement event handlers.

    One more note; you really should be using a textarea over a div (unless I'm misunderstanding and you just want to do something when a user focuses on your div). If you're using javascript only to completely reinvent a texteditor from a div; then your web page will not function without javascript. If you keep the text area; users could still type information in and you still get the benefit of grabbing text contents for form submits but using divs means your web page will just be rendered useless without javascript.