I'm loading new elements with a form. After the elements are loaded I need to make each one draggable. According to .on doc "Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time."
I've tried oh-so-many variants of .on, .click, etc but so far no luck. I'm currently working with...
$('#parent').on('change', '.thumb', function(event){
alert('loaded');
$('.thumb').draggable();
});
...but, it doesn't attach to the new .thumb element. How can I accomplish this?
Edit: Here's the html...
<input type="file" id="parent" name="files[]" multiple />
<output> //these spans are created after files are selected from 'file'
<span><img class=".thumb" src="..."></span>
<span><img class=".thumb" src="..."></span>
</output>
When you use a plugin that requires binding it's own events and DOM manipulation from within the plugin, delegation methods like on() are useless.
You need to call the draggable() method when you load new elements such as in success callback of ajax.
If you are using load()
$('#myDv').load( url, function(){
/* new html has been inserted now */
/* in case any other active draggables will only search within $('#myDiv') for new elements that need to be called*/
$(this).find('.dragClass').draggable();
})
There isn't enough detail for me to answer this question specifically, so I will attempt to guess what the problem is.
You are binding this function to the event "change" of an element with an id of "parent." The "change" function will only work in certain DOM elements, namely input, textarea, and select. (http://api.jquery.com/change/) This means that the change event will never fire if the element with id "parent" is anything but those three tags.
If this is the problem, I would suggest moving the .draggable() method to the same place you are adding "elements with a form."
Try this:
$('#parent').live('change', '#child', function(event){
alert('loaded');
$('#child').draggable();
});
Related
I'm trying to understand why loading HTML into a div block renders its class statement effectively non-existent to a click event.
My HTML code looks like this:
<div id="load-to"></div>
<div id="load-from">
<div class="load-from-css"> Hello!</div>
</div>
<button>load it!</button>
My JS code looks like this:
$('button').click(function(){
var html = $('#load-from').html();
$('#load-to').html(html);
});
$('.load-from-css').click(function(){
alert('clicked');
});
When I click the button the HTML from the lower div block is loaded into the upper div block, and then the HTML looks like this:
<div id="load-to">
<div class="load-from-css"> Hello!</div>
</div>
<div id="load-from">
<div class="load-from-css"> Hello!</div>
</div>
My question is, why does the second click event (defined in my jQuery code) only work on the original lower "Hello!" div block but not on the loaded upper one, when both have the same class definition?
Other answers have already covered the core reason for your problem (that copying the HTML of an element and placing it elsewhere will create a brand new DOM element and does not copy any events that were bound to the original element... keeping in mind that when you add an event listener, it will only bind to any elements that exist at the time that you do so)
However, I wanted to add some other options for accomplishing what you want to do.
jQuery has a few different techniques that make this sort of thing easy:
.clone() will essentially do the same thing as you are doing now*, it will copy the HTML content and create a new DOM element. However, if you pass true (ie: .clone(true)), it will clone it with all data and events intact.
* note that to truly get the same result as using .html(), you need to do .children().clone(), otherwise you'll get both the inner and outer div.. this may or may not be necessary depending on the use case
ex: https://jsfiddle.net/Lx0973gc/1/
Additionally, if you were in this same situation but did not want to make a clone, and simply wanted to move an element from one place to another, there is another method called .detach() which will remove the element from the DOM, but keep all data and events, allowing you to re-insert it later, in the same state.
ex: https://jsfiddle.net/Lx0973gc/2/ (not the best example because you won't see it move anywhere, but it's doing it!)
As another alternative, you can use delegated event binding, which actually binds the event to a different element (a parent) which you know won't change, but still allows you to target a child element within it:
$('body').on({
'click': function() {
alert('clicked');
}
}, '.load-from-css');
ex: https://jsfiddle.net/Lx0973gc/4/
The $('.load-from-css') finds all elements currently existing and .click(...) attaches a listener to all these elements. This is executed once.
Then you copy the raw html which does not transfer any listeners. The DOM has nodes onto which the listeners are attached but when you copy the plain HTML you essentially create new nodes based on the html.
Because you are copying just the HTML. The js file is loaded at the beginning, when there is just one instance of a div with the "load-from-css" class. You should execute again the code adding the listener after you copy the html. Somethinglike:
$('button').click(function(){
var html = $('#load-from').html();
$('#load-to').html(html);
$('.load-from-css').click(function(){
alert('clicked');
});
});
#load-to inner HTML is initially empty. so added click listener only for #load-from .load-from-css. Dynamically bind element will not attach the click listener.
jQuery new version have the feature to attach the event for dynamic elements also. Try this
$('button').click(function(){
var html = $('#load-from').html();
$('#load-to').html(html);
});
$(document).on('click', '.load-from-css', function(){
alert('clicked');
});
Also we can use like this
$( document ).delegate( "load-from-css", "click", function() {
alert( "Clicked!" ); // jQuery 1.4.3+
});
Simply because the page did not refresh. You loaded a content to another content without loading the page, and the browser wont recognized any event added to the loaded element.
What you should do is load your javascript tag with the load along with the content.
Your code should be like this:
<div id="load-to">
<div class="load-from-css"> Hello!</div>
</div>
<div id="load-from">
<div class="load-from-css"> Hello!</div>
<script>$('button').click(function(){
var html = $('#load-from').html();
$('#load-to').html(html);
});
$('.load-from-css').click(function(){
alert('clicked');
});</script>
</div>
I’ve read many posts already on the $.each and newly added elements + event attachment. Many of the current Questions regarding this topic on StackOverflow don’t seem to work for me. $.on() is normally recommended since it allows us to append new elements and still maintain a single event listener + handler.
In my current code:
1.$(‘input[type="checkbox"]’).on(“change”, function(e){});
//I do a logical if-statement, if(this.checked) else
//With-in the if-statement I run $.each, however, once I have appended new element in this context a new li to the ul, it stops working.
Out of the curiosity has anyone encountered something like this before, and if YES, how have you folks solved this?
Some StackOverflow posts I have already seen:
jQuery $(element).each function doesn't work on newly added elements
jquery: dynamically appending li items to ul then adding click, but click runs through each li
Event binding on dynamically created elements?
Currently what you are using is called a "direct" binding which will only attach to element that exist on the page at the time your code makes the event binding call.
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.
As you are creating elements.
You need to use Event Delegation. You have to use .on() using delegated-events approach.
General Syntax
$(document).on(event, selector, eventHandler);
Ideally you should replace document with closest static container.
Example
$(document).on('change', 'input[type="checkbox"]', function(){
//Your code
});
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/
Is it possible and how can I listen for changes through the entire DOM tree with jQuery?
My specific issue: I have a 'tooltip' function that displays the contents of the title attribute in a stylish way when you do a hover on any html element. When you do a hover, however, by standard the browser renders the title in its own box. I would like to supress that. So what I've thought of is to move the contents of the title attribute to a custom (HTML5) data-title attribute the first time the page is loaded, and then my tooltip function will work with data-title.
The problem is that later on I might add / remove / change the HTML dynamically, so I need to 'rebind' those elements - change those title attrs again. It would be nice if there was an event listener that would listen for such changes for me and rebind the elements automatically.
My best guess is that you want to listen to DOM mutation events.
You can do that by DOM mutation event as any normal javascript event such as a mouse click.
Refer to this : W3 MutationEvent
Example:
$("element-root").bind("DOMSubtreeModified", "CustomHandler");
[edited in reply to research by member Tony]
So, without additional code, this is a bit of a blind shot, but it seems to me there are two things to think about here: 1. the default browser tooltip behaviour; 2. a potentially updated DOM and the ability for your custom tooltips to continue functioning.
Regarding #1: when you bind your custom event to the element, you can use event.preventDefault() so that the tooltips don't appear. This doesn't work properly. So, the workaround to keep using the "title" attribute is to grab the value, push it into the data object (the $.data() function), and then null the title with an empty string (removeAttr is inconsistent). Then on mouseleave, you grab the value out of the data object and push it back into the title. This idea comes from here: How to disable tooltip in the browser with jQuery?
Regarding #2: instead of re-binding on DOM change, you just need to bind once to a listener element that is never expected to be destroyed. Usually this is a container element of some sort, but it can even be document (approximating .live() which is now deprecated) if you really need an all-encompassing container. Here's a sample that uses some fake markup of my own devising:
var container = $('.section');
container.on('mouseenter', 'a', function() {
var $this = $(this);
var theTitle = $this.attr('title');
$this.attr('title', '');
$('#notatooltip').html(theTitle);
$.data(this, 'title', theTitle);
});
container.on('mouseleave', 'a', function() {
$('#notatooltip').html('');
var $this = $(this);
var storedTitle = $.data(this, 'title');
$this.attr('title', storedTitle);
});
My unrealistic markup (just for this example) is here:
<div class="section">
Hover this foo!
<div id="notatooltip"></div>
</div>
And a fiddle is here: http://jsfiddle.net/GVDqn/
Or with some sanity checks: http://jsfiddle.net/GVDqn/1/
There's probably a more optimal way to do this (I honestly didn't research if you could bind two separate functions for two separate events with one selector) but it'll do the trick.
You shouldn't need to re-bind based on DOM change, the delegated listener will automatically handle it. And you should be able to prevent default tooltip functionality just by preventing it.
You need to look at this here: http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-eventgroupings-mutationevents
As noted by Greg Pettit, you should be using the on() function on the element.
What this does is allows you to bind a selector to an event, then jQuery will add this event handler when the objects returned by the selector are available.
If you wanted a function to fire on a mouse over event and you wanted it to fire on all elements with the class of *field_title* you would do this:
$('.field_title').bind('mouseenter', function() { doSomething(); });
This will trigger on the over mouse over event on any objects that have the class of *field_title* and execute the function doSomething().
Hope that makes sense :)
I'm displaying a tabbed interface with the help of jQuery. When you click a tab, a ajax call will replace all html from a $(".content") element with new html, using something like
$(".content").html(response);
When I do this, are all jquery events and functions that are attached to elements inside the .content div removed? Is it ok to fire these events and functions again after I replace the HTML ? If I click the tabs 324523452354 times, will it duplicate jQuery data every time?
Yes. They will be removed. You can use the live event to attach to elements that dont exist yet.
$(".myElementClass").live("click", function (e) {
e.preventDefault();
//do stuff
});
In this case, this function will always be called on myElement no matter when it is injected into the DOM.
All HTML inside of your selector is replaced with the parameter you pass in, implying it is completely removed from the DOM. Meaning if you have:
<div id="mine">
<ul>
<li>One thing</li>
</ul>
</div>
And I do a call as such:
$('div#mine').html("hey");
My HTML will then be:
<div id="mine">
hey
</div>
As you can see the is completely removed and all its bound events mean nothing. If you use the jQuery.live() binding instead however, then elements that don't yet exist can have events associated with them. Meaning if you add some elements to the DOM then they events will still work, without you have to rebind if you add more, or replace them.
**.live** events are binded at the document level , read the following document which is really useful
http://www.bennadel.com/blog/1751-jQuery-Live-Method-And-Event-Bubbling.htm