How to make "jQuery UI tab" blink/ flash - jquery-ui

I want to make "jQuery UI TAB" blink (like notification).
I have diffrent tabs (Inbox | Sent | Important). My timer function checks if there is a new message in inbox, if so, I want the Inbox tab to start blinking/ flashing unless its clicked open.
Have tried diffrent options like .effect(..), .tabs(fx: {..}) but nothing seems to work :(
Any idea if its possible or not?

Yes it's definitely possible.
To give me some practice, I've written a jQuery blinker plugin for you:
jQuery:
(function($){
// **********************************
// ***** Start: Private Members *****
var pluginName = 'blinker';
var blinkMain = function(data){
var that = this;
this.css(data.settings.css_1);
clearTimeout(data.timeout);
data.timeout = setTimeout(function(){
that.css(data.settings.css_0);
}, data.settings.cycle * data.settings.ratio);
};
// ***** Fin: Private Members *****
// ********************************
// *********************************
// ***** Start: Public Methods *****
var methods = {
init : function(options) {
//"this" is a jquery object on which this plugin has been invoked.
return this.each(function(index){
var $this = $(this);
var data = $this.data(pluginName);
// If the plugin hasn't been initialized yet
if (!data){
var settings = {
css_0: {
color: $this.css('color'),
backgroundColor: $this.css('backgroundColor')
},
css_1: {
color: '#000',
backgroundColor: '#F90'
},
cycle: 2000,
ratio: 0.5
};
if(options) { $.extend(true, settings, options); }
$this.data(pluginName, {
target : $this,
settings: settings,
interval: null,
timeout: null,
blinking: false
});
}
});
},
start: function(){
return this.each(function(index){
var $this = $(this);
var data = $this.data(pluginName);
if(!data.blinking){
blinkMain.call($this, data);
data.interval = setInterval(function(){
blinkMain.call($this, data);
}, data.settings.cycle);
data.blinking = true;
}
});
},
stop: function(){
return this.each(function(index){
var $this = $(this);
var data = $this.data(pluginName);
clearInterval(data.interval);
clearTimeout(data.timeout);
data.blinking = false;
this.style = '';
});
}
};
// ***** Fin: Public Methods *****
// *******************************
// *****************************
// ***** Start: Supervisor *****
$.fn[pluginName] = function( method ) {
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || !method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist in jQuery.' + pluginName );
}
};
// ***** Fin: Supervisor *****
// ***************************
})( jQuery );
See it in action here
The plugin and the fiddle are pretty raw in that I haven't tried to integrate with jQuery-ui-tabs. This may be easy or hard, I don't know, but providing each tab is addressable by class or id then it shouldn't be too difficult.
Something you may need to consider is stopping a blinking tab when it is clicked. For this you may wish to call the .blinker('stop') method directly (with a .on('click') handler) or from an appropriate jQuery-ui-tabs callback.
API
The plugin is properly written in jQuery's preferred pattern. It puts just one member in the jQuery.fn namespace and .blinker(...) will chain like standard jQuery methods.
Methods :
.blinker('init' [,options]) : Initialises selected element(s) with blinker behaviour. Called automatically with .blinker(options), or just .blinker() in its simplest form.
.blinker('start') : causes selected element(s) to start blinking between two styles as determined by plugin defaults and/or options.
.blinker('stop') : causes selected element(s) to stop blinking and return to their natural CSS style(s).
Options : a map of properties, which determine blinker styles and timing:
css_0 : (optional) a map of css properties representing the blink OFF-state.
css_1 : a map of CSS properties representing the blink ON-state.
cycle : the blink cycle time in milliseconds (default 2000).
ratio : ON time as a proportion of cycle time (default 0.5).
By omitting css_0 from the options map, the OFF state is determined by the element(s)' natural CSS styling defined elsewhere (typically in a stylesheet).
Default values are hard-coded for css_1.color, css_1.backgroundColor, cycle time and ratio. Changing the default settings programmatically is not handled, so for different default styling the plugin will need to be edited.

jQuery comes by default with a slew of effects to pick from. You can easily use them wherever you see the need for them and they can be applied like so:
$('#newmsg').effect("pulsate", {}, 1000);
Demo

yes... this is what you need...!!!
this is javascript
if(newmessage==true){
$('#chat-86de45de47-tab').effect("pulsate", {}, 1000);
}
i think it's

Related

Full-featured autocomplete widget for Dojo

As of now (Dojo 1.9.2) I haven't been able to find a Dojo autocomplete widget that would satisfy all of the following (typical) requirements:
Only executes a query to the server when a predefined number of characters have been entered (without this, big datasets should not be queried)
Does not require a full REST service on the server, only a URL which can be parametrized with a search term and simply returns JSON objects containing an ID and a label to display (so the data-query to the database can be limited just to the required data fields, not loading full data-entities and use only one field thereafter)
Has a configurable time-delay between the key-releases and the start of the server-query (without this excessive number of queries are fired against the server)
Capable of recognizing when there is no need for a new server-query (since the previously executed query is more generic than the current one would be).
Dropdown-stlye (has GUI elements indicating that this is a selector field)
I have created a draft solution (see below), please advise if you have a simpler, better solution to the above requirements with Dojo > 1.9.
The AutoComplete widget as a Dojo AMD module (placed into /gefc/dijit/AutoComplete.js according to AMD rules):
//
// AutoComplete style widget which works together with an ItemFileReadStore
//
// It will re-query the server whenever necessary.
//
define([
"dojo/_base/declare",
"dijit/form/FilteringSelect"
],
function(declare, _FilteringSelect) {
return declare(
[_FilteringSelect], {
// minimum number of input characters to trigger search
minKeyCount: 2,
// the term for which we have queried the server for the last time
lastServerQueryTerm: null,
// The query URL which will be set on the store when a server query
// is needed
queryURL: null,
//------------------------------------------------------------------------
postCreate: function() {
this.inherited(arguments);
// Setting defaults
if (this.searchDelay == null)
this.searchDelay = 500;
if (this.searchAttr == null)
this.searchAttr = "label";
if (this.autoComplete == null)
this.autoComplete = true;
if (this.minKeyCount == null)
this.minKeyCount = 2;
},
escapeRegExp: function (str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
},
replaceAll: function (find, replace, str) {
return str.replace(new RegExp(this.escapeRegExp(find), 'g'), replace);
},
startsWith: function (longStr, shortStr) {
return (longStr.match("^" + shortStr) == shortStr)
},
// override search method, count the input length
_startSearch: function (/*String*/ key) {
// If there is not enough text entered, we won't start querying
if (!key || key.length < this.minKeyCount) {
this.closeDropDown();
return;
}
// Deciding if the server needs to be queried
var serverQueryNeeded = false;
if (this.lastServerQueryTerm == null)
serverQueryNeeded = true;
else if (!this.startsWith(key, this.lastServerQueryTerm)) {
// the key does not start with the server queryterm
serverQueryNeeded = true;
}
if (serverQueryNeeded) {
// Creating a query url templated with the autocomplete term
var url = this.replaceAll('${autoCompleteTerm}', key, this.queryURL);
this.store.url = url
// We need to close the store in order to allow the FilteringSelect
// to re-open it with the new query term
this.store.close();
this.lastServerQueryTerm = key;
}
// Calling the super start search
this.inherited(arguments);
}
}
);
});
Notes:
I included some string functions to make it standalone, these should go to their proper places in your JS library.
The JavaScript embedded into the page which uses teh AutoComplete widget:
require([
"dojo/ready",
"dojo/data/ItemFileReadStore",
"gefc/dijit/AutoComplete",
"dojo/parser"
],
function(ready, ItemFileReadStore, AutoComplete) {
ready(function() {
// The initially displayed data (current value, possibly null)
// This makes it possible that the widget does not fire a query against
// the server immediately after initialization for getting a label for
// its current value
var dt = null;
<g:if test="${tenantInstance.technicalContact != null}">
dt = {identifier:"id", items:[
{id: "${tenantInstance.technicalContact.id}",
label:"${tenantInstance.technicalContact.name}"
}
]};
</g:if>
// If there is no current value, this will have no data
var partnerStore = new ItemFileReadStore(
{ data: dt,
urlPreventCache: true,
clearOnClose: true
}
);
var partnerSelect = new AutoComplete({
id: "technicalContactAC",
name: "technicalContact.id",
value: "${tenantInstance?.technicalContact?.id}",
displayValue: "${tenantInstance?.technicalContact?.name}",
queryURL: '<g:createLink controller="partner"
action="listForAutoComplete"
absolute="true"/>?term=\$\{autoCompleteTerm\}',
store: partnerStore,
searchAttr: "label",
autoComplete: true
},
"technicalContactAC"
);
})
})
Notes:
This is not standalone JavaScript, but generated with Grails on the server side, thus you see <g:if... and other server-side markup in the code). Replace those sections with your own markup.
<g:createLink will result in something like this after server-side page generation: /Limes/partner/listForAutoComplete?term=${autoCompleteTerm}
As of dojo 1.9, I would start by recommending that you replace your ItemFileReadStore by a store from the dojo/store package.
Then, I think dijit/form/FilteringSelect already has the features you need.
Given your requirement to avoid a server round-trip at the initial page startup, I would setup 2 different stores :
a dojo/store/Memory that would handle your initial data.
a dojo/store/JsonRest that queries your controller on subsequent requests.
Then, to avoid querying the server at each keystroke, set the FilteringSelect's intermediateChanges property to false, and implement your logic in the onChange extension point.
For the requirement of triggering the server call after a delay, implement that in the onChange as well. In the following example I did a simple setTimeout, but you should consider writing a better debounce method. See this blog post and the utility functions of dgrid.
I would do this in your GSP page :
require(["dojo/store/Memory", "dojo/store/JsonRest", "dijit/form/FilteringSelect", "dojo/_base/lang"],
function(Memory, JsonRest, FilteringSelect, lang) {
var initialPartnerStore = undefined;
<g:if test="${tenantInstance.technicalContact != null}">
dt = {identifier:"id", items:[
{id: "${tenantInstance.technicalContact.id}",
label:"${tenantInstance.technicalContact.name}"
}
]};
initialPartnerStore = new Memory({
data : dt
});
</g:if>
var partnerStore = new JsonRest({
target : '<g:createLink controller="partner" action="listForAutoComplete" absolute="true"/>',
});
var queryDelay = 500;
var select = new FilteringSelect({
id: "technicalContactAC",
name: "technicalContact.id",
value: "${tenantInstance?.technicalContact?.id}",
displayValue: "${tenantInstance?.technicalContact?.name}",
store: initialPartnerStore ? initialPartnerStore : partnerStore,
query : { term : ${autoCompleteTerm} },
searchAttr: "label",
autoComplete: true,
intermediateChanges : false,
onChange : function(newValue) {
// Change to the JsonRest store to query the server
if (this.store !== partnerStore) {
this.set("store", partnerStore);
}
// Only query after your desired delay
setTimeout(lang.hitch(this, function(){
this.set('query', { term : newValue }
}), queryDelay);
}
}).startup();
});
This code is untested, but you get the idea...

Knockout bindings are not working with jsTree

I'm trying to get jsTree (1.0-rc3) working with Knockout.js (2.2.1).
See example jsFiddle: http://jsfiddle.net/adeconsulting/qfr6A/
Note: I've included several JS resources in the Fiddle to match as close as possible my Visual Studio project, in case there's a conflict between libraries which might be causing this problem.
Run the Fiddle and navigate through the jsTree, it's a list of servers by their physical location and type. It helps to have Firebug's console open so you can see the ajax calls and responses. When you click a leaf node, an ajax call is made to retrieve the server details and display a form whose values use Knockout bindings. I hide the form when a non-leaf node is selected.
It works the first time you click a leaf node. After that, Knockout does not update the form for leaf node clicks. However, if you happen to click the Edit button, then all of a sudden the most recent server details ARE displayed.
I'm thinking that there's a conflict between jsTree and Knockout bindings, but don't know where to start troubleshooting what that might be.
Since stackoverflow apparently requires at least one code block, here's the JavaScript portion of the Fiddle:
// Global vars:
var prevJsTreeNodeId = null;
var serverModelBindingsApplied = false;
var serverLoadInProgress = false;
/*
* The knockout.js view model
*/
var ServerViewModel = function () {
// Data
var self = this;
self.IsReadOnly = ko.observable(true); // the form's input mode
self.btnEditSave = ko.observable("Edit"); // the Edit/Save button text
self.Server = ko.observable({}); // the Server object
// Operations
self.setEditable = function () {
self.IsReadOnly(false);
self.btnEditSave("Save");
};
self.setReadOnly = function () {
self.IsReadOnly(true);
self.btnEditSave("Edit");
};
self.doEditSave = function () {
var flag = self.IsReadOnly();
if (flag) {
// switch to Edit mode
self.setEditable();
}
else {
// switch back to readOnly
self.setReadOnly();
}
};
// use ajax to update the knockout.js view model's Server object for the specified server name
self.load = function (serverName) {
if (!serverLoadInProgress) {
serverLoadInProgress = true;
// use ajax to retrieve the server's details
var data = {
json: JSON.stringify({
ServerName: serverName,
PrimaryIP: "1.2.3.4",
BrandDesc: "Dell",
OSDesc: "Windows 2003 Server",
Location: "xyz"
}),
delay: 1
};
$.ajax({
url:"/echo/json/",
data:data,
type:"POST",
success:function(response)
{
console.log(response);
window.ServerViewModelInstance.Server = ko.mapping.fromJS(response);
// apply bindings the first time we retrieve a Server object
if (!serverModelBindingsApplied) {
ko.applyBindings(window.ServerViewModelInstance,
document.getElementById('servercontent'));
serverModelBindingsApplied = true;
}
else {
// hmmm... updating the view model's .Server property doesn't trigger the
// form to be updated, yet if we click the Edit button, the new values
// suddenly appear, so try emulating that here...
self.setReadOnly();
}
}
});
serverLoadInProgress = false;
}
};
}; // ServerViewModel
/*
* document load
*/
$(function () {
// configure the jsTree
$("#divtree")
.jstree({
"themes": { "theme": "default", "dots": true, "icons": true },
"plugins": ["themes", "html_data", "ui", "types"],
"types": {
"type_attr": "tag", // the attribute which contains the type name
"max_depth": -2, // disable depth check
"max_children": -2, // disable max children check
"valid_children": ["root"],
"types": {
"root": {
"valid_children": ["level1"]
},
"level1": {
"valid_children": ["level2"],
"start_drag": false,
"move_node": false,
"delete_node": false,
"remove": false
},
"level2": {
"valid_children": ["leaf"],
// use the theme icon for the level2 nodes
"start_drag": false,
"move_node": false,
"delete_node": false,
"remove": false
},
"leaf": {
"valid_children": "none"
}
}
}
});
// register to receive notifications from #divtree when a jsTree node is selected
$("#divtree").bind("select_node.jstree", function (event, data) {
// data.rslt.obj is the jquery extended node that was clicked
var key = data.rslt.obj.attr("key");
var id = data.rslt.obj.attr("id");
if (id == prevJsTreeNodeId) {
// user clicked the same node, nothing to do
return;
}
prevJsTreeNodeId = id;
// when a jsTree node is selected, reset the knockout.js view model to read only
window.ServerViewModelInstance.setReadOnly();
var idx = key.indexOf("Server");
if (idx === 0) { // "Server|servername"
// show the "servercontent" div
$("#servercontent").show();
// display the server details
var serverName = key.substr(idx + 7, key.length);
window.ServerViewModelInstance.load(serverName);
}
else {
// hide the "servercontent" div
$("#servercontent").hide();
}
});
// hide the "servercontent" div
$("#servercontent").hide();
// instantiate the knockout.js view model
window.ServerViewModelInstance = new ServerViewModel();
}); // document ready
// initialization timer routine to select the main jsTree node
setTimeout(function () {
// open the root node
$.jstree._reference("#divtree").open_node("#root");
}, 500);
Sorry for my bad formatting below - this editor is not my friend... :-/
If I understand you right, the detail panel for a clicked tree node isn't updated with the correct data - right?
Try to do the following:
change:
window.ServerViewModelInstance.Server = ko.mapping.fromJS(response);
to: window.ServerViewModelInstance.Server(response);
(e.g. not overwriting the initial ko.observable which you only binds once, instead updating its values)
and in view where you bind to the observables..
for instance instead of: ... "value: Server.ServerName, ...
change it to: ... "value: Server().ServerName, ...
(e.g executing the function before accessing the property)
It works and updates the form when clicking on a new server name node in the tree (tried in firefox)
A copy of your example with the modified code can be found at: http://jsfiddle.net/RZ92g/2/

Single EmberView doing resizable() and draggable()

As per answer of the question Ember.js draggable and droppable jqueryUI / native Drag and drop mixin.
I have implemented JQUERY UI drag, drop, resize mixins in EmberJS. But my problem is i want the same view to do drag and resize. I tried to implement in different ways. You can check in this jsfiddle http://jsfiddle.net/codejack/TGwxf/1/ The view gets UI behaviour of last called mixin only.
Is there any way to get more than 1 behaviour in drag,drop,resize for same view?
EDIT I found out the reason is the 2nd mixin overrides the uievents,uiOptions,uiType variables. But still dont know how to avoid that... only way i can see is writing own Widgets with own events...any way to solve that?
Though the #user1128571 gave a solution which partly solves the problem, here is how i corrected the issue. I added different mixins for Interactions as that will solve the problem.
https://github.com/thecodejack/jquery-ui-ember/blob/master/js/app.js#L104
check the github pages of the module to know how exactly it works
You might want the JQ.Widget to look like this, warning it's not pretty:
Here, JQ.UiBase is the same thing as JQ.Widget
JQ.UiBase = Ember.Mixin.create({
uiWidgets: {},
uiAttributes: {},
// ----------------------------------------------------------------------------
// setup and teardown
didInsertElement: function(){
this._super();
this._createUiWidgets();
},
willDestroyElement: function(){
this._super();
// implement tear down
},
// ----------------------------------------------------------------------------
// #Private
// #Function: for each $.ui specified in the view, create a $.ui widget
// add ui widgets to uiWidgets hash, ui widget setting to uiAttributes hash
_createUiWidgets: function(){
var widgetTypes = this._gatherWidgetTypes();
uiWidgets = this.get('uiWidgets'),
uiAttributes = this.get('uiAttributes'),
thisView = this;
widgetTypes.forEach( function( widget ){
var options = thisView.get( widget + 'Options' ) || {},
handlers = thisView._registerEventHandlers( widget ),
attributes = $.extend( options, handlers ),
uiWidget = $.ui[widget]( attributes, thisView.$() );
uiWidgets[widget] = uiWidget;
uiAttributes[widget] = attributes;
});
},
// #Function: collects named $.ui events from Widget mixin
// for each event, if there is an associated callback, wrap it in a function and call the view's context
// #Return: a hash map $.ui event to callback function defined in view
_registerEventHandlers: function( widget_name ){
var widgetName = widget_name + 'Events',
events = this.get( widgetName ) || [],
thisView = this,
eventHandlers = {};
if ( events.length === 0 ) return;
// note the iterator is not scoped to the view
events.forEach( function( event ){
var callBack = thisView.get( event );
if ( callBack ){
eventHandlers[ event ] = function ( event, ui ){ callBack.call( thisView, event, ui ); };
};
});
return eventHandlers;
},
// TODO --> find alternate implementation that does not break if structure of ui mixins or namespace change
_gatherWidgetTypes: function() {
var nameSpace = 'JQ',
widgetTypes = [];
Ember.Mixin.mixins(this).forEach( function( mixin ){
// find widget with correct namespace
if ( mixin.toString().substring(0,2) === nameSpace ){
// console.log( 'gather: ', mixin, ' --> ', mixin.mixins[1] )
// access widget mixin and check widget mixin have properties
if ( mixin.mixins && mixin.mixins[1] && mixin.mixins[1].properties ){
if ( mixin.mixins[1].properties.widgetType ) widgetTypes.push( mixin.mixins[1].properties.widgetType)
}
}
});
return widgetTypes;
},
});
And then your resizable mixin would look like this:
JQ.Resizable = Ember.Mixin.create( JQ.UiBase, {
widgetType: 'resizable',
resizableOptions: { 'aspectRatio': 1/1 },
resizableEvents: [ 'resize' ],
resize: function( event, ui ){
// do stuff
},
});
The most important function here is the _gatherWidgetTypes, which gathers all JQ-namespaced mixins in the ember object. In my opinion, it's bit of a hack and I ended up not using the JQ.UiBase after making it, favoring to mix logic to create the widget and specifying the event handlers and options into one mixin, which ended up looking cleaner, but that's just me.

How to get static information about page transition ended [duplicate]

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 :)

