.live() does not behave like .bind() - javascript

After asking this question : jQuery die() does not work. I found that live() does not seem to behave like bind().
I had the following line:
$('.produit').die().live('change',function(){ // the rest
$('.produit').live('change',function(){ // that did not work either
Then I changed it to:
$('.produit').unbind('change').bind('change',function(){ // the rest
What is the difference between the two lines.
In this example .produit is added dynamically to the page. And the binding is done after the prepend().
I'm using jQuery 1.4.2, and IE7.

If you use IE there is some problem with live and change event
search for livequery plugin which solves this.
try to change the event to Click event and youll see that it works.
The difference is that Bind is for Already In Page elements and live is also+Future elements.

Live does not behave like bind. That is correct.
Live attaches a handler for only predefined actions (like click or keypress). With bind you can define your own events and trigger them however you deem necessary.
All in all, in the end, it is better to use bind over live. That is why in the newest jQuery 1.7 (which you are not using) there is the functions on and off which basically combines the functionality of live, bind, and delagate

Related

SmartyStreets jQuery.liveaddress plugin, how to unbind events

I'm using smarty streets jquery.liveaddress plugin in an angular single page app. I need to unbind all of the event listeners from the liveaddress instance when I transition to next page. Right now, if I come back to the page, all events are fired twice, then the next time on page, three times.
I've tried everything i can think of. My last solution was to unbind all of the event names from the $(document) because it looks like that is where the plugin is attaching all of the events to. but even that didn't work.
jQuery(document).unbind("AddressChanged");
jQuery(document).unbind("AutocompleteUsed");
jQuery(document).unbind("VerificationInvoked");
jQuery(document).unbind("RequestSubmitted");
jQuery(document).unbind("ResponseReceived");
jQuery(document).unbind("RequestTimedOut");
jQuery(document).unbind("AddressWasValid");
jQuery(document).unbind("AddressWasAmbiguous");
jQuery(document).unbind("AddressWasInvalid");
jQuery(document).unbind("AddressWasMissingSecondary");
jQuery(document).unbind("OriginalInputSelected");
jQuery(document).unbind("UsedSuggestedAddress");
jQuery(document).unbind("InvalidAddressRejected");
jQuery(document).unbind("AddressAccepted");
jQuery(document).unbind("Completed");
Ok for anyone trying to implement SmartyStreets jquery.liveaddress plugin in an angular application.
The trick was to not register anonymous event handlers.
In my case I was instantiating SmartyStreets in a directive, so put all the eventHandlers on scope and call liveAddress.deactivate() upon $destroy. No more duplicate events.
In jQuery, event handler functions are stored in an array. Therefore, unbind() function looks just for the function in the aforementioned array. It further means that you can only unbind() event handlers which are already added with bind().
Check out jQuery documentation on .bind()

How jQuery's .on/.live works? [duplicate]

I'm curious to know the differences between the bind and live functions.
To me they seem to be almost identical.
I read the benefits of live/bind methods, but it didn't tell me about the differences...
Thanks!
In short: .bind() will only apply to the items you currently have selected in your jQuery object. .live() will apply to all current matching elements, as well as any you might add in the future.
The underlying difference between them is that live() makes use of event bubbling. That is, when you click on a button, that button might exist in a <p>, in a <div>, in a <body> element; so in effect, you're actually clicking on all of those elements at the same time.
live() works by attaching your event handler to the document, not to the element. When you click on that button, as illustrated before, the document receives the same click event. It then looks back up the line of elements targeted by the event and checks to see if any of them match your query.
The outcome of this is twofold: firstly, it means that you don't have to continue reapplying events to new elements, since they'll be implicitly added when the event happens. However, more importantly (depending on your situation), it means that your code is much much lighter! If you have 50 <img> tags on the page and you run this code:
$('img').click(function() { /* doSomething */ });
...then that function is copied into each of those elements. However, if you had this code:
$('img').live('click', function() { /* doSomething */ });
...then that function is stored only in one place (on the document), and is applied to whatever matches your query at event time.
Because of this bubbling behaviour though, not all events can be handled this way. As Ichiban noted, these supported events are click, dblclick mousedown, mouseup, mousemove, mouseover, mouseout, keydown, keypress, keyup.
.bind() attacheds events to elements that exist or match the selector at the time the call is made. Any elements created afterwards or that match going forward because the class was changed, will not fire the bound event.
.live() works for existing and future matching elements. Before jQuery 1.4 this was limited to the following events: click, dblclick mousedown, mouseup, mousemove, mouseover, mouseout, keydown, keypress, keyup
Bind will bind events to the specified pattern, for all matches in the current DOM at the time you call it. Live will bind events to the specified pattern for the current DOM and to future matches in the DOM, even if it changes.
For example, if you bind $("div").bind("hover", ...) it will apply to all "div"s in the DOM at the time. If you then manipulate the DOM and add an extra "div", it won't have that hover event bound. Using live instead of bind would dispatch the event to the new div as well.
Nice read on this: http://www.alfajango.com/blog/the-difference-between-jquerys-bind-live-and-delegate/
Is nowadays (since jQuery 1.7) deprecated using the .on() function - http://api.jquery.com/on/
imagine this scenario:
i have several <img> elements.
$('img').bind('click', function(){...});
add some extra images (using get(), or html(), anything)
the new images don't have any binding!!
of course, since the new images didn't exist when you did the $('img')... at step 2, it didn't bind the event handler to them.
now, if you do this:
i have several <img> elements.
$('img').live('click', function(){...});
add some extra images (using get(), or html(), anything)
the new images do have the binding!!
magic? just a little. in fact jQuery binds a generic event handler to another element higher in the DOM tree (body? document? no idea) and lets the event bubble up. when it gets to the generic handler, it checks if it matches your live() events and if so, they're fired, no matter if the element was created before or after the live() call.
In adition to what they said, I think it's best to try to stick to bind when/where you can and use live only when you must.
All these jQuery methods are used for attaching events to selectors or elements. But they all are different from each other.
.bind(): This is the easiest and quick method to bind events. But the issue with bind() is that it doesn’t work for elements added dynamically that matches the same selector. bind() only attach events to the current elements not future element. Above that it also has performance issues when dealing with a large selection.
.live(): This method overcomes the disadvantage of bind(). It works for dynamically added elements or future elements. Because of its poor performance on large pages, this method is deprecated as of jQuery 1.7 and you should stop using it. Chaining is not properly supported using this method.
Find out more here
I wanted to add to this after having to debug a bit due to my own silliness. I applied .live() to a class of button on my page, assuming that it would just render out the correct ID I was trying to pass on the query string and do what I wanted to do with the ajax call. My app has dynamically added buttons associated with an inventory item. For instance, drill down categories to the 'COKE' button to add a coke to your order. Drill down from the top again, and add 'BUDLITE' - each time I wanted those items to be entered into a table via an AJAX call.
However, since I bound .live() to the entire class of buttons, it would remember each ajax call I had made and re-fire it for each subsequent button! It was a little tricky because I wasn't exactly clear on the difference between bind and live (and the answer above is crystal about it), so I figured I'd put this here just in case somebody was doing a search on this stuff.
There is a way to get the live effect but its kind of nasty.
$(this).unbind('mouseout').bind('mouseout',function(){
});
this will clear the previous and reset the new. It has seemed to work fine for me over time.
Difference between live and livequery is discussed here .

bind('keyup') not working on content injected after the dom is loaded

I have a list of inputs and when the user enters a specific key, something happens. This works great but there is also a button to fetch content from a server (JSON) and then add it to the dom (HTML) after it has been formatted (Markup.js). The problem is that on the inputs that are injected after the dom is loaded the keyup events do not register. What is causing this problem?
Use .on() instead of .bind().
For earlier versions, the .bind() method is used for attaching an
event handler directly to elements. Handlers are attached to the
currently selected elements in the jQuery object, so those elements
must exist at the point the call to .bind() occurs.
See jQuery - how to use the "on()" method instead of "live()"? on how to use .on(), and https://stackoverflow.com/a/14354091/584192 for examples on how to migrate existing code.
You must to bind the events AFTER the injection of the inputs. Can you post you're relevant code to better answer this question?

effects of javascript not work in ajax reply

I am new in AJAX. I have searched a lot on Internet but only got basic AJAX steps. Now I am writing codes using AJAX but a common problem I am facing continuously.
When I place return text in the particular id of HTML page, Javascript effects do not work. CSS works fine but Javascript effects like table sorting, jQuery effects or any other effect does not work. I know I am missing some concept here. But didn't get any effective answer.
Please suggest me what should I do? And what is the concept behind this...
The new HTML you're adding to the DOM (page) didn't exist when your jquery ran the first time and bound events to elements on the page. You're probably using $("something").click(...) or .bind("click", ...). Instead of these use the delegate function from jquery. Delegate is generally more flexible and faster than live. For instance you can not stopPropagation in a 'live' binding.
Jquery Delegate
Why Delegate is better than Live
Here is another SO answer that explains the benefits of delegate
What's most likely happening is that your events are getting unbound because you update the DOM with new elements. The easiest solution is to use the live method to bind to events : http://api.jquery.com/live/
Or you can simply rebind the events to the elements after insertion to the DOM just as easily.
EDIT
As user kasdega points out, another alternative is to use delegate : http://api.jquery.com/delegate/ Delegate works by using the bound root elements as the context to rebind events to DOM elements that may appear in the future.

Are events lost in jQuery when you remove() an element and append() it elsewhere?

What happens in jQuery when you remove() an element and append() it elsewhere?
It appears that the events are unhooked - as if you were just inserting fresh html (which I guess is what happening). But its also possible my code has a bug in it - so I just wanted to verify this behavior before I continue.
If this is the case - are there any easy ways to rehookup the events to just that portion of HTML, or a different way to move the element without losing the event in the first place.
The jQuery detach() function is the same as remove() but preserves the event handlers in the object that it returns. If you have to remove the item and place it somewhere else with everything you can just use this.
var objectWithEvents = $('#old').detach();
$('#new').append(objectWithEvents);
Check the API docs here: http://api.jquery.com/detach/
Yes, jQuery's approach with remove() is to unbind everything bound with jQuery's own bind (to prevent memory leaks).
However, if you just want to move something in the DOM, you don't have to remove() it first. Just append to your heart's content, the event bindings will stick around :)
For example, paste this into your firebug on this page:
$('li.wmd-button:eq(2)').click(function(){ alert('still here!') }).appendTo(document.body)
And now scroll down to the bottom of this page and click on the little globy icon now buried under the SO footer. You will get the alert. All because I took care to not remove it first.
use jQuery1.3.1 live() to bind events and you won't need to worry about this..
Update: live events are deprecated now, but you can get the same effect from $(document).on().

Categories