Reputation: 247
I have a litte issue with jQuery and .remove().
I have a td
and inside the td
I have a div
. When I click the td
I want to show the div
. When it is visible I can click the div
and after clicking it shall be removed.
I use the following javascript code:
$("td").click(function () {
$(".dragDiv").show();
});
$("#1").on("click", function () {
$(this).remove();
});
The removing works fine but after I call .remove() I cannot click the td
again. Nothing happens.
So what is wrong? Any help, appreciate it!!
Here is a working JSFIDDLE
Upvotes: 1
Views: 64
Reputation: 836
.remove()
literally deletes the div. What you should use is .hide()
or `.addClass( 'hide' );
Upvotes: 1
Reputation: 8858
It if your intention is to remove the element ( not hide it ), then you might wanna look into the .detach()
function. It would remove the element from the DOM temporarily and would be available as parameter value.
<table border="1">
<tr>
<td>test
<div id="1" class="dragDiv" style="height:100px; width:100px; display:none;">Test</div>
</td>
</tr>
</table>
var detachedEle;
$("td").click(function () {
if(detachedEle){
detachedEle.appendTo("tr td");
$(".dragDiv").hide();
detachedEle = null;
return;
}
$(".dragDiv").show();
});
$("#1").on("click", function () {
detachedEle = $(this).detach();
});
http://jsfiddle.net/kz1wmajL/2/
Upvotes: 1
Reputation: 21
You can use toggle
function, is better for reading code, and it's not complicated.
$('td').on('click', function() {
$('#1').toggle();
});
So, when you click
on td element (we are using on
because jQuery in future will deprecated short hand functions) you are asking if div#1
is showed or not. If not, hide that element.
Upvotes: 2
Reputation: 82277
The click event still works on the td after you click and then after you remove the div. The problem is that the div is removed, as in gone. So there is nothing to show, and as that element is gone there is no longer an element with an event there.
You probably wanted hide.
$("#1").on("click", function () {
$(this).hide();
});
Which simply sets display:none
to hide the element as opposed to permanently removing it.
This brings up another issue with your code though, which is that the div id=1 (ids are suggested to not start with numbers), is nested inside of the td element. So when the click event on the div occurs, it also then propagates out to the td. This means that once the div is shown, it will hide, and the event will propagate to the td and show it again preventing it from hiding. This may have been your original issue and why remove seemed to work.
In order to prevent that from happening, taking the event and calling event.stopPropagation()
is required. jQuery provides a shortcut of doing this (in addition with event.preventDefault()) by using return false
. That would look like this:
$("#1").on("click", function () {
$(this).hide();
return false;
});
Upvotes: 1