This fiddle has an ADD button when you click it a Chat window is added. When there are more than 1 windows the message from one window is reflected across all the windows.
Say you have templates (in above case "Chat Window") which will repeat in DOM (i.e. append and removal will happen dynamically):
var html="<h1>Chat Window</h1> <div> <p></p>
<textarea rows='4' cols='50'> </textarea>
<input type='button' value='send'></div>";
The above template keeps repeating in the DOM i.e. when you click on the ADD button they are added inside:
<div id="chatApp">
</div>
I have an event handler which listens to the clicks in its innerHTML
:
var e = document.getElementById('chatApp');
e.addEventListener("click", function(event){
var chatWindows=document.getElementsByTagName('p');
if(event.target.value=="send"){
for(var i=0;i<chatWindows.length;++i){
chatWindows[i].innerHTML+= "<em>Chat window</em> {index} says: <b>"+ event.target.previousElementSibling.value+"</b><br/>";
}
event.target.previousElementSibling.value=null;
}
},false);
I have a couple of questions regarding it:
Say each of the template has an event with it and a respective handler so say I add this template 10 times in DOM (i.e. click add button in the fiddle 10 times) then I want to do event handling for each of them, possible ways:
- I append event handler to each of this template by giving the elements ID so I will have 10 event handlers which I feel is inefficient.
- I have one event handler on the parent of these chat windows and then use event.target to extract the particular values (like I have done in fiddle as shown above). But its side effect is that it also listens to click events other then on the SEND button.
Which strategy to use from above?
I want to know that SEND button of which chat window was pressed i.e. chat window of what index but Ii don't want to give ID to my templates then how do I do it? this will help me to display that message is coming from which chat window:
Chat window {index} says: " check the above fiddle
You want to recognize individual/particular group of elements in JavaScript DOM the known ways are:
- Provide ids to the elements dynamically before appending in DOM
- Provide class names
- Provide name attribute or any of your own attributes with some values
Among above which is most recommended? Or if there is any other way too, then please specify.
In the Fiddle provided above, when you add more than one Chat window and then you type a msg and press SEND, I select all elements with P tag and replace their innerHTML
to show message across all windows. As shown above in the handler and Fiddle.
But I know it is unsafe as, if there are other P tags in the page then they too will be screwed. Can you suggest the best strategy for this? How can I make sure that only P tags meant to display the chat message have their content changed?