Bind function in jQuery plugin function - javascript

I'm trying to implement an infinite scroll in a div with filtering option, as well, filtering should work when user stops typing in the box.
Html:
<div class="span2" style="margin-top: 50px;">
<input id="Search" class="input-mysize" />
<div id="listNav" style="height: 370px; border: 1px solid; overflow: auto; margin-right: 20px; width: 90%;">
</div>
</div>
JS in Html:
$(function() {
function onSuccess(row, container) {
container.append('<div style="border:1px solid; cursor: hand; cursor: pointer;" >' +
'<table border="0">' +
'<tr>' +
'<td id="Location' + row.Id + '">'+
'<b>Name: </b>' + row.Name + '</br >' + '<b>Address: </b>' + row.Address + '' +
'</td>' +
'<td onclick="locationDetails(' + row.Id + ')"> > </td>' +
'</tr>' +
'</table>' +
'</div>');
var tdId = "Location" + row.Id;
var element = $('#' + tdId);
$(element).click(function() {
google.maps.event.trigger(arrMarkers[row.Id], 'click');
});
};
//...
$('#listNav').empty();
$('#listNav').jScroller("/Dashboard/GetClients", {
numberOfRowsToRetrieve: 7,
onSuccessCallback: onSuccess,
onErrorCallback: function () {
alert("error");
}
});
//...
$('#Search').keyup(function(){
clearTimeout(typingTimer);
if ($('#myInput').val) {
typingTimer = setTimeout(doneTyping, doneTypingInterval);
}
});
function doneTyping () {
startInt = startInt + 5;
$('#listNav').empty();
$('#listNav').unbind();
$('#listNav').jScroller("/Dashboard/GetClients", {
numberOfRowsToRetrieve: 7,
start : startInt,
locationFilter: $('#Search').val(),
onSuccessCallback: onSuccess,
onErrorCallback: function () {
alert("error");
}
});
};
});
rest of JS (based on jScroller plug in):
(function ($) {
"use strict";
jQuery.fn.jScroller = function (store, parameters) {
var defaults = {
numberOfRowsToRetrieve: 10,
locationFilter: '',
onSuccessCallback: function (row, container) { },
onErrorCallback: function (thrownError) { window.alert('An error occurred while trying to retrive data from store'); },
onTimeOutCallback: function () { },
timeOut: 3 * 1000,
autoIncreaseTimeOut: 1000,
retryOnTimeOut: false,
loadingButtonText: 'Loading...',
loadMoreButtonText: 'Load more',
fullListText: 'There is no more items to show',
extraParams: null
};
var options = jQuery.extend(defaults, parameters);
var list = jQuery(this),
end = false,
loadingByScroll = true;
var ajaxParameters;
if (options.extraParams === null) {
ajaxParameters = {
start: 0,
numberOfRowsToRetrieve: options.numberOfRowsToRetrieve,
locationFilter: options.locationFilter
};
}
else {
ajaxParameters = {
start: 0,
numberOfRowsToRetrieve: options.numberOfRowsToRetrieve,
locationFilter: option.locationFilter,
extraParams: options.extraParams
};
}
list.html('');
function loadItems() {
preLoad();
jQuery.ajax({
url: store,
type: "POST",
data: ajaxParameters,
timeOut: options.timeOut,
success: function (response) {
list.find("#jscroll-loading").remove();
if (response.Success === false) {
options.onErrorCallback(list, response.Message);
return;
}
for (var i = 0; i < response.data.length; i++) {
if (end === false) {
options.onSuccessCallback(response.data[i], list);
}
}
if (loadingByScroll === false) {
if (end === false) {
list.append('<div><a class="jscroll-loadmore">' + options.loadMoreButtonText + '</a></div>');
}
}
ajaxParameters.start = ajaxParameters.start + options.numberOfRowsToRetrieve;
if (ajaxParameters.start >= response.total) {
end = true;
list.find('#jscroll-fulllist').remove();
list.find(".jscroll-loadmore").parent("div").remove();
}
},
error: function (xhr, ajaxOptions, thrownError) {
if (thrownError === 'timeout') {
options.onTimeOutCallback();
if (options.retryOnTimeOut) {
options.timeOut = options.timeOut + (1 * options.autoIncreaseTimeOut);
loadItems();
}
}
else {
options.onErrorCallback(thrownError);
}
}
});
}
function preLoad() {
if (list.find("#jscroll-loading").length === 0) {
list.find(".jscroll-loadmore").parent("div").remove();
list.append('<a id="jscroll-loading">' + options.loadingButtonText + '</a>');
}
}
//called when doneTyping is called and first time page loaded
jQuery(document).ready(function () {
loadItems();
});
//called when user scrolls down in a div
$('#listNav').bind('scroll', function () {
if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
loadItems();
}
});
};
})(jQuery);
It's mostly working, but at some cases when user stops typing, the
jQuery(document).ready(function () {
loadItems();
});
and
$('#listNav').bind('scroll', function () {
if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
loadItems();
}
});
are both called instead of just first one, adding bad html to the div. Most cases only jQuery(document).ready is called, which is what i need.
As well why is jQuery(document).ready() is called every time the doneTyping() is called ? I though it should be called only the first time the page is loaded after DOM is ready.

