Javascript - How do I delete the DOM Element by cliking (This command) - javascript

I'm trying to delete a DOM element when I click the button.
I assumed that through 'this' I could achieve that easily.
However, 'this' doesn't work in this case.
I tried as below.
deletebutton.addEventListener('click',function()
{this.parentNode.parentNode.removeChild(this.parentNode.parentNode)})
How do I delete the element when I click the DOM Object?
How the page works is
I click the Add Movie button,
and the code reads through the informatin I input
and generates the cards according to the information I put,
Full code is in the following link.
https://codepen.io/jotnajoa/pen/mdVWddz
Thank you in advance

Try replacing your code for this
deletebutton.addEventListener("click", function () {
this.parentNode.remove();
});

Replace
deletebutton.addEventListener('click',function()
{this.parentNode.parentNode.removeChild(this.parentNode.parentNode)})
with
deletebutton.addEventListener('click',function()
{this.parentNode.parentNode.removeChild(this.parentNode)})

I will suggest using selectors rather than hardcoding the element. After that, you can specify it inside the listener that you want to remove that selected element.
The HTML code example:
<div class="cards">
<div id="card-1">
Your card goes here
</div>
</div>
Now as the card is added according to the after the loading of DOM, we will use the concept of Event Delegation to add event listeners. We will all event listener on the parent i.e. cards class, and check if it returns an id.
document.querySelector('.cards').addEventListener('click', event => {
if(event.target.id !== ''){
let storeID = event.target.id;
document.getElementById(storeID).remove();
}
}
This will remove the element from the DOM.

You can rather make use of the getElement or querySelector functions which will allow you to directly access the DOM element in question.

Related

Getting the current div id in content-editable div(specific)

I am recently working on one of my projects and currently i am stuck in some problem. Well, i have made a content editable div where the user can type its input. This content_editable div contains several div's in which user has to type. I tried document.activeElement but it gives me the content_editable div not the specific div and that the one with id second_div
I want to know how to find that specific div in content_editable div where user is type.For example:-
<div contenteditable="true" id="content_editable_div">
<div id="first_div">
I am the first div
</div>
<div id="second_div">
I am the second div and i want to know if the focus is on me
</div>
</div>
My Javascript:
window.onload = function () {
getDivwhohasfocusincontentedtiablediv(); // Something like that
};
I can use jquery but only at the last choice. I want to use only javascript for this purpose.Please help me to solve this, i didn't find solution for this all the net ( it could be that i haven't searched carefully). Thanks in advance
One possible solution is to attach an Event Listener on each inner div to listen for "focus" event. However I found out that not all elements emit "focus" events.
JQuery docs says:
The focus event is sent to an element when it gains focus. This event
is implicitly applicable to a limited set of elements, such as form
elements (input, select, etc.) and links (a href). In recent
browser versions, the event can be extended to include all element
types by explicitly setting the element's tabindex property. An
element can gain focus via keyboard commands, such as the Tab key, or
by mouse clicks on the element.
Adding tabindex attribute to each inner div will make it possible to listen to focus events.
Example at JSFiddle. Note: I wrote the code in JQuery but it can easily be written in JS.
You can find focus element in js using this,
var focused = document.activeElement;
What about this ,
<div contenteditable="true" id="content_editable_div">
<div id="first_div">
First Div
</div>
<div id="second_div">
Second Div
</div>
</div>
$(document).ready(function () {
function onMouseUp(e) {
console.log(this.id);
}
document.getElementById("first_div").addEventListener("mouseup", onMouseUp, false);
document.getElementById("second_div").addEventListener("mouseup", onMouseUp, false);
});
Demo Here JS FIDDLE
to get specific div
in Javascript you can use
document.getElementById("second_div")
or using Jquery
$("#second_div")
make sure your id was unique. This is the fastest way to find obj in any browser.
now for getting getting the active div. why not put specific event whenever the div was clicked or edited. like:
$("#second_div").click (function (){
//raise flag or something
currentDiv = "second_div";
})
function getCurrentDiv()
{
//do something in currentDiv
}
or try also explore other event such as, on mouse over, on mouse leave, etc.
i hope that might help. other wise, please elaborate your question if I missed something.

