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.
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
On page 1, when ajax loading to page 2, I need to get the [data-role=page] element of page 2,
but on pageinit(or pagecreate), the $.mobile.activePage is still page 1.
How to get the newly loaded page instead of the current page on pageinit?
$(document).on('pageinit', function () {
console.log($.mobile.activePage); // page 1
});
If you want to retrieve it one time only, then use pagecreate because it fires once per page and it fires before navigation is commenced.
$(document).on("pagecreate", function (e) {
if ( $(e.target).hasClass("ui-dialog") ) {
var dialog = $(e.target);
}
});
To retrieve it every time you navigate to it, you can use othe pageContainer events. In case you want to alter the page you're nacigating to, use pagecobtainerbeforechange.
$(document).on("pagecintainerbeforechange", function (e, data) {
if ( typeof data.toPage == "object" && typeof data.prevPage != "undefined" && data.toPage.hasClass("ui-dialog") ) {
data.toPage.find(".foo").addClass(".bar");
}
});
For other events in case you just want to access dialog and manipulate its markup.
$(document).on("pagecontainerbeforeshow pagecontainershow", function (e, data) {
if ( data.toPage.hasClass("ui-dialog") ) {
var dialog = data.toPage;
/* do something */
});
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,
}
Are there any events fired by an element to check whether a css3 transition has started or end?
W3C CSS Transitions Draft
The completion of a CSS Transition generates a corresponding DOM Event. An event is fired for each property that undergoes a transition. This allows a content developer to perform actions that synchronize with the completion of a transition.
Webkit
To determine when a transition completes, set a JavaScript event listener function for the DOM event that is sent at the end of a transition. The event is an instance of WebKitTransitionEvent, and its type is webkitTransitionEnd.
box.addEventListener( 'webkitTransitionEnd',
function( event ) { alert( "Finished transition!" ); }, false );
Mozilla
There is a single event that is fired when transitions complete. In Firefox, the event is transitionend, in Opera, oTransitionEnd, and in WebKit it is webkitTransitionEnd.
Opera
There is one type of transition event
available. The oTransitionEnd event
occurs at the completion of the
transition.
Internet Explorer
The transitionend event occurs at the completion of the transition. If the transition is removed before completion, the event will not fire.
Stack Overflow: How do I normalize CSS3 Transition functions across browsers?
Update
All modern browsers now support the unprefixed event:
element.addEventListener('transitionend', callback, false);
https://caniuse.com/#feat=css-transitions
I was using the approach given by Pete, however I have now started using the following
$(".myClass").one('transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd',
function() {
//do something
});
Alternatively if you use bootstrap then you can simply do
$(".myClass").one($.support.transition.end,
function() {
//do something
});
This is becuase they include the following in bootstrap.js
+function ($) {
'use strict';
// CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
// ============================================================
function transitionEnd() {
var el = document.createElement('bootstrap')
var transEndEventNames = {
'WebkitTransition' : 'webkitTransitionEnd',
'MozTransition' : 'transitionend',
'OTransition' : 'oTransitionEnd otransitionend',
'transition' : 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return { end: transEndEventNames[name] }
}
}
return false // explicit for ie8 ( ._.)
}
$(function () {
$.support.transition = transitionEnd()
})
}(jQuery);
Note they also include an emulateTransitionEnd function which may be needed to ensure a callback always occurs.
// http://blog.alexmaccaw.com/css-transitions
$.fn.emulateTransitionEnd = function (duration) {
var called = false, $el = this
$(this).one($.support.transition.end, function () { called = true })
var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
setTimeout(callback, duration)
return this
}
Be aware that sometimes this event doesn’t fire, usually in the case
when properties don’t change or a paint isn’t triggered. To ensure we
always get a callback, let’s set a timeout that’ll trigger the event
manually.
http://blog.alexmaccaw.com/css-transitions
All modern browsers now support the unprefixed event:
element.addEventListener('transitionend', callback, false);
Works in the latest versions of Chrome, Firefox and Safari. Even IE10+.
In Opera 12 when you bind using the plain JavaScript, 'oTransitionEnd' will work:
document.addEventListener("oTransitionEnd", function(){
alert("Transition Ended");
});
however if you bind through jQuery, you need to use 'otransitionend'
$(document).bind("otransitionend", function(){
alert("Transition Ended");
});
In case you are using Modernizr or bootstrap-transition.js you can simply do a change:
var transEndEventNames = {
'WebkitTransition' : 'webkitTransitionEnd',
'MozTransition' : 'transitionend',
'OTransition' : 'oTransitionEnd otransitionend',
'msTransition' : 'MSTransitionEnd',
'transition' : 'transitionend'
},
transEndEventName = transEndEventNames[ Modernizr.prefixed('transition') ];
You can find some info here as well http://www.ianlunn.co.uk/blog/articles/opera-12-otransitionend-bugs-and-workarounds/
Just for fun, don't do this!
$.fn.transitiondone = function () {
return this.each(function () {
var $this = $(this);
setTimeout(function () {
$this.trigger('transitiondone');
}, (parseFloat($this.css('transitionDelay')) + parseFloat($this.css('transitionDuration'))) * 1000);
});
};
$('div').on('mousedown', function (e) {
$(this).addClass('bounce').transitiondone();
});
$('div').on('transitiondone', function () {
$(this).removeClass('bounce');
});
If you simply want to detect only a single transition end, without using any JS framework here's a little convenient utility function:
function once = function(object,event,callback){
var handle={};
var eventNames=event.split(" ");
var cbWrapper=function(){
eventNames.forEach(function(e){
object.removeEventListener(e,cbWrapper, false );
});
callback.apply(this,arguments);
};
eventNames.forEach(function(e){
object.addEventListener(e,cbWrapper,false);
});
handle.cancel=function(){
eventNames.forEach(function(e){
object.removeEventListener(e,cbWrapper, false );
});
};
return handle;
};
Usage:
var handler = once(document.querySelector('#myElement'), 'transitionend', function(){
//do something
});
then if you wish to cancel at some point you can still do it with
handler.cancel();
It's good for other event usages as well :)
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.