I have a div container. If the user clicks on this div container, then this is replaced with an input box.
If the user click on anywhere else on the page other than the input box, then I want the previous div to be shown again.
This is what I have managed to do until now. This works fine only once. This is the javascript code:
$(document).ready(function() {
$(".new-section").click(function(event) {
$(this).replaceWith('<div class="span8 offset1 create-section"><input type="text" placeholder="Enter the title of the section"></div>');
event.stopPropagation();
});
$(".create-section").click(function(event) {
event.stopPropagation();
});
$(document).click(function(event) {
$(".create-section").replaceWith('<div class="span8 offset1 new-section"><p>Click to add a new section</p></div>');
});
});
This is the HTML code:
<div class="span8 offset1 new-section">
<p>
Click to add a new section
</p>
</div>
After replacing the input with the div, further clicks on the div do not bring the input box again. It seems like the click event is only trigerred once. Basically what I want is:
1. User clicks on div
2. Div replaced with input
3. User clicks outside input
4. Input replaced with div
5. User clicks on div again and the input box comes back.
The cycle repeats. As of now, I have managed to get this working only once. Any idea what I am doing wrong?
EDIT: I do not want to allow the to be shown again, if the user clicks on the . Only if the user clicks on anywhere else in the web page (other than the ), the should be shown again. In other words, a toggle between the and the elements.
As you are creating the element dynamically you should delegate the event:
However toggling visibility of the elements is more efficient than replacing them.
http://jsfiddle.net/34wHG/
Note that I have used focus and blur events, you can also create a button which generates the section and hide the div element when button is clicked.