I have an group of checkboxes with id's starting with somename and I want catch the click event of these checkboxes. Previously I have done this through jQuery. i.e.:
$("input[id^='somename']").click(function(){
// my code follows here
})
but this is not working this time around. Why?
P.S. The element is created via JavaScript after the page is fully loaded after making some ajax request. I don't know if this may be the problem?
just use live if elements are created after the page is loaded.
$("input[id^='somename']").live('click', function(){ // my code follows here })
P.S : Your search selector is "somename" but you search it on the attribute ID, are you sure that you don't want :
$("input[name^='somename']").live('click', function(){ // my code follows here })
instead?
This indeed could be the problem. Replace .click with .live()
$("input[id^='somename']").live('click', function(){ // my code follows here })
and you should be fine.
Since a call to .click is just a shortcut for .bind('click', fnc), this will not work if the element is not in the DOM when calling this. Even better than using .live() would be to use .delegate(). Have a read:
.live(), .delegate()
Using the standard binding functions only works on elements that exist at the time of the bind. You need to use something called event delegation, where elements further up the DOM tree are notified of events on descendant elements. The best way to do this is with .delegate():
$('#containingElement').delegate("input[id^='somename']", 'click', function(){
// your code here
});
This assumes that you have an element #containingElement that contains all the elements that you want to capture the events on.
NB that other answers recomment live. live and delegate use the same backend code, but for various reasons delegate is more efficient.
I believe that because you want this applied to dynamically created elements in the DOM you are going to have to use the the jQuery .live() method:
$("input[id^='somename']").live('click', function(e) {
// Your code
});
Instead of .click() try .change() event.
Related
This question already has answers here:
What's the difference between jQuery .live() and .on()
(8 answers)
Closed 9 years ago.
This may sound "silly" but I have a simple calendar that is loaded onto the page like this:
jQuery('#calendar .show_hide').load('plugins/calendar.html', function(){ // do something // });
That is not a problem
The calendar has 2 links that should scroll through the months - typical next prev links. So inside my load function I have this
jQuery('#calendar .show_hide').load('plugins/calendar.html', function(){
jQuery('a.month_change').on('click',function(){
jQuery.ajax({
type: "post",
data: jQuery(this).attr('href').replace('#',''),
url: 'plugins/calendar.html',
success:function(msg){
jQuery('#calendar .show_hide').html(msg);
}
});
});
});
where a.month_change is a class attached to the prev/next links. The Ajax post sends the data and returns the html. So far so good.
The first time you click a.month_change it works, but every time afterwards the page is not loaded. if I try .live('click;,function ... nothing happens the first time, nor any other.
I always get confused on these things, which is the correct way to dynamically load the page and then have the ajax calls/links etc. always work. Note the dynamic load and the ajax receiving page are the same page - plugins/calendar.html and JQ version is jquery-1.9.0
Live is deprecated since 1.7 and removed in 1.9 you must use it like this
$(document).on('click','selector',function(){
});
You should use the closest static element instead of document if you have one closer.
live() is depreciated, you should use the on() function instead.
$(document).on('click','selector',function(){
});
None of the answers here effectively show you how to use it, OR the documentation, so here you go.
jQuery(document).on('click', 'a.month_change', function(){
jQuery.ajax({
type: "post",
data: jQuery(this).attr('href').replace('#',''),
url: 'plugins/calendar.html',
success:function(msg){
jQuery('#calendar .show_hide').html(msg);
}
});
});
Where the first element we target is a static element that exists during page load, then the event we wish to capture, followed by the element that should have the event bound to it. This is event delegation in newer versions of jQuery. You don't need to use .live(), or .bind().
Here's the documentation for jQuery's .on()
use .on() because it also works on dynamically added DOM.
.live() is deprecated from new version.
Run Test
try
<script type="text/javascript">
$(function()
{
jQuery('a.month_change').on('click',function()
{
jQuery.ajax(
{
type: "post",
data: jQuery(this).attr('href').replace('#',''),
url: 'plugins/calendar.html',
success:function(msg)
{
jQuery('#calendar .show_hide').html(msg);
}
});
});
jQuery('#calendar .show_hide').load('plugins/calendar.html', function()
{
});
});
</script>
best is use Jquery on method. .live() is deprecated from new version.
for eg;
$('#yourElement').on('click',function(){});
Try
$(parentcontainer).on('click',elementtoclick,function(...){....});
Usually bind in this way solved my problems with new HTML contents
.click and .bind are binding with dom element currently present in the DOM during page load.
.live is one used to attach event for element which might be filled in DOM later either by Ajax or Javascript. But .live have major issue related to performance.
To over come this $.delegate where introduce with better performance in DOM Hierarchy.
With Latest Jquery 1.7 or above coming in place .on is used which used to bind event to element ( Run Time ) whenever element will be filled in DOM. It have improved performance
then .live you can have more information on this site
http://api.jquery.com/live/
Which will provide to insite of jQuery event binding
Since none of the other answers address the point you make that:
The first time you click a.month_change it works, but every time
afterwards the page is not loaded
then let me attempt to explain…
Your code is actually making two AJAX calls, one from .load() and one from .ajax()
The problem of the click events only firing once is caused because you are replacing the HTML of the calendar in the success handler for the .ajax() call with jQuery('#calendar .show_hide').html(msg); thereby replacing the a.month_change elements that you previously bound the click handler on.
The fix is to move the click event binding to be captured on an element in the page that is not being replaced by any AJAX call.
For example on the #calender element:
jQuery('#calendar').on('click', 'a.month_change', function(){ ... });
So you can therefore replace all content inside the #calendar and the click events will still be captured and then filtered by the click handler on the static ancestor element.
As the other answers have mentioned that .live() is removed in v1.9 you are using the correct .on() method but just in the wrong place.
i prefer and recommend you to use on() .. you can have a look to this post to learn more about on direct and delegated methods ....
$(document).on('click','yourselector',function{....});
this delegates the click event to document which is always static.. and finds the selector to put th events on.... however, using closest static element is always preferred since document is not good performances wise.
Not sure if this is posible or not, but I'm trying to use JavaScript that I loaded via a script tag when the page was initially requested on dynamic HTML that was loaded via jQuery's load() function.
Example: http://jsfiddle.net/3MR43/
As you can see in the example, after clicking a link in the pop up box, the link goes. The problem is that the link was suppose to be stopped, and you were suppose to see an alert.
However, if I paste the HTML that I am loading via jQuery, it works, so the code is fine.
Description
You need jQuery .live() or .on() method to bind events to dynamically created html.
Choose .live() or .on() depending on the version of jQuery you are using.
.live() Available since jQuery 1.3. Attach an event handler for all elements which match the current selector, now and in the future.
.on() Available since jQuery 1.7. Attach an event handler function for one or more events to the selected elements.
Check out my sample and this jsFiddle Demonstration
Sample
... for jQuery.live()
$('.lang').live("click", function(e) {
e.preventDefault();
alert('Testing..');
});
... for jQuery.on()
$('.lang').on("click", function(e) {
e.preventDefault();
alert('Testing..');
});
More Information
jsFiddle Demonstration
jQuery.live()
jQuery.on()
The problem is your .click will do it for only elements that exist at that time. If you want to do it for all potential future elements that that selector will match, you want to use on() (delgate() or live() with older versions of jQuery).
The $('.lang').click() event must be registered after the element is created!
You need a callback on the load function to register this.
You need to use live to attach handlers to elements that are loaded dynamically.
Try this, it will solve your problem.
$('.lang').live('click',function(e) {
e.preventDefault();
alert('Testing..');
});
You have to use on function for dynamicly loaded elements:
$('.open_lang').click(function(e) {
e.preventDefault();
$('#popup').load('http://skins.thehabbos.org/pop_up/language.php').css('display', 'block');
});
$('body').on('click', '.lang', function(e) {
e.preventDefault();
alert('Testing..');
});
(live and delegate are deprecated in JQuery 1.7+ which is the version of your JSFiddle)
Fixed JSFiddle
First off, I don't want another plugin to do this... jQuery already has the functionality to do 99% of what I want with the live() method.
Basically, I want to change this:
$(".some-button").live("click", function() { alert('yay!'); });
into this:
$(".some-button").live(function() { alert('yay!'); });
So, what I'm saying is that I want to fire a method right away when an element is added to the page... jQuery can already do this SOOO close because that's how it adds the "click" even in my example above!
How can I achieve this without adding another plugin, but rather, just by using the same functionality as the "live" and "die" methods do?
Here's some code I've copied and pasted that seems to work in fiddle, at least on FF: http://jsfiddle.net/KQBzn/
$(document).bind('DOMNodeInserted', function(event) {
alert('inserted ' + event.target.nodeName + // new node
' in ' + event.relatedNode.nodeName); // parent
});
source: http://forum.jquery.com/topic/how-to-get-notified-when-new-dom-elements-are-added
There isn't any cross-browser way to do this, and there's nothing in jQuery itself that allows it.
You'd have to use a plugin, or just manage invoking code for your new elements manually.
The the live()[docs] method and the delegate()[docs] method are only for event handling. The code you give them will only respond to browser events, not to DOM manipulation.
The reason .live() won't do this is because it does not run any code when adding new elements to the DOM. It isn't monitoring any DOM changes. Rather it is responding to events that bubble to the document, and invoking the handler if it matches the selector you gave it.
You can't do it with the .live() method.
It seems jQuery should add a feature to the .live() method so that if its used with a specific keyword like 'created' instead of an event name then it will let you execute a function for the created element. That'd be cool! For example, the ideal scenario would be like this:
$('.foobar').live('created', function() {
// do something with each newly created .foobar element here.
});
I am trying to use SimpleBox jQuery plug-in on my website. I have the code such that everytime the user clicks on a div of class "link", a SimpleBox is invoked.
I also have another button that uses javascript to dynamically create divs of class "link" to my page. However, when I try to click these divs, the SimpleBox is not invoked.
<script type="text/javascript">
function createLinkDiv()
{
var parentDiv = document.getElementById ("right");
var linkDiv = document.createElement("div");
numDivs++;
linkDiv.setAttribute("class","link");
linkDiv.setAttribute("id",numDivs);
parentDiv.appendChild(linkDiv);
}
$().ready(function() {
$(".link").click(function(event) {
event.preventDefault();
$("#simplebox").simplebox();
});
$(".close_dialog").click(function() {
event.preventDefault();
$("#simplebox").simplebox('close');
});
});
</script>
Any idea why? Any help would be appreciated! Thanks!
For Dynamically added items use .live() or .delegate() to attach event handlers
$(".link").live("click",function(event) {
event.preventDefault();
$("#simplebox").simplebox();
});
Or
$("#right").delegate(".link","click",function(event) {
event.preventDefault();
$("#simplebox").simplebox();
});
Out of context
I suppose you've placed the the createLinkDiv function since you're calling it through inline javascript. Calling functions via inline javascript is a bit of out of fashion these days. Binding those events in code helps to keep your javascipt code easily maintainable.
$("#createLink").click(function(){
$('<div/>').attr({"class":"link","id":"link_" + $(".link").size() })
//Id shouldn't start with a number (not in HTML5)
.click(linkClick)
//Now you don't have to use live
.appendTo("#right");
});
As a side note, the $().ready() syntax is deprecated; it's better to use $(document).ready or just call $ with a function as a parameter.
To answer your main question, the .click method only binds to elements that exist when it's called. So when you add elements to the DOM later, you're not launching the simplebox on click because the handler hasn't been bound. You could either use .delegate to attach event handlers, or you could add the onclick directly in the creation of the DOM element.
The accepted answer is out of date now. The live() method has been removed from jQuery 1.9 and replaced with the on() method.
The syntax for on() is
$(element).on(event, selector, handler)
So in #jnfr's case, one of his handlers could be re-written as
$(document).on("click",".link",function(event) {
event.preventDefault();
$("#simplebox").simplebox();
});
Hopefully this will be of use to anyone arriving here and getting errors when using live().
I noticed that in jquery appended text won't be processed by jquery functions. For example, you append a code containing dropdown-list and you have a function that invokes on changing its value. This function works on existing code only, not on appended one.
And the correct answer is:
Instead of using:
$('#purchase-table select').change(function() {
});
Use:
$('#purchase-table select').live('change', function() {
});
You need it to be able to process ajax-appended content by your jquery functions. Have a nice day.
Thanks to everyone helped.
You can use JQuery .live()
Append new content:
$('body').append('<div class="clickme">Another target</div>');
Add handler to it:
$('.clickme').live('click', function() {
// Live handler called.
});
Then clicks on the new element will also trigger the handler.
The easiest way to handle events on interactive content is the jQuery.live method.
http://api.jquery.com/live/
Description: Attach a handler to the event for all elements which match the current selector, now and in the future.