The dynamically added links (classnames .divToggle and .removeDiv) only function if clicked twice the first time. What is preventing them from working properly right away?
$(document).ready(function(){
// adds click event to links.
$('a.divToggle').live('click', function(event) {
// Toggles the visibility of divs.
event.preventDefault;
$(this).toggle(function(){
$(this).next(".divToToggle").slideUp("slow");
$(this).text("show[+]");
},
function(){
$(this).next(".divToToggle").slideDown("slow");
$(this).text("hide[-]");
});
});
// used to remove divs from the page.
$("a.removeDiv").live("click", function(event) {
event.preventDefault;
$(this).parent().prev("a").prev("h2").remove();
$(this).parent().prev("a").remove();
$(this).parent().next("br").remove();
$(this).parent().remove();
});
// Used to add new divs to the page.
$(".addDiv").click(function(){
$("<h2>Title Area</h2><a href='#' class='divToggle'>hide[-]</a>"
+ "<div class='divToToggle'><a href='#' class='removeDiv'>Remove this div</a>"
+ "<ul><li>List element 1</li><li>List element 2</li>"
+ "<li>List element 3</li></ul></div><br />").insertBefore($(this));
});
});
$(...).toggledoesn’t do anything straight away. It just binds click events to the selected elements, so that in the future clicking causes one of the two functions to be called. So the first click does nothing but set up the toggle event handler. The second click actually calls the toggle event handler. (And also adds another toggle event handler! So the third click calls two toggle event handlers, and so on.).toggleis an alternative to.clickbinding, not something you would (normally) use inside a.clickevent handler.There is no ‘live’ version of
toggle, but you can write one yourself, eg.: