jQuery live("click", function() {...}) doesn't work for body - javascript

I am trying this simple code here. It doesn't work for either the actual click event or the one which is commented out. Can anybody explain why? I have had issues with not previously also...

That's simply because the live function, which was long deprecated, has now been removed from jQuery.
Replace
$("body").live("click",function() { alert("coo"); });
with
$("body").on("click",function() { alert("coo"); });
Look at the top right of this page : "removed 1.9".

.live has been deprecated in jQuery since v1.7, and has been removed in v1.9.
You should replace it with .on().
.on has 2 syntaxes for binding elements, whereas .live only had 1.
If the element exists at the time you are binding, you do it like this:
$('.element').on('click', function(){
});
You can even use the shorthand:
$('.element').click(function(){
});
If the element does not exist at the time, or new ones will be added (which is what .live was normally used for), you need to use "event delegation":
$(document).on('click', '.element', function(){
});
NOTE: You want to bind to the closest static element, not always document.

The live() method has been deprecated and deleted. Use on().

If you are using jquery 2.0 version then you have to get the migrate 1.0 too
see this: http://jsfiddle.net/CRYDV/1/
otherwise you have to work with .on() handler as suggested in above answers.

Related

jQuery function .on works in 1.8.3 but not in 1.9.1

I have a function that works with jQuery 1.8.3 but when I upgrade to 1.9.1 it's not working anymore, but there's no change in documentation. Does somebody know how to fix this?
$(document).on("hover", "#cart-left", function(){
$("#cart").addClass('active');
});
http://jsfiddle.net/michalcerny/R9HZp/
Thanks for support!
In 1.9.1 you should use mouseover
$(document).on("mouseover", "#cart-left", function(){
$("#cart").addClass('active');
});
The status of the hover shorthand
As of jQuery 1.8 the hover shorthand has been deprecated. See the jQuery on() documentation:
Deprecated as of jQuery 1.8: The name "hover" used as a shorthand for the string "mouseenter mouseleave"
As of jQuery 1.9, the hover shorthand is unsupported. See the jQuery 1.9 Upgrade Guide
Alternative
In your case, it means you should use the mouseenter event. For example:
$(document).on("mouseenter", "#cart-left", function(){
$("#cart").addClass('active');
});
See jsFiddle demo
Making better usage of on()
It's also worth noting that unless the selector passed to on() refers to elements that are added to the DOM dynamically (i.e. after page load), there's no need to delegate the handler to the document. Instead, in this case you can probably bind the handler function directly to the element like so:
$("#cart-left").on("mouseenter", function(){
$("#cart").addClass('active');
});
The problem is not on the "on" function, but rather the "hover" pseudo-event that has been deprecated (and removed) in 1.9.1: http://jquery.com/upgrade-guide/1.9/#hover-pseudo-event

Why when initiating $.click() several times, and if the link is clicked once, it captures it more than once?

