2

Is there any way to fire an event when an object of a certain type is created?

I have an <div> element with editableContent="true" and when the user presses enter within the <div>, a new <div> is created that takes up just that line. Is it possible to have an event fire whenever a <div> object is created within my original <div> object?

I know one way to do this would to listen for keystrokes and on an 'enter' key being pressed, do a bunch of logic to figure out what to do, but this seems a lot less elegant - so it would be great if there was another way.

4 Answers 4

3

There are the a bunch of DOM Events and some of them will be supported by firefox for example. But I dont think that IE will support only one of them. Here is a complete list. First you can fire a custom event every time you create a new div, or you have a settimeout that checks every second if the count of you divs childnodes has changed.

Sign up to request clarification or add additional context in comments.

1 Comment

the DOMNodeInserted event should be what I need. luckily it's supported by everyone but IE.
1

You have a function that creates a div when you press enter. Why don't you just add a function call at the end of it.

function createDiv(){
  //create div 
  //append div
  divCreated();
}

1 Comment

I don't have a function that creates a div when you press enter, the div is created automatically (this is just the standard behavior of an object with contentEditable=true; )
1

There's no default callbacks for new elements creating. The first thing I have in mind - you can add an event listener for mouseUp event and check content delta (changed part) - if it looks like an element markup with regexp.

Comments

0

Everybody who looking for a way to react to changes in a DOM should take into consideration MutationObserver. It is a standard DOM4 feature currently implemented in all latest (even not all modern but latest!) browsers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.