I assume that your JS code in your HTML starts with a $(document).ready({}), so there would be no need to add $(document).ready({}) inside your plugin. Just call loadItems(); without the document ready event.

Related

fetch javascript input/output from google sheet

I have the code below on Apps script but keep getting 'ReferenceError: setInterval is not defined on line 17'. Not sure how to fix this but it does load when i use the scipt below in a cell in google sheets and set it up to output to another - it runs apart from that error. not sure if it's because i have it set up wrong or because google apps script doesn't like the code
function scart() {// ==UserScript==
setInterval(function() {
var possibleClasses = [".listenArtworkWrapper", ".listenInfo"],
sizes = { 't500x500': '500x500', 'original': 'original size' },
regexp = /t\d{3}x\d{3}/gi;
$('.modal__content:not(.appeared)')
.addClass('appeared')
.each(handleModal);
function handleModal() {
var imageURL;
for (var i = 0; i < possibleClasses.length; i++) {
if ($(possibleClasses[i] + " .image__full").length > 0) {
imageURL = $(possibleClasses[i] + " .image__full").css('background-image');
}
}
if (!imageURL) {
logError('No suitable selector found!');
} else {
imageURL = /url\("(.+)"\)/.exec(imageURL)[1];
}
$(".modal__content .image__full").parent().remove();
$(".modal__content .imageContent").append("<img style='width: 500px; height: 500px; margin-bottom: 15px;' src='" + imageURL.replace(regexp, 't500x500') + "'>");
Object.keys(sizes).forEach(function (size) {
var url = imageURL.replace(regexp, size);
$.ajax({
type: 'HEAD',
url: url,
complete: function(xhr) {
if (xhr.status !== 200) {
return;
}
$(".modal__content .imageContent").append(
makeButton(url, sizes[size])
);
}
});
});
}
function makeButton(url, sizeLabel) {
var $btn = $('<button />')
.css({ margin: '10px auto 0 auto', display: 'block', width: '100%'})
.attr('class', 'sc-button sc-button-medium sc-button-responsive')
.text('Download ' + sizeLabel);
$btn.on('click', function(e) {
e.preventDefault();
download(url);
});
return $btn;
}
function download(url) {
url = url.split('?')[0];
if (!url.startsWith('http')) {
url = window.location.protocol + (url.startsWith('//') ? '' : '//') + url;
}
var fileNameParts = url.split('/');
var fileName = fileNameParts[fileNameParts.length - 1];
var options = {
url: url,
name: fileName,
onerror: function (e) {
logError('Download failed. Reason: ' + e.error);
}
};
GM_download(options);
}
function logError(message) {
var details = {
title: GM_info.script.name,
text: message,
};
GM_notification(details);
console.error('%c' + GM_info.script.name + '%c: ' + message, 'font-weight: bold', 'font-weight: normal');
}
}, 250);
}
setInterval is not actually a function within Google App Script. You'll have to utilize the other built-in features. I typically use Utilities.sleep(timeout) to make this work. You can see more here.

Nested Javascript function