keep dynamically added elements after postback

i got a big problem with jquery and the postback.
i'm dynamically adding html elements to my page. e.g. JQuery UI Tabs.
but after postback ALL dynamically added elements are gone.
how can i keep all of these elements after postback and also the values of textboxes and datetimepicker?
greetz
Tobi
EDIT:
e.g. i'm adding some JqueryUI Tabs with this code:
$(function () {
var $tab_title_input = $("#tab_title"),
$tab_content_input = $("#tab_content");
var tab_counter = 1;
var $addButton = $('<li class="ui-state-default ui-corner-top add-button"><span>+</span></li>');
$addButton.click(function () { addTab(); });
var $tabs = $("#tabsTravel, #tabsWork").tabs({ autoHeight: true, fillSpace: true,
tabTemplate: "<li><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close'>Remove Tab</span></li>",
add: function (event, ui) {
var tab_content = $tab_content_input.val() || "Tab " + tab_counter + " content.";
$(ui.panel).append("<p>" + tab_content + "</p>");
$("#tabsTravel ul.ui-tabs-nav").append($addButton);
}
});
$("#tabsTravel ul.ui-tabs-nav").append($addButton);
// actual addTab function
function addTab() {
tab_counter++;
var tab_title = "worker " + tab_counter;
$tabs.tabs("add", "#tabsTravel-" + tab_counter, tab_title)
.tabs("select", "#tabsWork-" + tab_counter, tab_title);
}
// close icon: removing the tab on click
$("#tabsTravel span.ui-icon-close").live("click", function () {
var index = $("li", $tabs).index($(this).parent());
$tabs.tabs("remove", index);
tab_counter--;
});
$("#tabsWork span.ui-icon-close").live("click", function () {
var index = $("li", $tabs).index($(this).parent());
$tabs.tabs("remove", index);
// tab_counter--;
});
$('#button').click(function () {
addTab()
});
});
how can i implement this localStorage to this code?
greetz
Bl!tz
Normally this would be the job of your server-side code; you would save the added elements in the the session cache, or in the database if the changes need to be permanent.
You could also consider using the new HTML5 session storage, or local storage, but this approach will probably be more of a hassle; best to use the sophisticated server-side libraries of PHP, .NET, etc, if possible.
Edit
Here's a simple example. Let's say your client script adds some HTML to the page:
var html = "<div>hello world</div>";
$("body").append(html);
Now, you can save it in local storage like this:
localStorage.setItem("dynamichtml", html);
If you put something in your page startup script like this:
$(document).ready(function() {
if (localStorage["dynamichtml"]) {
$("body").append(localStorage["dynamichtml"]);
}
});
Then you will have achieved the dynamic functionality. Note that the localStorage data will remain saved until the user deletes it explicitly.

Resources