jQuery Drag and Drop Breaks When Loading Divs by AJAX - jquery-ui

I have a list of draggables that need to be dropped onto divs loaded by AJAX. However, when the divs are loaded by AJAX it breaks the droppables functionality. I removed AJAX from the equation and it worked fine.
Here's working code. With this code I can drag items in my .contentList to #block1 div and everything works peachy.
<div id="block1"></div>
$(".contentList").draggable();
var dropOpts = {
hoverClass: "activated",
tolerance: "pointer",
drop: getURL
};
$("#block1").droppable(dropOpts);
I then have the following code load a new div via jQuery .load.
$(document).ready(function() {
$("#template1").click(function() {
$("#dynamic-ui").load("/templates/newtemplate.html");
});
The newtemplate.html contains a div with the same id; #block1. However, once it loads I can no longer drag onto it. Any help would be greatly appreciated!

Add the code to make #block1 droppable after the newtemplate.html is loaded into dom. e.g.
$(document).ready(function() {
$("#template1").click(function() {
$("#dynamic-ui").load("/templates/newtemplate.html");
var dropOpts = {
hoverClass: "activated",
tolerance: "pointer",
drop: getURL
};
$("#block1").droppable(dropOpts);
});
});

The binding of events happens when the browser loads the webpage.
So during the loading if the JavaScript didn't find the specified division/element they won't bind the event. So for dynamically created divisions you need use jQuery live to bind the events.
For your question i think this question will answer you.
Hope it will help you.
Good luck

Related

Jquery UI Autocomplete not working after dom manipluation

I have been trying to implement the autocomplete and have come across a problem that has stumped me. The first time I call .autocomplete it all works fine and I have no problems. If, however, I call it after I have removed some (unrelated) elements from the DOM and added a new section to the DOM then autocomplete does nothing and reports no errors.
Code:-
$.ajax({
type : 'get',
dataType : 'json',
url : '/finance/occupations',
cache:true,
success:function(data){
occupationList = data;
$('.js-occupation').autocomplete({
source: occupationList,
messages: {
noResults: '',
results: function(){}
},
minLength : 2,
select:function(event, ui){
$('.js-occupationId').val(ui.item.id);
}
});
}
});
The background to this page is that it contains multiple sections that are manipulated as the user moves through them. Hide and show works fine and does not impact on the autocomplete. However, if I do the following:-
var section = $('.js-addressForm:last').clone();
clearForm(section);
$('div.addressDetails').append(section);
$('.js-addressForm:first').remove();
Which gives the user the bility to add multiple addresses on the previous section then the autocomplete stops working.
Any suggestions or pointers on something obvious I am missing?
I have tried to put the initialisation of the autocomplete on an event when the element gets focus and it still does not work.
You have to create the autocomplete after all other underlying objects. If you F12, you will see that the list is "visible", however it is below and hidden by all instances created after it.
If you created a div with inputs (one input being the autocomplete), then you create the automplete then the dialog instances, the autocomplete will never show. If you create the dialog then the autocomplete, no problem. The problem is the z-order
I have faced the same issue. For now to fix this, i'm creating widget on the input once input is in focus. It will help you solve the issue.
You can look for the help on
making sure some event bing only when needed
Sample code will look like this
$( "#target" ).focus(function() {
//I don't care if you manipulated the DOM or not. I'll be cautious. ;)
(function() {
$( "#combobox" ).combobox();
$( "#toggle" ).click(function() {
$( "#combobox" ).toggle();
});
})();
// use a flag variable if you want
});
This solved my problem. Hope its the solution you were looking f

Adding jquery dragdrop to knockout [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Sortable and droppable knockout list
I am using knockout to bind a UL. I am wanting to gives users the ability to drag and drop a LI and for my viewmodel to update with the reorder.
Drag and drop is working and I have the correct event working within my jquery but I am not sure how to make the update.
I have had a hunt around the documentation but cant find anything.
I've created a fiddle to make explaining what I am doing a little easier
Js Fiddle here
Any suggestions would be awesome!
Updated the jsfiddle link
I've never worked with Knockout and I don't have time to understand its intricacies right now, so this isn't a complete solution, but here's something to get you started. See below for links to some pages I found while searching that may help you complete the solution.
This is the part that I changed from your original fiddle:
var view_model = new ViewModel(initialData);
ko.applyBindings(view_model);
$(function() {
$( "#sortable" ).sortable({
revert: true,
stop: function(event, ui) { console.log("stop event")},
start : function ( event, ui ) {
ui.item.data( 'previous_index', ui.item.index() );
},
// start
update : function ( event, ui ) {
var question = view_model.questions.splice(
ui.item.data( 'previous_index' ), 1
)[0];
view_model.questions.splice( ui.item.index(), 0, question );
ui.item.removeData( 'previous_index' );
}
// update
});
});
References:
jQuery UI Sortable, how to determine current location and new location in update event?
get the start position of an item using the jquery ui sortable plugin
jQuery Sortable() with original position placeholder?
knockout + jqueryui draggable/droppable follow-up
Ryan Niemeyer has authored a Knockout plug-in for this purpose:
https://github.com/rniemeyer/knockout-sortable
Here is an updated blog entry:
http://www.knockmeout.net/2012/02/revisiting-dragging-dropping-and.html

Creating a jQuery UI sortable in an iframe

On a page I have an iframe. In this iframe is a collection of items that I need to be sortable. All of the Javascript is being run on the parent page. I can access the list in the iframe document and create the sortable by using context:
var ifrDoc = $( '#iframe' ).contents();
$( '.sortable', ifrDoc ).sortable( { cursor: 'move' } );
However, when trying to actually sort the items, I'm getting some aberrant behavior. As soon as an item is clicked on, the target of the script changes to the outer document. If you move the mouse off of the iframe, you can move the item around and drop it back by clicking, but you can not interact with it within the iframe.
Example: http://robertadamray.com/sortable-test.html
So, is there a way to achieve what I want to do - preferably without having to go hacking around in jQuery UI code?
Dynamically add jQuery and jQuery UI to the iframe (demo):
$('iframe')
.load(function() {
var win = this.contentWindow,
doc = win.document,
body = doc.body,
jQueryLoaded = false,
jQuery;
function loadJQueryUI() {
body.removeChild(jQuery);
jQuery = null;
win.jQuery.ajax({
url: 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js',
dataType: 'script',
cache: true,
success: function () {
win.jQuery('.sortable').sortable({ cursor: 'move' });
}
});
}
jQuery = doc.createElement('script');
// based on https://gist.github.com/getify/603980
jQuery.onload = jQuery.onreadystatechange = function () {
if ((jQuery.readyState && jQuery.readyState !== 'complete' && jQuery.readyState !== 'loaded') || jQueryLoaded) {
return false;
}
jQuery.onload = jQuery.onreadystatechange = null;
jQueryLoaded = true;
loadJQueryUI();
};
jQuery.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js';
body.appendChild(jQuery);
})
.prop('src', 'iframe-test.html');
​
Update: Andrew Ingram is correct that jQuery UI holds and uses references to window and document for the page to which jQuery UI was loaded. By loading jQuery / jQuery UI into the iframe, it has the correct references (for the iframe, rather than the outer document) and works as expected.
Update 2: The original code snippet had a subtle issue: the execution order of dynamic script tags isn't guaranteed. I've updated it so that jQuery UI is loaded after jQuery is ready.
I also incorporated getify's code to load LABjs dynamically, so that no polling is necessary.
Having played with their javascript a bit, Campaign Monitor solves this by basically having a custom version of jQuery UI. They've modified ui.mouse and ui.sortable to replace references to document and window with code that gets the document and window for the element in question. document becomes this.element[0].ownerDocument
and they have a custom jQuery function called window() which lets them replace window with this.element.window() or similar.
I don't know why your code isn't working. Looks like it should be.
That said, here are two alternative ways to implement this feature:
If you can modify the iframe
Move your JavaScript from the parent document into iframe-test.html. This may be the cleanest way because it couples the JavaScript with the elements its actually executing on.
http://dl.dropbox.com/u/3287783/snippets/rarayiframe/sortable-test.html
If you only control the parent document
Use the jQuery .load() method to fetch the content instead of an HTML iframe.
http://dl.dropbox.com/u/3287783/snippets/rarayiframe2/sortable-test.html
Instead of loading jQuery and jQueryUI inside the iFrame and evaluating jQueryUI interactions both in parent and child - you can simply bubble the mouse events to the parent's document:
var ifrDoc = $( '#iframe' ).contents();
$('.sortable', ifrDoc).on('mousemove mouseup', function (event) {
$(parent.document).trigger(event);
});
This way you can evaluate all your Javascript on the parent's document context.

Bind jQuery UI autocomplete using .live()

I've searched everywhere, but I can't seem to find any help...
I have some textboxes that are created dynamically via JS, so I need to bind all of their classes to an autocomplete. As a result, I need to use the new .live() option.
As an example, to bind all items with a class of .foo now and future created:
$('.foo').live('click', function(){
alert('clicked');
});
It takes (and behaves) the same as .bind(). However, I want to bind an autocomplete...
This doesn't work:
$('.foo').live('autocomplete', function(event, ui){
source: 'url.php' // (surpressed other arguments)
});
How can I use .live() to bind autocomplete?
UPDATE
Figured it out with Framer:
$(function(){
$('.search').live('keyup.autocomplete', function(){
$(this).autocomplete({
source : 'url.php'
});
});
});
jQuery UI autocomplete function automatically adds the class "ui-autocomplete-input" to the element. I'd recommend live binding the element on focus without the "ui-autocomplete-input"
class to prevent re-binding on every keydown event within that element.
$(".foo:not(.ui-autocomplete-input)").live("focus", function (event) {
$(this).autocomplete(options);
});
Edit
My answer is now out of date since jQuery 1.7, see Nathan Strutz's comment for use with the new .on() syntax.
If you are using the jquery.ui.autocomplete.js try this instead
.bind("keydown.autocomplete") or .live("keydown.autocomplete")
if not, use the jquery.ui.autocomplete.js and see if it'll work
If that doesn't apply, I don't know how to help you bro
Just to add, you can use the .livequery plugin for this:
$('.foo').livequery(function() {
// This will fire for each matched element.
// It will also fire for any new elements added to the DOM.
$(this).autocomplete(options);
});
To get autocomplete working when loaded dynamically for the on() event used in jQuery > 1.7, using the syntax Nathan Strutz provides in his comment:
$(document).on('focus', '.my-field:not(.ui-autocomplete-input)', function (e) {
$(this).autocomplete(options)
});
where .my-field is a selector for your autocomplete input element.
.live() does not work with focus.
also keyup.autocmplete does not make any sense.
Instead the thing I have tried and working is this
$(document).ready(function(){
$('.search').live('keyup' , function()
{
$(this).autocomplete({ source : 'url.php' });
});
})
This works perfectly fine.
You can't. .live() only supports actual JavaScript events, not any custom event. This is a fundamental limitation of how .live() works.
You can try using this:
$('.foo').live('focus.autocomplete', function() {
$(this).autocomplete({...});
});
After reading and testing everyone else's answers I have updated it for the current version of JQuery and made a few tweaks.
The problem with using keydown as the event that calls .autocomplete() is that it fails to autocomplete for that first letter typed. Using focus is the better choice.
Another thing I have noticed is that all of the given solutions result in .autocomplete() being called multiple times. If you are adding an element dynamically to the page that will not be removed again, the event should only be fired once. Even if the item is to be removed and added again, the event should be removed and then added back each time the element is removed or added so that focusing on the field again will not unnecessarily call .autocomplete() every time.
My final code is as follows:
$(document).on('focus.autocomplete', '#myAutocomplete', function(e){
$(this).autocomplete(autocompleteOptions);
$(document).off('focus.autocomplete', '#myAutocomplete');
});
autocomplete is not an event rather a function that enables autocomplete functionality for a textbox.
So if you can modify the js that creates the textboxes dynamically to wrap the textbox element in as a jquery object and call autocomplete on that object.
I just noticed you edited your post with this answer. It was obvious to me so I'm posting it below for others. Thank you.
$(function()
{
$('.search').live('keyup.autocomplete', function()
{
$(this).autocomplete({ source : 'url.php' });
});
});
This works for me:
$(function()
{
$('.item_product').live('focus.autocomplete', function()
{
$(this).autocomplete("/source.php/", {
width: 550,
matchContains: true,
mustMatch: false,
selectFirst: false,
});
});
});
You can just put the autocomplete inside input live event, like this:
$('#input-element').live('input', function(){
$("#input-element").autocomplete(options);
});

Fancybox, getting Fancybox to bind using LIVE() to items being loaded onto the page after load

I have a page that loads and after it loads, it pulls in a list of LIs to populate a news feed.
<li>quick view</li>
<li>quick view</li>
<li>quick view</li>
I'm trying to get fancy box to trigger when a user clicks on quick view but haven't had any luck. Any Ideas?
$(document).ready(function() {
$('.quickview').fancybox();
});
also tried:
$(document).ready(function() {
$('a.quickview').live('click', function() {
$(this).fancybox();
});
});
http://fancybox.net/
Thanks for any ideas...
Old question, but might be useful for future searchers.
My preferred solution is to fire fancybox manually from within the live event, eg:
$('.lightbox').live('click', function() {
$this = $(this);
$.fancybox({
height: '100%',
href: $this.attr('href'),
type: 'iframe',
width: '100%'
});
return false;
});
EDIT: From jQuery 1.7 live() is deprecated and on() should be used instead. See http://api.jquery.com/live/ for more info.
this should work after every ajax request
$(document).ajaxStop(function() {
$("#whatever").fancybox();
});
The problems is to attach fancybox into AJAX loaded element, right?
I got same problems and I found this solution.
I copy paste it here, see the original bug report for more info:
$.fn.fancybox = function(options) {
$(this)
.die('click.fb')
.live('click.fb', function(e) {
$(this).data('fancybox', $.extend({}, options, ($.metadata ? $(this).metadata() : {})))
e.preventDefault();
[...]
Credit goes to jeff.gran.
Since .on is now recommended over .live, and after reading over the documentation on delegated events, here's a solution I came up with (assuming your elements have a class of 'trigger-modal'):
$(document).on('click', '.trigger-modal', function() {
// remove the class to ensure this will only run once
$(this).removeClass('trigger-modal');
// now attach fancybox and click to open it
$(this).fancybox().click();
// prevent default action
return false;
});
From my understanding of Fancybox, the call to fancybox() simple attaches the plugin to the selected element. Calling fancybox on a click event won't open anything.
I think you just need to add
$(li_element_that_you_create).fancybox();
to the code that creates the new LI elements in your list
EDIT
If you're using load, then you would do something like:
$('#ul_id_goes_here').load('source/of/news.feed', function() {
$('.quickview').fancybox();
});

Resources