jQuery selector stores object? How to force it not to?

I have a dropdown ( < select > ) element and a container.
<div class='container' />
<script>
var dropdown = "<select class='multi-dropdown'> ... </select>"
</script>
When the value is changed, You get another of it.
It is logical, that this only happens when the document is ready ( the first one is made there ), and when the client modifies the last one.
$(document).ready( function(){
$('.container').append(dropdown);
$('.multi-dropdown:last').change(function(){
$('.container').append(dropdown);
});
});
Seems to be a working code for me. But what I noticed is, this is not working with the next appended dropdown element. Also if I change the original one, it fires.
My theory is, maybe jQuery already stored the original object as the :last , so it won't select a new element again even if I add new "last" ones.
or
The freshly created element ( this way ) isn't even selectable with jQuery.
Please argue in favor, or against, these are just my ideas.
The issue is that you're newly appended SELECT doesn't ever get an event bound to it. Just because you used the class to bind the change even for the initial SELECT, that doesn't automatically apply to every newly added element to the DOM.
Read up on delegated events, like for the on() function. Or use something like livequery.
Because you are binding the change handler to the :last element at page startup, if the last element changes dynamically it will not be changed accordingly; try and read deeply delegation using on method instead.
Like:
$(document).ready( function(){
$('.container').append(dropdown);
$('body').on('change','.multi-dropdown:last',function(){
$('.container').append(dropdown);
});
});

Possible to make div tags created using JQuery .html() clickable?

