Add Event listener using Jquery - javascript

I am creating a clone of a div, but unfortunately i am not able to add event listener to cloned div.
I tried using clone(true,true) but still did not get it running.
Can some one help me out with it please
JS fiddle for clone
Clicking image next to And, adds a new div
Code i tried for adding event listener
$("#add").on('click',function () {
$("#cont").clone(true, true).appendTo(".container");
});

First you should change your cont id to a class as multiple ids are bad and won't work properly.
Second, use jQuery's first method to grab the first in the returned jQuery nodelist that you get from grabbing all the cont classes: $('.cont') and then clone the node. You have to grab only the first one or you'll end up adding multiples of the div back on to the page.
$(".cont").first().clone(true, true).appendTo(".container");
Third, change the delete id to a class.
Fourth, because you're adding to the DOM you need to use event delegation on the parent node in order to catch the events properly. Use closest to find the nearest cont class and remove it.
$('.container').on('click', '.delete', function () {
$(this).closest('.cont').hide();
});
Fiddle
Hope this helps.

Related

How to use JQuery.find() when DOM is dynamic

I have a cascading menu with the following flow;
click on an item from menu-1
creates and updates menu-2 li elements
click on an item from menu-2
creates and updates menu-3 li elements
etc..
```
$firstMenu = $('.prime-menu');
$secondtMenu = $('.second-menu');
$thirdMenu = $('.third-menu');
```
As i'm traversing through different elems. within each menu, using find() comes as a blessing, the issue is that the script loads when no menu other than the first menu is created so $secondtMenu.find('.item-year').click(function (clickEvent) {}) is 0 length.
What are my options in JQuery to make my find() functions work on elements that are not loaded yet in the DOM?
I thought of creating an event listener, but I think there are more terse approaches than that.
You should use delegates when dealing with dynamic HTML. For instance, use an outer element like document or body to "start" your finds.
$(document).find(".prime-menu");
EDIT: Find and event delegation
The solution was to use find with event delegation. Example event.
$(document).find(".prime-menu").on('mouseenter', '.track-table tbody tr', function(){ });
You state that when you click on an item from menu-1 it creates and updates menu-2 li elements. In this function is where you should do your event binding. The DOMElement will exist in js before being added to the dom, and that is where your bindings should be set.
If you need help share this code with us I'm sure myself or someone will be able to help you sort it out.
Bind the click handler to the menu parent, not the actual menu items.
Something like this might work...
$("#menuparent").on("click",".item-year",function(event) {
var clicked_element = event.currentTarget;
});
Doing it this way, even if the element with class .item-year is added to the dom after the click event is bound, it will still register the click.

jQuery Click Not Working/Registering

I am dynamically adding a list of anchor tags into a div with the id of join. For some reason, my jQuery handler (is it a handler?) isn't handling the clicks.
$(document).ready(function() {
$("#join").click(function() {
console.log("Clicked");
});
});
"Clicked" is not appearing in my console. I have a big headache now after Googling for about 2 hours.
Thanks in advance.
You can also try this way out, this is the most efficient way as you can have control over the click event.
$(document).ready(function() {
$("#join").on('click',function() {
$('#join').off('click');
console.log("Clicked");
});
});
try
$(document).ready(function() {
$(document).on.('click','#join',function() {
console.log("Clicked");
});
});
Note :this will only detect the first instance of #join element.
you may want to use classes instead of id
you need to use document as the selector to detect generated elements
When you create a handler from a selector, the handler is added to all the elements that match the selector when the selector (and handler) are run. If you subsequently add elements which would NOW match the selector, the handler is not automatically added. Those elements were not present when the selector first ran.
When you add your new elements, add the click handler to those new elements at the time they are added.
It is also strongly recommended not to have multiple elements in the page with the same "id" value. Consider using a class for an indicator of grouping.

Removing a dynamically generated element

I have implemented a user-generated keyword list for a project I'm working on, using jQueryUI autocomplete to suggest existing keywords.
On selecting the autocomplete suggestion, the returned string is added to the html of a div, as a child div.
I would like to add a removal function whereby the user can remove the child div if erroneously entered.
I've tried multiple suggested answers from Stackoverflow and elsewhere, but can't seem to get it working.
I've created a fiddle containing the pertinent elements.
The most logical solution to me was:
$('.keyword-entry').click(function(e){
var id = $(this).closest('div').prop('id');
$('#'+id).remove();
}
Though it would appear this doesn't work.
Whilst a solution to the problem would be very much appreciated to save my dwindling supply of coffee from running out this evening, I would also appreciate a rundown as to why I'm going wrong.
Thanks in advance.
Event delegation.
It's basically that you're attempting to attach an event to an DOM element that doesn't exist in the DOM at the time of load. Rewrite the .click() handler too:
$(document).on('click', '.trashYes', function () {
$(this).remove();
});
Fiddle: http://jsfiddle.net/6bBU4/
What it's doing is that, it's attaching the .click() event to the document (The top most DOM element) will travel down to find any new .trashYes, thus successfully executing the .remove(). This doesn't have to be bound to the document but to any DOM element within the document as well at load.
No need to get the id and then try and find it again, just do this...
$('<div id="'+id+'" class="keyword-entry" style="z-index:0">'+ui.item.value+' <--I want to remove this</div>')
.appendTo($('#keyword-list'))
.click(function(e){
$(this).remove();
});
when adding the keyword entry

Remove dynamically added elements

I've looked through some of the other posts but couldn't find an answer, so sorry if this is a somewhat stupid question.
I have a div
which I add span elements dynamically to, like <span id="agolf-squirecreek1.jpg">golf-squirecreek1.jpg</span>. I need to remove these elements dynamically as well when clicked on. I have the click event linked with .live(), but the remove() wont work on it. Any ideas?
Try to use .remove
http://api.jquery.com/remove/
Or
Why dont you hide the element on click using
.hide()
or by putting style or class. .add() or .addClass
or replace the html itself by .html or .text
This will remove a span when clicked within the context of div#id.
$('div#id').delegate('span', 'click', function() {
$(this).remove();
});
If you want to remove everything within an element you can use .empty() and furthermore, if you want to remove a span element but retain its event handlers/data object you can use .detach() which is useful if you intend to add the element back to the DOM.

Adding, Removing and Adding Element again removes its Event

I have a hyperlink with an ID when clicked will perform a certain event using JQuery. JQuery records the existence of this link on document load. Some time during the course of the users visit. I remove that link and the re-add it later. However, that even is not fired off again when that link is clicked after it has been removed and added.
Why is the case and how can I remedy it? Something to do with event binding?? Or shall I just add an onclick attribute?
You've been using a tag like this to add the click event:
$('#speciallink').click(function(){
// do something
return false;
});
This will bind the event to the elements that are selected at that moment.
Removing a link and adding it again, will effectively create a new element, without this event. You can use the "live" method to add rules that will be applied to events matching the rule, even when these elements are created after creating the rule:
$('#speciallink').live("click",function(){
// do something
return false;
});
You will need to bind that event handler to the new element when it is added or you could use live() instead of bind to achieve what you need.
Basically, the event handler references the original element. When that element is removed, even though a new element is added with the same id, it is a different element.
Don't remove the link from the DOM tree. Instead, just toggle its visibility with show() and hide().
Removing the element from the DOM tree with remove() will remove the element and all of its event handlers, even if you add it back with the same id.
If you completely remove the element, you will need to reattach any event listeners to the element when you recreate it.
Alternatively, just hide the element by setting its style to display:none with .show() and .hide()

Categories

Resources