I have two javascript functions for pagination and truncate as follow:
<script type="text/javascript" src="//path/js/jquery.quick.pagination.min.js"></script>
$("#post_list").quickPagination({
pagerLocation:"both",
pageSize:"3"
});
<script type="text/javascript" language="javascript" src="//path/js/jquery.dotdotdot.js"></script>
$(".post_detail").dotdotdot({
after: 'a.more',
callback : function( isTruncated, orgContent ) {
if (!isTruncated) {
$('.more',this).remove()
}
},
});
Each runs fine onLoad. However, once the pagination function is fired, the truncate function does not run again.
Please see my jsfiddle and click page 2 to see the problem.
jsfiddle: http://jsfiddle.net/wr2ezv4f/1/
EDITED:
I managed to include the truncate function by adding it directly to the jquery.quick.pagination.min.js file (Please see the comment inside the js as folow (AND is working well):
(function($) {
"use strict";
$.fn.quickPagination = function(options) {
var defaults = {
pageSize: 10,
currentPage: 1,
holder: null,
pagerLocation: "after",
transitionSpeed: null
};
options = $.extend(defaults, options);
return this.each(function() {
var selector = $(this);
var pageCounter = 1;
if ($(".simplePagerContainer").length < 1) selector.wrap("<div class='simplePagerContainer'></div>");
selector.parents(".simplePagerContainer").find("ul.simplePagerNav").remove();
selector.children().removeClass(function(index, css) {
return (css.match(/simplePagerPage([0-9]+)?/ig) || []).join(' ');
}).filter(":visible").each(function(i) {
if (i < pageCounter * options.pageSize && i >= (pageCounter - 1) * options.pageSize) {
$(this).addClass("simplePagerPage" + pageCounter);
} else {
$(this).addClass("simplePagerPage" + (pageCounter + 1));
pageCounter++;
}
});
selector.children().hide();
selector.children(".simplePagerPage" + options.currentPage).show();
if (pageCounter <= 1) {
return;
}
var pageNav = "<ul class='simplePagerNav'>";
for (var i = 1; i <= pageCounter; i++) {
if (i == options.currentPage) {
pageNav += "<li class='page currentPage simplePageNav" + i + "'><a rel='" + i + "' href='#'>" + i + "</a></li>";
} else {
pageNav += "<li class='page simplePageNav" + i + "'><a rel='" + i + "' href='#'>" + i + "</a></li>";
}
}
pageNav += "</ul>";
if (!options.holder) {
switch (options.pagerLocation) {
case "before":
selector.before(pageNav);
break;
case "both":
selector.before(pageNav);
selector.after(pageNav);
break;
default:
selector.after(pageNav);
}
} else {
$(options.holder).append(pageNav);
}
selector.parent().find(".simplePagerNav a").click(function(e) {
e.preventDefault();
var clickedLink = $(this).attr("rel");
options.currentPage = clickedLink;
var container = options.holder ? options.holder : ".simplePagerContainer";
$(this).parents(container).find("li.currentPage").removeClass("currentPage");
$(this).parents(container).find("a[rel='" + clickedLink + "']").parent("li").addClass("currentPage");
selector.children().hide();
if (options.transitionSpeed) {
selector.find(".simplePagerPage" + clickedLink).fadeIn(options.transitionSpeed);
// ** I managed to include the truncate function here **//
$(".post_title").dotdotdot();
$(".post_detail").dotdotdot({
after: 'a.more',
callback : function( isTruncated, orgContent ) {
if (!isTruncated) {
$('.more',this).remove()
}
},
});
} else {
selector.find(".simplePagerPage" + clickedLink).show();
//** and to include the truncate function here **//
$(".post_title").dotdotdot();
$(".post_detail").dotdotdot({
after: 'a.more',
callback : function( isTruncated, orgContent ) {
if (!isTruncated) {
$('.more',this).remove()
}
},
});
}
return false;
});
});
};
})(jQuery);
My question now is, how can I modify this js file so that I can include this function outside the js file instead:
Something like:
$("#post_list").quickPagination({
pagerLocation:"both",
pageSize:"3"
// ** optional function I want to include here **/
});
You can write both function in a common function like this
$(function()
{
$("#post_list").quickPagination({
pagerLocation:"both",
pageSize:"3"
});
$(".post_title").dotdotdot();
$(".post_detail").dotdotdot({
after: 'a.more',
callback : function( isTruncated, orgContent ) {
if (!isTruncated) {
$('.more',this).remove()
}
},
});
});

JavaScript jQuery.post to get data from .php file in Firefox Extension

I'm trying to make a Firefox extension based on iNettuts widget interface:
Source 1
Source 2
My goal is to get the widget's content from the widgets_rpc.php file:
<?php
header("Cache-Control: no-cache");
header("Pragma: nocache");
$id=$_REQUEST["id"];
echo "<p>This is the content for <b>$id</b></p>";
switch ($id) {
case "widget1":
echo "<p>This is the content for widget #1</p>";
break;
case "widget2":
echo "<p>This is the content for widget #2</p>";
break;
case "widget3":
echo "<p>This is the content for widget #3</p>";
break;
default: echo "<p>OK</p>";
}
?>
Source JS:
/*
* Script from NETTUTS.com [modified by Mario Jimenez] V.3 (ENHANCED, WITH DATABASE, ADD WIDGETS FEATURE AND COOKIES OPTION!!!)
* #requires jQuery($), jQuery UI & sortable/draggable UI modules
*/
var ios = Components.classes["#mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
var cookieUri = ios.newURI("chrome://mystartpage/content/index.html", null, null);
var cookieSvc = Components.classes["#mozilla.org/cookieService;1"].getService(Components.interfaces.nsICookieService);
var cookieVal = " ";
var iNettuts = {
jQuery : $,
settings : {
columns : '.column',
widgetSelector: '.widget',
handleSelector: '.widget-head',
contentSelector: '.widget-content',
saveToDB: false,
cookieName: '',
widgetDefault : {
movable: true,
removable: true,
collapsible: true,
editable: true,
colorClasses: ['color-yellow', 'color-red', 'color-blue', 'color-white', 'color-orange', 'color-green'],
content: "<div align='center'><img src='/skin/img/load.gif' border='0' /></div>"
},
widgetIndividual : {
widget1 : {
movable: true,
removable: true,
collapsible: true,
editable: true,
mycontent: "asd"
}
}
},
init : function () {
this.attachStylesheet('/skin/inettuts.js.css');
$('body').css({background:'#000'});
$(this.settings.columns).css({visibility:'visible'});
this.sortWidgets();
//this.addWidgetControls();
//this.makeSortable();
},
initWidget : function (opt) {
if (!opt.content) opt.content=iNettuts.settings.widgetDefault.content;
return '<li id="'+opt.id+'" class="new widget '+opt.color+'"><div class="widget-head"><h3>'+opt.title+'</h3></div><div class="widget-content">'+opt.content+'</div></li>';
},
/*loadWidget : function(id) {
$.post("widgets_rpc.php", {"id":id},
function(data){
$("#"+id+" "+iNettuts.settings.contentSelector).html(data);
});
},*/
loadWidget : function(id) {
$.post("widgets_rpc.php", {"id":id},
function(data){
var thisWidgetSettings = iNettuts.getWidgetSettings(id);
if (thisWidgetSettings.mycontent) data+=thisWidgetSettings.mycontent;
$("#"+id+" "+iNettuts.settings.contentSelector).html(data);
});
},
addWidget : function (where, opt) {
$("li").removeClass("new");
var selectorOld = iNettuts.settings.widgetSelector;
iNettuts.settings.widgetSelector = '.new';
$(where).append(iNettuts.initWidget(opt));
iNettuts.addWidgetControls();
iNettuts.settings.widgetSelector = selectorOld;
iNettuts.makeSortable();
iNettuts.savePreferences();
iNettuts.loadWidget(opt.id);
},
getWidgetSettings : function (id) {
var $ = this.jQuery,
settings = this.settings;
return (id&&settings.widgetIndividual[id]) ? $.extend({},settings.widgetDefault,settings.widgetIndividual[id]) : settings.widgetDefault;
},
addWidgetControls : function () {
var iNettuts = this,
$ = this.jQuery,
settings = this.settings;
$(settings.widgetSelector, $(settings.columns)).each(function () {
var thisWidgetSettings = iNettuts.getWidgetSettings(this.id);
if (thisWidgetSettings.removable) {
$('CLOSE').mousedown(function (e) {
/* STOP event bubbling */
e.stopPropagation();
}).click(function () {
if(confirm('This widget will be removed, ok?')) {
$(this).parents(settings.widgetSelector).animate({
opacity: 0
},function () {
$(this).wrap('<div/>').parent().slideUp(function () {
$(this).remove();
iNettuts.savePreferences();
});
});
}
return false;
}).appendTo($(settings.handleSelector, this));
}
if (thisWidgetSettings.editable) {
$('EDIT').mousedown(function (e) {
/* STOP event bubbling */
e.stopPropagation();
}).toggle(function () {
$(this).css({backgroundPosition: '-66px 0', width: '55px'})
.parents(settings.widgetSelector)
.find('.edit-box').show().find('input').focus();
return false;
},function () {
$(this).css({backgroundPosition: '', width: '24px'})
.parents(settings.widgetSelector)
.find('.edit-box').hide();
return false;
}).appendTo($(settings.handleSelector,this));
$('<div class="edit-box" style="display:none;"/>')
.append('<ul><li class="item"><label>Change the title?</label><input value="' + $('h3',this).text() + '"/></li>')
.append((function(){
var colorList = '<li class="item"><label>Available colors:</label><ul class="colors">';
$(thisWidgetSettings.colorClasses).each(function () {
colorList += '<li class="' + this + '"/>';
});
return colorList + '</ul>';
})())
.append('</ul>')
.insertAfter($(settings.handleSelector,this));
}
if (thisWidgetSettings.collapsible) {
$('COLLAPSE').mousedown(function (e) {
/* STOP event bubbling */
e.stopPropagation();
}).click(function(){
$(this).parents(settings.widgetSelector).toggleClass('collapsed');
/* Save prefs to cookie: */
iNettuts.savePreferences();
return false;
}).prependTo($(settings.handleSelector,this));
}
});
$('.edit-box').each(function () {
$('input',this).keyup(function () {
$(this).parents(settings.widgetSelector).find('h3').text( $(this).val().length>20 ? $(this).val().substr(0,20)+'...' : $(this).val() );
iNettuts.savePreferences();
});
$('ul.colors li',this).click(function () {
var colorStylePattern = /\bcolor-[\w]{1,}\b/,
thisWidgetColorClass = $(this).parents(settings.widgetSelector).attr('class').match(colorStylePattern)
if (thisWidgetColorClass) {
$(this).parents(settings.widgetSelector)
.removeClass(thisWidgetColorClass[0])
.addClass($(this).attr('class').match(colorStylePattern)[0]);
/* Save prefs to cookie: */
iNettuts.savePreferences();
}
return false;
});
});
},
attachStylesheet : function (href) {
var $ = this.jQuery;
return $('<link href="' + href + '" rel="stylesheet" type="text/css" />').appendTo('head');
},
makeSortable : function () {
var iNettuts = this,
$ = this.jQuery,
settings = this.settings,
$sortableItems = (function () {
var notSortable = '';
$(settings.widgetSelector,$(settings.columns)).each(function (i) {
if (!iNettuts.getWidgetSettings(this.id).movable) {
if(!this.id) {
this.id = 'widget-no-id-' + i;
}
notSortable += '#' + this.id + ',';
}
});
if (notSortable=='')
return $("> li", settings.columns);
else
return $('> li:not(' + notSortable + ')', settings.columns);
})();
$sortableItems.find(settings.handleSelector).css({
cursor: 'move'
}).mousedown(function (e) {
$sortableItems.css({width:''});
$(this).parent().css({
width: $(this).parent().width() + 'px'
});
}).mouseup(function () {
if(!$(this).parent().hasClass('dragging')) {
$(this).parent().css({width:''});
} else {
$(settings.columns).sortable('disable');
}
});
$(settings.columns).sortable('destroy');
$(settings.columns).sortable({
items: $sortableItems,
connectWith: $(settings.columns),
handle: settings.handleSelector,
placeholder: 'widget-placeholder',
forcePlaceholderSize: true,
revert: 300,
delay: 100,
opacity: 0.8,
containment: 'document',
start: function (e,ui) {
$(ui.helper).addClass('dragging');
},
stop: function (e,ui) {
$(ui.item).css({width:''}).removeClass('dragging');
$(settings.columns).sortable('enable');
iNettuts.savePreferences();
}
});
},
savePreferences : function () {
var iNettuts = this,
$ = this.jQuery,
settings = this.settings,
cookieString = '';
/* Assemble the cookie string */
$(settings.columns).each(function(i){
cookieString += (i===0) ? '' : '|';
$(settings.widgetSelector,this).each(function(i){
cookieString += (i===0) ? '' : '&';
/* ID of widget: */
cookieString += $(this).attr('id') + ',';
/* Color of widget (color classes) */
cookieString += $(this).attr('class').match(/\bcolor-[\w]{1,}\b/) + ',';
/* Title of widget (replaced used characters) */
cookieString += $('h3:eq(0)',this).text().replace(/\|/g,'[-PIPE-]').replace(/,/g,'[-COMMA-]') + ',';
/* Collapsed/not collapsed widget? : */
cookieString += $(settings.contentSelector,this).css('display') === 'none' ? 'collapsed' : 'not-collapsed';
});
});
if(settings.saveToDB) {
/* AJAX call to store string on database */
$.post("iNettuts_rpc.php","value="+cookieString);
} else {
cookieSvc.setCookieString(cookieUri, null, "" + cookieString + ";expires=Thu, 31 Dec 2099 00:00:00 GMT", null);
}
},
sortWidgets : function () {
var iNettuts = this,
$ = this.jQuery,
settings = this.settings;
if (settings.saveToDB) {
$.post("iNettuts_rpc.php", "", this.processsSavedData);
} else {
var cookie = cookieSvc.getCookieString(cookieUri, null);
this.processsSavedData(cookie);
}
//$('body').css({background:'#000'});
//$(settings.columns).css({visibility:'visible'});
return;
},
processsSavedData : function (cookie) {
if (!cookie) {
$('body').css({background:'#000'});
$(iNettuts.settings.columns).css({visibility:'visible'});
iNettuts.addWidgetControls();
iNettuts.makeSortable();
return;
}
/* For each column */
$(iNettuts.settings.columns).each(function(i){
var thisColumn = $(this),
widgetData = cookie.split('|')[i].split('&');
$(widgetData).each(function(){
if(!this.length) {return;}
var thisWidgetData = this.split(','),
opt={
id: thisWidgetData[0],
color: thisWidgetData[1],
title: thisWidgetData[2].replace(/\[-PIPE-\]/g,'|').replace(/\[-COMMA-\]/g,','),
content: iNettuts.settings.widgetDefault.content
};
$(thisColumn).append(iNettuts.initWidget(opt));
if (thisWidgetData[3]==='collapsed') $('#'+thisWidgetData[0]).addClass('collapsed');
iNettuts.loadWidget(thisWidgetData[0]);
});
});
/* All done, remove loading gif and show columns: */
$('body').css({background:'#000'});
$(iNettuts.settings.columns).css({visibility:'visible'});
iNettuts.addWidgetControls();
iNettuts.makeSortable();
}
};
iNettuts.init();
At this moment the widget shows nothing. Please help.

Move a object (this case a ball) with acclerometer in JS and Cordova

I'm trying to move a ball with my accelerometer. But I'm stuck with getting the ball moved.
I get the values of the accelerometer, but how do I combine them with the ball so it can move?
Waiting for accelerometer...
<div id="heading">Waiting for heading...</div>
<div id="ball"></div>
<script src="cordova.js"></script>
<script src="static/js/app.js"></script>
#ball {
display: block;
border-radius: 50%;
width: 50px;
height: 50px;
background-color: rgb(0,0,0);
color: rgb(0,0,0);
}
//self-invoking anonymous function
(function () {
'use strict';
// The watch id references the current `watchAcceleration` & 'watchHeading'
var watchID = null;
// Initialize app with an controller object literal
var app = {
// init method, Cordova is ready to be used
init: function () {
accelerometer.begin();
compas.begin();
},
}
var accelerometer = {
begin: function () {
// Update acceleration every 100 of a second
var options = {
frequency: 100
};
watchID = navigator.accelerometer.watchAcceleration(this.success, debug.fail, options);
},
// Stop watching the acceleration
stop: function () {
if (watchID) {
navigator.accelerometer.clearWatch(watchID);
watchID = null;
}
},
// onSuccess: Get a snapshot of the current acceleration
success: function (acceleration) {
var element = document.getElementById('accelerometer');
element.innerHTML = 'Acceleration X: ' + acceleration.x + '<br />' +
'Acceleration Y: ' + acceleration.y + '<br />' +
'Acceleration Z: ' + acceleration.z + '<br />' +
'Timestamp: ' + acceleration.timestamp + '<br />';
}
}
var ball = {
object: function () {
var element = document.getElementById('ball');
},
update: function () {
game.clear();
newDX = accelerometer.begin.acceleration.x();
newDY = accelerometer.begin.acceleration.y();
newDX *= -5;
newDY *= -5;
object.setDX(newDX);
object.setDY(newDY);
ball.update();
}
}
var compas = {
begin: function () {
// Update acceleration every 100 of a second
var options = {
frequency: 100
};
watchID = navigator.compass.watchHeading(this.succes, debug.errormsg, options);
},
// Stop watching the heading
stop: function () {
if (watchID) {
navigator.compass.clearWatch(watchID);
watchID = null;
}
},
// onSuccess: Get a snapshot of the current heading
success: function (heading) {
var element = document.getElementById('heading');
element.innerHTML = 'Heading: ' + heading.magneticHeading;
}
}
var debug = {
fail: function () {
alert('onError!');
},
errormsg: function (compassError) {
alert('Compass error: ' + compassError.code);
}
}
document.addEventListener("deviceready", app.init, false);
})();
Try out this tutorial. It's pretty simple.
(note: change the phonegap.js to cordova.js)

multiple autocomplete dropdowns not working

When I have one autocomplete dropdown for one field everything works fine, however when I add more dropdowns for more fields the value of the input fields is no longer populated with the text of the li which is returned from the php file which is called
The following works where .sugnorm1 is the class of the li
var delay = (function () {
var timer = 0;
return function (callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
$(document).ready(function () {
$('#quality1').bind('input propertychange', function () {
delay(function () {
$.post("functions/autocomplete.php", {
quality:$(this).val(),
questionname:"<?php echo $_SESSION['question']; ?>",
count:1
}, function (response) {
$('#qualitySuggest1').hide();
setTimeout("finishAjax('qualitySuggest1', '" + escape(response) + "')", 20);
});
return false;
}, 20);
});
});
$('.sugnorm1').live("mouseover mouseout click", function(event) {
if ( event.type == "mouseover" ) {
$(this).addClass('sughover');
} else if ( event.type == "click") {
$("#quality1").val($(this).text());
$("#qualitySuggest1").hide();
}
else {
$(this).removeClass('sughover');
}
});
$("#quality1").blur(function () {
$("#qualitySuggest1").hide();
});
});
function finishAjax(id, response) {
$('#' + id).html(unescape(response));
$('#' + id).show();
} //finishAjax
However if I add another field the quality suggest .hide() is called but I can't get anything else such as an alert to work in the event.type == click for both of the fields.
var delay = (function () {
var timer = 0;
return function (callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
$(document).ready(function () {
$('#quality1').bind('input propertychange', function () {
delay(function () {
$.post("functions/autocomplete.php", {
quality:$(this).val(),
questionname:"<?php echo $_SESSION['question']; ?>",
count:1
}, function (response) {
$('#qualitySuggest1').hide();
setTimeout("finishAjax('qualitySuggest1', '" + escape(response) + "')", 20);
});
return false;
}, 20);
});
$('#quality2').bind('input propertychange', function () {
delay(function () {
$.post("functions/autocomplete.php", {
quality:$(this).val(),
questionname:"<?php echo $_SESSION['question']; ?>",
count:2
}, function (response) {
$('#qualitySuggest2').hide();
setTimeout("finishAjax('qualitySuggest2', '" + escape(response) + "')", 20);
});
return false;
}, 20);
});
});
$('.sugnorm1').live("mouseover mouseout click", function(event) {
if ( event.type == "mouseover" ) {
$(this).addClass('sughover');
} else if ( event.type == "click") {
$("#quality1").val($(this).text());
$("#qualitySuggest1").hide();
}
else {
$(this).removeClass('sughover');
}
});
$("#quality1").blur(function () {
$("#qualitySuggest1").hide();
});
$('.sugnorm2').live("mouseover mouseout click", function(event) {
if ( event.type == "mouseover" ) {
$(this).addClass('sughover');
} else if ( event.type == "click") {
$("#quality2").val($(this).text());
$("#qualitySuggest2").hide();
}
else {
$(this).removeClass('sughover');
}
});
$("#quality2").blur(function () {
$("#qualitySuggest2").hide();
});
});
function finishAjax(id, response) {
$('#' + id).html(unescape(response));
$('#' + id).show();
} //finishAjax
Thanks for your help!
My click event was being called after the blur event, thus the suggestion dropdown was hidden. I solved this by changing my click event to mousedown. Mousedown will then be called before blur.

Categories