When I drag an element to a droppable area, it sends a socket to the server. Whenever I append a new element to the page, the drop: function() {} does not trigger when the appended element is dropped, it only works once the page has been refreshed, although the drag function works.
question
Is there a way to bind the drop function to the appending elements?
code
var UI = {
droppedArea: $('.dropArea'),
initialArea: $('#init-area')
};
UI.droppedArea.droppable({
drop: function(event, ui) {
var dropped = ui.draggable;
var droppedOn = $(this),
/* Rest of the code */
socket.emit('move', data);
}
});
// Element appended like this
function newItem(data) {
var html = '<li>'+data.content+'</li>';
UI.initialArea.append(html);
}
// From the server
socket.on('new', function(data) {
newItem(data);
});
Figured out why.
Under the drop: function(), I had an accept: option, which value were DOM elements, with a type of class, stored in a variable.
Therefore, any appended elements were not referenced by the variable, so they were not being captured by the function
var UI = {
var item = $('.the_item')
}
drop: function() {
accept: UI.item,
}
Related
I have a sortable list in React which is powered by jQuery UI. When I drag and drop an item in the list, I want to update the array so that the new order of the list is stored there. Then re-render the page with the updated array. i.e. this.setState({data: _todoList});
Currently, when you drag and drop an item, jQuery UI DnD works, but the position of the item in the UI does not change, even though the page re-renders with the updated array. i.e. in the UI, the item reverts to where it used to be in the list, even though the array that defines its placement has updated successfully.
If you drag and drop the item twice, then it moves to the correct position.
// Enable jQuery UI Sortable functionality
$(function() {
$('.bank-entries').sortable({
axis: "y",
containment: "parent",
tolerance: "pointer",
revert: 150,
start: function (event, ui) {
ui.item.indexAtStart = ui.item.index();
},
stop: function (event, ui) {
var data = {
indexStart: ui.item.indexAtStart,
indexStop: ui.item.index(),
accountType: "bank"
};
AppActions.sortIndexes(data);
},
});
});
// This is the array that holds the positions of the list items
var _todoItems = {bank: []};
var AppStore = assign({}, EventEmitter.prototype, {
getTodoItems: function() {
return _todoItems;
},
emitChange: function(change) {
this.emit(change);
},
addChangeListener: function(callback) {
this.on(AppConstants.CHANGE_EVENT, callback);
},
sortTodo: function(todo) {
// Dynamically choose which Account to target
targetClass = '.' + todo.accountType + '-entries';
// Define the account type
var accountType = todo.accountType;
// Loop through the list in the UI and update the arrayIndexes
// of items that have been dragged and dropped to a new location
// newIndex is 0-based, but arrayIndex isn't, hence the crazy math
$(targetClass).children('form').each(function(newIndex) {
var arrayIndex = Number($(this).attr('data-array-index'));
if (newIndex + 1 !== arrayIndex) {
// Update the arrayIndex of the element
_todoItems[accountType][arrayIndex-1].accountData.arrayIndex = newIndex + 1;
}
});
// Sort the array so that updated array items move to their correct positions
_todoItems[accountType].sort(function(a, b){
if (a.accountData.arrayIndex > b.accountData.arrayIndex) {
return 1;
}
if (a.accountData.arrayIndex < b.accountData.arrayIndex) {
return -1;
}
// a must be equal to b
return 0;
});
// Fire an event that re-renders the UI with the new array
AppStore.emitChange(AppConstants.CHANGE_EVENT);
},
}
function getAccounts() {
return { data: AppStore.getTodoItems() }
}
var Account = React.createClass({
getInitialState: function(){
return getAccounts();
},
componentWillMount: function(){
AppStore.addChangeListener(this._onChange);
// Fires action that triggers the initial load
AppActions.loadComponentData();
},
_onChange: function() {
console.log('change event fired');
this.setState(getAccounts());
},
render: function(){
return (
<div className="component-wrapper">
<Bank data={this.state.data} />
</div>
)
}
});
The trick is to call sortable('cancel') in the stop event of the Sortable, then let React update the DOM.
componentDidMount() {
this.domItems = jQuery(React.findDOMNode(this.refs["items"]))
this.domItems.sortable({
stop: (event, ui) => {
// get the array of new index (http://api.jqueryui.com/sortable/#method-toArray)
const reorderedIndexes = this.domItems.sortable('toArray', {attribute: 'data-sortable'})
// cancel the sort so the DOM is untouched
this.domItems.sortable('cancel')
// Update the store and let React update (here, using Flux)
Actions.updateItems(Immutable.List(reorderedIndexes.map( idx => this.state.items.get(Number(idx)))))
}
})
}
The reason jQuery UI Sortable doesn't work with React is because it directly mutates the DOM, which is a big no no in React.
To make it work, you would have to modify jQuery UI Sortable so that you keep the DnD functionality, but when you drop the element, it does not modify the DOM. Instead, it could fire an event which triggers a React render with the new position of the elements.
Since React uses a Virtual DOM, you have to use the function React.findDOMNode() to access an actual DOM element.
I would call the jQuery UI function inside the componentDidMount method of your component because your element has to be already rendered to be accessible.
// You have to add a ref attribute to the element with the '.bank-entries' class
$( React.findDOMNode( this.refs.bank_entries_ref ) ).sortable( /.../ );
Documentation - Working with the browser (everything you need to know is here)
Hope that makes sense and resolves your issue
I'm building a Meteor app that let's the user organize lists of items in tags.
I use jQuery draggable and droppable to update a collection when a user drags an item from one tag to another.
I find it hard to understand how/where/when I should call the function. I've tried a few different options (including this "hacky way of doing it". The Blaze documentation mentions that functions can be called on DOM events, but lacks the drag and drop events that I'm looking for. I've currently settled on calling the function under Template.rendered, but that means the item can only be dropped once per render. I've tried to counter this with Tracker.autorun, but I don't think I understand how it works and the item can still only be dropped once per render.
How can I make the .item draggable several times per render?
Template.tag.rendered = function () {
//wait on subscriptions to load
if (Session.get('DATA_LOADED')) {
Tracker.autorun(function () {
$(".item").draggable({
revert: true,
start: function (event, ui) {
var movingItem = Blaze.getData(this)._id;
Session.set('movingItem', movingItem);
},
});
$(".tag").droppable({
hoverClass: 'droppable',
drop: function () {
var movingItem = Session.get('movingItem');
var acceptingTag = Blaze.getData(this)._id;
Items.update(movingItem, {
$set: {"parents": acceptingTag}
});
}
});
});
}
};
I found the solution.
By separating the .draggable and .droppable into two different Template.rendered the function is now correctly called each time an item is moved.
No need for the Tracker.autorun
Template.item.rendered = function () {
if (Session.get('DATA_LOADED')) {
$(".item").draggable({
revert: true,
start: function (event, ui) {
var movingItem = Blaze.getData(this)._id;
Session.set('movingItem', movingItem);
console.log('moving ' + movingItem);
},
});
}
};
Template.tag.rendered = function () {
if (Session.get('DATA_LOADED')) {
$(".tag").droppable({
hoverClass: 'droppable',
drop: function () {
var movingItem = Session.get('movingItem');
var acceptingTag = Blaze.getData(this)._id;
Items.update(movingItem, {
$set: {"parents": acceptingTag}
});
console.log('Dropped on ' + acceptingTag);
}
});
}
};
In 1.4.2, I have this:
$(document).on('pagecontainershow', PageShown);
function PageShown(myEvent, myUI ) {
log(this)
log(myEvent)
log(myUI)
};
I can't determine which page was just shown.
If I add more specificity to the selector, the event doesn't fire.
Update
As of jQuery Mobile 1.4.2 you can access previous .prevPage and next page .toPage.
$(document).on("pagecontainerhide", function (e, ui) {
var activePage = ui.toPage,
previousPage = ui.prevPage;
});
Both are jQuery objects so $() isn't needed.
To determine which page is currently active, you have two options:
Listen to pagecontainerhide and check ui.nextPage object emitted by that event
$(document).on("pagecontainerhide", function (e, ui) {
var activePage = $(ui.nextPage);
});
On pagecontainershow, use the below function which will return active page.
var activePage = $.mobile.pageContainer.pagecontainer("getActivePage");
Read more about page events.
i have created a directive to handle selectable provided by Jquery
mydirectives.directive('uiSelectable', function ($parse) {
return {
link: function (scope, element, attrs, ctrl) {
element.selectable({
stop: function (evt, ui) {
var collection = scope.$eval(attrs.docArray)
var selected = element.find('div.parent.ui-selected').map(function () {
var idx = $(this).index();
return { document: collection[idx] }
}).get();
scope.selectedItems = selected;
scope.$apply()
}
});
}
}
});
to use in html
<div class="margin-top-20px" ui-selectable doc-array="documents">
where documents is an array that get returned by server in ajax response.
its working fine i can select multiple items or single item
Issue: i want to clear selection on close button
http://plnkr.co/edit/3cSef9h7MeYSM0cgYUIX?p=preview
i can write jquery in controller to remove .ui-selected class but its not recommended approach
can some one guide me whats the best practice to achieve these type of issue
Update:
i fixed the issue by broadcasting event on cancel and listening it on directive
$scope.clearSelection=function() {
$scope.selectedItems = [];
$timeout(function () {
$rootScope.$broadcast('clearselection', '');
}, 100);
}
and in directive
scope.$on('clearselection', function (event, document) {
element.find('.ui-selected').removeClass('ui-selected')
});
is this the right way of doing it or what is the best practice to solve the issue.
http://plnkr.co/edit/3cSef9h7MeYSM0cgYUIX?p=preview
By default the jQuery U Autocomplete produces a list of results, upon clicking on a result it will populate the text field with the clicked result text.
I would like to change this behaviour, so that when clicking on a result it will take you to that result's page. To generate the hyperlink I can pass in the ID of the result.
I'm using PHP JSON to bring back the resultset:
$return_arr = array();
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['id'] = $row['id'];
$row_array['value'] = $row['name'];
array_push($return_arr, $row_array);
}
echo json_encode($return_arr);
And here is my current jQuery:
$(function() {
$("#searchcompany").autocomplete( {
source: "companies.php",
minLength: 2
});
});
Think you need to hook into the select event and supply your own function.
See here for more information.
Supply a callback function to handle the select event as an init option.
$("#searchcompany").autocomplete( {
source: "companies.php",
minLength: 2,
select: function(event,ui) { //Do your code here...
event.preventDefault();
}
});
or Bind to the select event by type: autocompleteselect.
$( "#searchcompany" ).bind( "autocompleteselect", function(event, ui) {
...
});
and to change the matching items to include a hyperlink that can be clicked use the Open event :-
open: function(event, ui) { $( 'li.ui-menu-item a').each( function() {
var el = $(this);
el.attr('href', el.html());
}
); }
This will add an href="[item value]" to each <a> element.
Edit: The code below will allow you to use the open event to change the items to include a href so they show the link in the window and when clicked they will take you to the specified location :-
open: function(event, ui) {
$("ul.ui-autocomplete").unbind("click");
var data = $(this).data("autocomplete");
for(var i=0; i<=data.options.source.length-1;i++)
{
var s = data.options.source[i];
$("li.ui-menu-item a:contains(" + s.value + ")").attr("href", "directory/listing/" + s.id);
}
}
Using this also means that you don't need to use the select event.