I have something like:
function init(){
$('.btn').click(function(){
//do something;
}
}
And when new content is added via ajax, I'm calling init(), so that click event applies to new buttons. But when I click it once, it captures several clicks (as many times as I called init()). It makes sense, but how to avoid it?
jsFiddle link: http://jsfiddle.net/s2ZAz/8/
Solutions:
* Use $.delegate() - http://api.jquery.com/delegate/
* Use $.live() - http://api.jquery.com/live/
Less preferred, but still, solutions:
* Use $.off() - http://api.jquery.com/off/ or $.unbind() - http://api.jquery.com/unbind/
click says, "for every object matching the selector, hook up this click listener". You probably want something more like delegate that says "for every object that will ever match this selector, hook up this listener".
$(document).delegate('button', 'click', function() {
});
You will still get double callbacks if you call init twice, but in this manner, you won't have to call init twice, because as new objects are added, they'll already be assigned to click listeners.
Note that document above should be replaced with the nearest persistent ancestor, as per Greg's comment below.
Demo.
Since jQuery 1.7, you can preferably use the .on() function to achieve the same effect.
Demo.
You can use the unbind method to remove the event handler (or the off method if you're using the new jQuery 1.7 syntax for attaching handlers)
Better yet, you can use the live method, to set up the event handler for any elements that are added to the page in the future and match the given selector. In this way you only have to call init once.
$("body").delegate("button", "click", function() {
alert('I\'m annoying!');
});
$('div').append("<button>Click me, I will alert twice</button><br/>");
$('div').append("<button>Click me, I will alert once</button><br/>");
$('div').append("<button>Click me, I will not alert at all</button><br/>");
Try it out
As mentioned by David, and as per liho's delegate example (loved the way the fiddle cascaded how many times the alert would pop!!), the problem is with multiple bindings, which can be solved with .live() (deprecated) or .delegate() (being phased out), or .on() (the preferred). However, it is a mistake to delegate listening to the document or even body node in terms of performance.
A better way to do this is identify an ancestor of the button that will not ever be destroyed. body is an easy choice, but it's almost always the case that we build our pages with wrapper elements of some sort, which are nested one or more levels deeper than body and therefore allow you to set fewer listeners.
HTML:
<div id="someWrapper">
<div class="somethingThatGetsDestroyed">
<button>Click Me</button>
</div>
</div>
JS using jQuery 1.7+:
$('#someWrapper').on('click', 'button', function() {
alert('Clickity-click!');
});

mouseover does not work after prepending

I am using the following to prepend new tweets to the list of tweets that I currently have
$(newTwet).clone().hide().prependTo('#tweetsList').slideDown();
newTweet is a variable that holds HTML code that is coming from a POST request. Which contains
<div class="newTweet">.........</div>
Everything seems to work just fine. However, the .newTweet class that is being prepended to the #tweetlist has an associated mouseover/mouseout function that does not work until I refresh the page. Is there a way to fix this?
Without seeing your actual script, particularly the part that handles the mouseover, it's difficult to say. But I'd suggest that you need to use on() (or delegate() in jQuery versions less than 1.7):
$('#parentElementID').on('mouseover','.newTweet',
function(){
// do stuff
});
Or with delegate():
$('#parentElementID').delegate('.newTweet','mouseover',
function(){
// do stuff
});
In jQuery 1.7 live() was deprecated, and replaced by on(), and prior to 1.7 delegate() is recommended:
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live(). [Cited from: jQuery API reference for live().
Use .live('mouseover',function(){});
Try with:
$(newTwet).clone(true).hide().prependTo('#tweetsList').slideDown();
Here is a .clone() documentation.

jQuery: How to add event handler to dynamically added HTML elements?

I have the following code:
$(document).ready(function({
$(".click").click(function(){
alert(' The Button Was Clicked !');
});
}));
This works fine.But If I add an element with the same class to the web page, as shown here:
$('#clicked').click(function(){
$("#area").append("<button class='click'>Click me</button>");
});
Then the event handler I added before to the .click class won't work for this new element.
What's that best way to add event handlers to elements that were added dynamically ?
UPDATE
It's been a while since I posted this answer and things have changed by now:
$(document).on('click', '.click', function() {
});
Since jQuery 1.7+ the new .on() should be used and .live() is deprecated. The general rule of thumb is:
Don't use .live() unless your jQuery version doesn't support .delegate().
Don't use .delegate() unless your jQuery version doesn't support .on().
Also check out this benchmark to see the difference in performance and you will see why you should not use .live().
Below is my original answer:
use either delegate or live
$('.click').live('click', function(){
});
or
$('body').delegate('.click', 'click', function() {
});
In reference to your code, the way to do it would be.
$('.click').live('click', function(){
... do cool stuff here
});
Using the .live() function allows you to dynamically attach event handlers to DOM objects.
Have fun!
for all the elements added dynamically to DOM at run time , please use live
http://api.jquery.com/live/
After jQuery 1.7 the live method just points to .on() method. And I had alot trouble finding out how to bind event handler to element which is appended to the DOM after its loaded.
$('body').live('click', '.click', function(){
//Your code
});
This worked for me. Just a little tip for those having trouble with it also.

jQuery.click not working after adding element to the DOM

I have a simple jQuery('div#star').click(function.
The function works once when the DOM is initially loaded, but at a later time, I add a div#star to the DOM, and at that point the click function is not working.
I am using jQuery 1.4.4, and as far as I know, I shouldn't need to use .live or .bind anymore. There is never more than one div#star in the DOM at any one time. I tried changing from id="star" to class="star" but that didn't help.
Any suggestions on how to get this working or why it isn't working?
I've had the .click inside the jQuery(document).ready, and in an external js file, and neither works after adding the div to the DOM.
This works with jQuery 2.0.3
$(document).on('click', '#myDiv', function() {
myFunc();
});
As of jQuery 1.7, the .live() method is deprecated. The current recommendation is to use .on() which provides all functionality covering the previous methods of attaching event handlers. Simply put, you don't have to decide any more since on() does it all.
Documentation is handily provided in the help for converting from the older jQuery event methods .bind(), .delegate(), and .live()
You still need to use live events.
http://api.jquery.com/live/
try
.on('event', 'element', function(){
//code })
You need to use either live or delegate here. Nothing has changed in this department since jQuery 1.4.4.
Try to think of it like this: click and bind attach an event to the element itself, so when the element disappears, all the information about the event does too. live attaches the event at the document level and it includes information about which element and event type to listen for. delegate does the same thing, except it attaches the event information to whatever parent element you like.
user "live" method $("div#star").live("click", function() {});
Doc
You can use delegate instead on :
$(document).delegate('click', "selector", function() {
//your code
});
I hope it will help.

Categories