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.
Related
I have some code that creates an accordion with a select2 element which has a class called docType. I also have jquery code to trigger an event on selecting a value of the jquery element. While this works for select2 elements that already exist on the page load, it doesn't trigger for dynamically added elements. Here is my on change code:
$('.docType').on('change', function() {
// the code inside should be firing for dynamically added elements
}
Does anyone know why this way isn't working?
Use event delegation for dynamically added elements.
$(document).on("change",".docType", function() {
Us the 'on' method to delegate events. This will add a handler to dynamically generated elements.
$(document).on("change",".classnameyouarewatching", function() {
//Your code
}
on method definition
If your elements are being dynamically loaded, you'll need to use something more like what's below. For instance, say you're dynamically generating via AJAX or something similar the following input element:
<input type="text" class="text_element" value="some value">
To add event handlers to that element try using JS like this:
<script type="text/javascript">
$(document).on('change', '.text_element', function() {
console.log('Element with class "text_element" has changed');
console.log('New value is: ' + $(this).val());
});
</script>
The answer above is correct, but it is not just the 'on' handler that delegates the handling of dynamically generated DOM elements. The actual trick here is to place the handler on the document as it will always exist rather than the element or element class as you have above. It is the handler on document, looking for elements of a class (2nd param of the on event) that gets the job done you're looking for.
I think u need to call find() method for all the select element before firing on change method like below
$(".docType").find(":select").on( ("change", function() { // the code inside });
If it does not work, try JQuery instead of $.
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
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.
As most of us know, once an element has been loaded it is possible to attach an event to it by simply using the normal JQuery events.
The question is, what if I want to create a specific event, and define that an element with a specific class or id, will get that event automatically when they are loaded?
For example:
I have a function that checks whether the input that has been entered is numeric only, and allows only numbers to be entered inside an input.
To do that I add the class "numeric" to the input element.
Normally I would just run a script right after with JQuery or just by using the onkeypressed DOM event to attach that function to it.
However, let's assume I have an ajax request that attaches a new from page, with the class numeric in the proper input elements.
Using the script again using the same class selector will result in the event run 2 times for elements that were loaded earlier.. And for every time I run that script it will add that event over and over...
What I do now, is I used the "unbind" first, and then reattach the event to all elements, and it is working perfectly! But I am looking for more elegant solution.
Any suggestions?
You need to use the .on with event delegation
Syntax
$(parent-selector).on(event,target-selector,callback);
Note: The parent-selector must be parent element which is present in the DOM while binding the event, generally people use document and body, but for the performance you must have the nearest parent possible to the target
Example
$(document).on("click",".button",function(){
alert("Button Clicked");
});
Use the on function to attach event handlers for elements that do not exist.
$(document).on("keypress", ".numeric", function(){
//do something
});
JS Fiddle: http://jsfiddle.net/T34Ph/
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()