I'm having a problem with a fun little project I'm doing. I currently have the option to create elements by clicking on a button, but I wanna be able to delete them again (They are all draggable, making it work like a whiteboard or post it board.). BUT! I am having trouble in the sense that, when I delete with my current function, it just takes whatever div is first, so if I choose the bottom post it, then it deletes the first one instead.
Here is my currently code:
function deleteDiv() {
$("#buttonDiv").parent().remove(); }
I have a div called "drag" which is the one I want to remove, that's why I am selecting the parent of #buttonDiv.
This is the HTML of the whole div that I want to delete.
<div class='drag resizable'>
<textarea class='resizable' type='text'></textarea>
<div id='buttonDiv'>
<button onClick='deleteDiv();'>Delete</button>
<br>
<button>Change color</button>
</div>
</div>
Would it also be possible to "hide" it instead of deleting? JQuery UI which I am using apparently likes to take up the whole width of the page on every div that has something to do with it, and I don't seem to be able to change it. So if hiding or changing the visibility to hidden would work.
The problem is because, presumably from the context of creating multiple buttons, you have lots of elements with the same id
of buttonDiv
. id
attributes must be unique. Use a class instead. You can then hook the event handler to that class and remove only the relevant elements from the DOM.
Also note that the on*
event attributes are very outdated. You should be using unobtrusive event handlers instead - and delegated ones at that if you're appending the elements dynamically. As you've included jQuery already, here's how you can do that:
$(document).on('click', '.buttonDiv .delete', function() {
$(this).closest('.drag.resizable').remove();
}).on('click', '.buttonDiv .color', function() {
$(this).closest('.drag.resizable').toggleClass('foo');
});;
.foo { background-color: #CCC; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='drag resizable'>
<textarea class='resizable' type='text'></textarea>
<div class='buttonDiv'>
<button class="delete">Delete</button><br>
<button class="color">Change color</button>
</div>
</div>
<div class='drag resizable'>
<textarea class='resizable' type='text'></textarea>
<div class='buttonDiv'>
<button class="delete">Delete</button><br>
<button class="color">Change color</button>
</div>
</div>