Hey guys bit of an odd questions but if I add div tags using JQuery .html() and give them an ID can I then use .click on them? The code might explain what I am trying to do. If not is there a possible work around?
I am trying to dynamically change my site without going to a new site.
So if I create Divs with an ID.
$("#funTime").click(function(){
var htmls = $("#content2").html();
$("#content2").html(htmls + " <div id='button1'>Create</div><div id='button2'>Annimate</div><div id='button4'>Clear</div>");
});
$("#button1").click(function(){create();});
$("#button2").click(function(){forannimation();});
$("#button3").click(function(){createOnMouse();});
It does not work but I do not know why.
Thanks in advance.
No you would need .on() to be able to handle dynamic added elements.
$('#content2').on('click', '#button1', function() {
// do your stuff
});
Also note that you can only add a single element with a certain id to the DOM. In your example everytime when the element with id #funTime is clicked you add en element with the same id.
You could improve your code by adding the button with some class instead of an id to the DOM or having a counter to produce unique ids. Or by preventing other clicks on #funTime by using .one() depending on your needs.
You can only assign an event handler to an element that exists. So the assignment of handlers should be done after the creation of the elements:
$("#funTime").click(function(){
var htmls = $("#content2").html();
$("#content2").html(htmls + " <div id='button1'>Create</div><div id='button2'>Annimate</div><div id='button4'>Clear</div>");
$("#button1").click(function(){create();});
$("#button2").click(function(){forannimation();});
$("#button3").click(function(){createOnMouse();});
});
However, several calls clicks on funtime will result in several elements with the same id, which results in an invalid document. Either prevent duplicate ids (e.g. implement a counter) or use classes.
You can actually create elements, bind events to them, all before they are on the screen. Backbone and others to it this way too.
var myNewDiv = $("<div ...>");
myNewDiv.click(function(){});
$(something).append(myNewDiv);
If you want to add events to things that are not yet on the page you must you use jQuery delegate.
You should use an on() listener for dynamically added elements
$("#content2").on('click','#button1',function(){create();});
This will add a listener to check for live added buttons in the selected container (#content2)
To do add thehandler as elements are created would need to add it within the click handler right after elements are appended....otherwise need to use delegation methods like on()
This would work:
$("#funTime").click(function(){
var htmls = $("#content2").html();
$("#content2").html(htmls + " <div id='button1'>Create</div><div id='button2'>Annimate</div><div id='button4'>Clear</div>");
/* elements exist can add event handlers*/
$("#button1").click(function(){create();});
$("#button2").click(function(){forannimation();});
$("#button3").click(function(){createOnMouse();});
});
More common current practice is to use delegation that allows for future elements and can be run on page load

Why is clone only cloning item once?

I'm new to jquery and I'm 100% sure I'm making a logical error but I can't see it. Basically as a user types a item in a field I want to clone the fields so they can continue adding more info. In the example I'm working on, I'm trying to create a list of siblings and their age.
Here's my code:
$(document).ready(function () {
$("input[name='age']").on('keydown', function() {
//is it the last input?
if (this == $("input[name='age']:last", this.form)[0]) {
//insert an empty clone of the current input
//$(this).after($(this).clone(true).val(''));
$('.family').clone().insertAfter(".family");
}
Here's the html:
<form>
<div class="family">
<input name="age" value=0> <input name="sibling" value="name?">
<hr />
</div>
</form>
If I use $(this).after($(this).clone(true).val('')); then it works but it only clones one field(the age one) so I tried to replace it with $('.family').clone().insertAfter(".family"); to clone the div class but it clones the fields only once. If I start typing my first siblings info then the second form will appear but if I start typing on the second form then nothing new appears after that.
Its just a guess but I think the if statement is not matching so the clone isn't being created(I'm new so this idea could be wrong). If this is the case then I'm confused because I'm cloning the same names of the input fields so input[name='age']:last should match the last age field..not sure.
Any idea what I'm doing wrong?
You're going to have to make your keydown event handler take note of future elements as well (i.e. the new <div> elements you're cloning and inserting).
Change
$("input[name='age']").on('keydown', function() {
to
$('form').on('keydown', 'input[name="age"]', function () {
i.e. (with some corrections / optimizations as well)
$('form').on('keydown', 'input[name="age"]:last-child', function() {
var _p = $(this).parent('.family');
// insert an empty clone of the current input's containing div
// ADDED : ... after the current input's containing div
_p.clone().insertAfter(_p);
}
Try this:
$("form").on('keydown',"input[name='age']:last", function() {
$('.family:last').clone().insertAfter(".family:last");
})
jsFiddle example
The issue is that you're trying to bind to elements that don't yet exist. To do that using .on(), you just need to bind to an element that exists in the dom:
Event handlers are bound only to the currently selected elements; they
must exist on the page at the time your code makes the call to .on().
To ensure the elements are present and can be selected, perform event
binding inside a document ready handler for elements that are in the
HTML markup on the page. If new HTML is being injected into the page,
select the elements and attach event handlers after the new HTML is
placed into the page. Or, use delegated events to attach an event
handler, as described next.
Then, you want to make sure you're only checking and cloning the last div and it's input. Note that when you're cloning the input fields, you will need to either change the names so you don't end up with a bunch of them that use the same name, or with a language like PHP you can append [] after the name and PHP will parse that into an array.

How to work with dynamically created fields?

I have web layout, which can contains several links on it. Those links are dynamically created, using AJAX functions. And it works ok.
But, I don't know how can I work with those "dynamically created links" (ie. how to call some JS or jQuery function if I click on them). I guess that browser can not recognize them, since there are created after page is loaded.
Is there some function, that can "re-render" my page and elements on it?
Tnx in adv on your help!
You can use the 2 following methods jQuery provides:
The first one, is the .live() method, and the other is the .delegate() method.
The usage of the first one is very simple:
$(document).ready(function() {
$("#dynamicElement").live("click", function() {
//do something
});
}
As you can see, the first argument is the event you want to bind, and the second is a function which handles the event. The way this works is not exactly like a "re-rendering". The common way to do this ( $("#dynamicElement").click(...) or $("#dynamicElement").bind("click", ...) ) works by attaching the event handler of a determinate event to the DOM Element when the DOM has properly loaded ($(document).ready(...) ). Now, obviously, this won't work with dynamically generated elements, because they're not present when the DOM first loads.
The way .live() works is, instead of attaching the vent handler to the DOM Element itself, it attaches it with the document element, taking advantage of the bubbling-up property of JS & DOM (When you click the dynamically generated element and no event handler is attached, it keeps looking to the top until it finds one).
Sounds pretty neat, right? But there's a little technical issue with this method, as I said, it attaches the event handler to the top of the DOM, so when you click the element, your browser has to transverse all over the DOM tree, until it finds the proper event handler. Process which is very inefficient, by the way. And here's where appears the .delegate() method.
Let's assume the following HTML estructure:
<html>
<head>
...
</head>
<body>
<div id="links-container">
<!-- Here's where the dynamically generated content will be -->
</div>
</body>
</html>
So, with the .delegate() method, instead of binding the event handler to the top of the DOM, you just could attach it to a parent DOM Element. A DOM Element you're sure it's going to be somewhere up of the dynamically generated content in the DOM Tree. The closer to them, the better this will work. So, this should do the magic:
$(document).ready(function() {
$("#links-container").delegate("#dynamicElement", "click", function() {
//do something
});
}
This was kind of a long answer, but I like to explain the theory behind it haha.
EDIT: You should correct your markup, it's invalid because: 1) The anchors does not allow the use of a value attribute, and 2) You can't have 2 or more tags with the same ID. Try this:
<a class="removeLineItem" id="delete-1">Delete</a>
<a class="removeLineItem" id="delete-2">Delete</a>
<a class="removeLineItem" id="delete-3">Delete</a>
And to determine which one of the anchors was clicked
$(document).ready(function() {
$("#links-container").delegate(".removeLineItem", "click", function() {
var anchorClicked = $(this).attr("id"),
valueClicked = anchorClicked.split("-")[1];
});
}
With that code, you will have stored in the anchorClicked variable the id of the link clicked, and in the valueClicked the number associated to the anchor.
In your page initialization code, you can set up handlers like this:
$(function() {
$('#myForm input.needsHandler').live('click', function(ev) {
// .. handle the click event
});
});
You just need to be able to identify the input elements by class or something.
How are these links dynamically created? You can use use the correct selector, given that they are using the same class name or resides in the same tag, etc.
consider the html form
<form>
<input type="text" id="id" name="id"/>
<input type="button" id="check" name="check value="check"/>
</form>
jquery script
$('#check).click(function() {
if($('#id).val() == '') {
alert('load the data!!!!);
}
});
here on clicking the button the script check the value of the textbox id to be null. if its null it will return an alert message....
i thin this is the solution you are looking for.....
have a nice day..
Noramlly , the browser process response HTML and add it to DOM tree , but sometimes , current defined events just not work , simply reinitialize the event when u call the ajax request ..
All you need to do to work with dynamically created elements is create identifiers you can locate them with. Try the following code in console of Firebug or the developer tools for Chrome or IE.
$(".everyonelovesstackoverflow").html('<a id="l1" href="http://www.google.com">google</a> <a id="l2" href="http://www.yahoo.com">yahoo</a>');
$("#l1").click(function(){alert("google");});
$("#l2").click(function(){alert("yahoo");});
You should now have two links where the ad normally is that were dynamically created, and than had an onclick handler added to bring up an alert (I didn't block default behaviour, so it will cause you to leave the page.)
jQuery's .live will allow you to automatically add handlers to newly created element.
If your links are coming in via AJAX, you can set the onclick attributes on the server. Just output the links into the AJAX like this:
Holy crap I'm a link
The return false makes sure the link doesn't reload the page.
Hope this helps!

Categories