multiple autocomplete dropdowns not working - javascript

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.

Related

Jquery drop not fired

I need to fire the drop part so that when user drop a file it uploads. But in my code drop not firing.
Please give me the corrected version of this code. This is really very important for my project. This code is taken from another stackoverflow post. And I have edited the drop part at the code given below.
User's answer will be appreciated.
$.fn.dndhover = function(options) {
return this.each(function() {
var self = $(this);
var collection = $();
self.on('dragenter', function(event) {
if (collection.length === 0) {
self.trigger('dndHoverStart');
}
collection = collection.add(event.target);
});
self.on('dragleave', function(event) {
/*
* Firefox 3.6 fires the dragleave event on the previous element
* before firing dragenter on the next one so we introduce a delay
*/
setTimeout(function() {
collection = collection.not(event.target);
if (collection.length === 0) {
self.trigger('dndHoverEnd');
}
}, 1);
});
self.on('drop', function(event) {
alert(event);
self.trigger('dndHoverDrop');
});
});
};
$('.uploadDiv').dndhover().on({
'dndHoverStart': function(event) {
if(!$(".selectFile").hasClass("hide")){
$(".selectFile").addClass("hide");
}
if($(".dropFile").hasClass("hide")){
$(".dropFile").removeClass("hide");
}
event.stopPropagation();
event.preventDefault();
return false;
},
'dndHoverEnd': function(event) {
if($(".selectFile").hasClass("hide")){
$(".selectFile").removeClass("hide");
}
if(!$(".dropFile").hasClass("hide")){
$(".dropFile").addClass("hide");
}
event.stopPropagation();
event.preventDefault();
return false;
},
'dndHoverDrop': function(event) {
alert('dropped');
if(!$(".selectFile").hasClass("hide")){
$(".selectFile").addClass("hide");
}
if(!$(".dropFile").hasClass("hide")){
$(".dropFile").addClass("hide");
}
event.preventDefault();
event.stopPropagation();
return false;
}
});
New Code:
$.fn.dndhover = function(options) {
return this.each(function() {
var self = $(this);
var collection = $();
self.on('dragenter', function(event) {
if (collection.length === 0) {
self.trigger('dndDragEnter');
}
collection = collection.add(event.target);
});
self.on('dragleave', function(event) {
/*
* Firefox 3.6 fires the dragleave event on the previous element
* before firing dragenter on the next one so we introduce a delay
*/
setTimeout(function() {
collection = collection.not(event.target);
if (collection.length === 0) {
self.trigger('dndDragLeave');
}
}, 1);
});
self.on('dragover', function(event) {
setTimeout(function() {
collection = collection.not(event.target);
if (collection.length === 0) {
self.trigger('dndDragOver');
}
}, 1);
});
self.on('drop,dragdrop', function(event) {
self.trigger('dndDragDrop');
});
});
};
$('.uploadDiv').dndhover().on({
'dndDragEnter': function(event) {
if(!$(".selectFile").hasClass("hide")){
$(".selectFile").addClass("hide");
}
if($(".dropFile").hasClass("hide")){
$(".dropFile").removeClass("hide");
}
event.stopPropagation();
},
'dndDragLeave': function(event) {
if($(".selectFile").hasClass("hide")){
$(".selectFile").removeClass("hide");
}
if(!$(".dropFile").hasClass("hide")){
$(".dropFile").addClass("hide");
}
},
'dndDragDrop': function(event) {
alert('dropped');
if(!$(".selectFile").hasClass("hide")){
$(".selectFile").addClass("hide");
}
if(!$(".dropFile").hasClass("hide")){
$(".dropFile").addClass("hide");
}
alert(event);
event.preventDefault();
},
'dndDragOver': function(event) {
if(!$(".selectFile").hasClass("hide")){
$(".selectFile").addClass("hide");
}
if($(".dropFile").hasClass("hide")){
$(".dropFile").removeClass("hide");
}
event.preventDefault();
}
});

Tab Navigation not working for Autocomplete text box on Mozilla Firefox

I am using 'jquery.ui.autocomplete.js'. What issue I am facing is that during TAB Press default Naviagtion get stuck
when it reached in Autocomplete Text Box. The issue is reflecting only in Mozilla Firefox. What I want is that on TAB key press
it shold move to next elemnt. Can anyone please assist me to fix this issue?
I have tried Googled solutions but not able to fix. I am posting some link hope it will help you to understand isue.
1. http://bugs.jqueryui.com/ticket/6661
I think issue is somewhere in these lines:
case keyCode.ENTER:
case keyCode.NUMPAD_ENTER:
// when menu is open or has focus
if (self.menu.element.is(":visible")) {
event.preventDefault();
}
//passthrough - ENTER and TAB both select the current element
case keyCode.TAB:
if (!self.menu.active) {
return;
}
self.menu.select(event);
break;
case keyCode.ESCAPE:
self.element.val(self.term);
self.close(event);
break;
default:
// keypress is triggered before the input value is changed
clearTimeout(self.searching);
self.searching = setTimeout(function () {
// only search if the value has changed
if (self.term != self.element.val()) {
self.selectedItem = null;
self.search(null, event);
}
}, self.options.delay);
break;
}
})
My jquery code is here:
(function ($, undefined) {
$.widget("ui.autocomplete", {
options: {
appendTo: "body",
delay: 300,
minLength: 1,
position: {
my: "left top",
at: "left bottom",
collision: "none"
},
source: null
},
_create: function () {
var self = this,
doc = this.element[0].ownerDocument;
this.element
.addClass("ui-autocomplete-input")
.attr("autocomplete", "off")
// TODO verify these actually work as intended
.attr({
role: "textbox",
"aria-autocomplete": "list",
"aria-haspopup": "true"
})
.bind("keydown.autocomplete", function (event) {
if (self.options.disabled || self.element.attr("readonly")) {
return;
}
var keyCode = $.ui.keyCode;
switch (event.keyCode) {
case keyCode.PAGE_UP:
self._move("previousPage", event);
break;
case keyCode.PAGE_DOWN:
self._move("nextPage", event);
break;
case keyCode.UP:
self._move("previous", event);
// prevent moving cursor to beginning of text field in some browsers
event.preventDefault();
break;
case keyCode.DOWN:
self._move("next", event);
// prevent moving cursor to end of text field in some browsers
event.preventDefault();
break;
case keyCode.ENTER:
case keyCode.NUMPAD_ENTER:
// when menu is open or has focus
if (self.menu.element.is(":visible")) {
event.preventDefault();
}
//passthrough - ENTER and TAB both select the current element
case keyCode.TAB:
if (!self.menu.active) {
return;
}
self.menu.select(event);
break;
case keyCode.ESCAPE:
self.element.val(self.term);
self.close(event);
break;
default:
// keypress is triggered before the input value is changed
clearTimeout(self.searching);
self.searching = setTimeout(function () {
// only search if the value has changed
if (self.term != self.element.val()) {
self.selectedItem = null;
self.search(null, event);
}
}, self.options.delay);
break;
}
})
.bind("focus.autocomplete", function () {
if (self.options.disabled) {
return;
}
self.selectedItem = null;
self.previous = self.element.val();
})
.bind("blur.autocomplete", function (event) {
if (self.options.disabled) {
return;
}
clearTimeout(self.searching);
// clicks on the menu (or a button to trigger a search) will cause a blur event
self.closing = setTimeout(function () {
self.close(event);
self._change(event);
}, 150);
});
this._initSource();
this.response = function () {
return self._response.apply(self, arguments);
};
this.menu = $("<ul></ul>")
.addClass("ui-autocomplete")
.appendTo($(this.options.appendTo || "body", doc)[0])
// prevent the close-on-blur in case of a "slow" click on the menu (long mousedown)
.mousedown(function (event) {
// clicking on the scrollbar causes focus to shift to the body
// but we can't detect a mouseup or a click immediately afterward
// so we have to track the next mousedown and close the menu if
// the user clicks somewhere outside of the autocomplete
var menuElement = self.menu.element[0];
if (event.target === menuElement) {
setTimeout(function () {
$(document).one('mousedown', function (event) {
if (event.target !== self.element[0] &&
event.target !== menuElement &&
!$.ui.contains(menuElement, event.target)) {
self.close();
}
});
}, 1);
}
// use another timeout to make sure the blur-event-handler on the input was already triggered
setTimeout(function () {
clearTimeout(self.closing);
}, 13);
})
.menu({
focus: function (event, ui) {
var item = ui.item.data("item.autocomplete");
if (false !== self._trigger("focus", null, { item: item })) {
// use value to match what will end up in the input, if it was a key event
if (/^key/.test(event.originalEvent.type)) {
self.element.val(item.value);
}
}
},
selected: function (event, ui) {
var item = ui.item.data("item.autocomplete"),
previous = self.previous;
// only trigger when focus was lost (click on menu)
if (self.element[0] !== doc.activeElement) {
self.element.focus();
self.previous = previous;
}
if (false !== self._trigger("select", event, { item: item })) {
self.element.val(item.value);
}
self.close(event);
self.selectedItem = item;
},
blur: function (event, ui) {
// don't set the value of the text field if it's already correct
// this prevents moving the cursor unnecessarily
if (self.menu.element.is(":visible") &&
(self.element.val() !== self.term)) {
self.element.val(self.term);
}
}
})
.zIndex(this.element.zIndex() + 1)
// workaround for jQuery bug #5781 http://dev.jquery.com/ticket/5781
.css({ top: 0, left: 0 })
.hide()
.data("menu");
if ($.fn.bgiframe) {
this.menu.element.bgiframe();
}
},
destroy: function () {
this.element
.removeClass("ui-autocomplete-input")
.removeAttr("autocomplete")
.removeAttr("role")
.removeAttr("aria-autocomplete")
.removeAttr("aria-haspopup");
this.menu.element.remove();
$.Widget.prototype.destroy.call(this);
},
_setOption: function (key, value) {
$.Widget.prototype._setOption.apply(this, arguments);
if (key === "source") {
this._initSource();
}
if (key === "appendTo") {
this.menu.element.appendTo($(value || "body", this.element[0].ownerDocument)[0])
}
},
_initSource: function () {
var array,
url;
if ($.isArray(this.options.source)) {
array = this.options.source;
this.source = function (request, response) {
response($.ui.autocomplete.filter(array, request.term));
};
} else if (typeof this.options.source === "string") {
url = this.options.source;
this.source = function (request, response) {
$.getJSON(url, request, response);
};
} else {
this.source = this.options.source;
}
},
search: function (value, event) {
value = value != null ? value : this.element.val();
if (value.length < this.options.minLength) {
return this.close(event);
}
clearTimeout(this.closing);
if (this._trigger("search") === false) {
return;
}
return this._search(value);
},
_search: function (value) {
this.term = this.element
.addClass("ui-autocomplete-loading")
// always save the actual value, not the one passed as an argument
.val();
this.source({ term: value }, this.response);
},
_response: function (content) {
if (content.length) {
content = this._normalize(content);
this._suggest(content);
this._trigger("open");
} else {
this.close();
}
this.element.removeClass("ui-autocomplete-loading");
},
close: function (event) {
clearTimeout(this.closing);
if (this.menu.element.is(":visible")) {
this._trigger("close", event);
this.menu.element.hide();
this.menu.deactivate();
}
},
_change: function (event) {
if (this.previous !== this.element.val()) {
this._trigger("change", event, { item: this.selectedItem });
}
},
_normalize: function (items) {
// assume all items have the right format when the first item is complete
if (items.length && items[0].label && items[0].value) {
return items;
}
return $.map(items, function (item) {
if (typeof item === "string") {
return {
label: item,
value: item
};
}
return $.extend({
label: item.label || item.value,
value: item.value || item.label
}, item);
});
},
_suggest: function (items) {
var ul = this.menu.element
.empty()
.zIndex(this.element.zIndex() + 1),
menuWidth,
textWidth;
this._renderMenu(ul, items);
// TODO refresh should check if the active item is still in the dom, removing the need for a manual deactivate
this.menu.deactivate();
this.menu.refresh();
this.menu.element.show().position($.extend({
of: this.element
}, this.options.position));
menuWidth = ul.width("").outerWidth();
textWidth = this.element.outerWidth();
ul.outerWidth(Math.max(menuWidth, textWidth));
},
_renderMenu: function (ul, items) {
var self = this;
$.each(items, function (index, item) {
self._renderItem(ul, item);
});
},
_renderItem: function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append($("<a></a>").text(item.label))
.appendTo(ul);
},
_move: function (direction, event) {
if (!this.menu.element.is(":visible")) {
this.search(null, event);
return;
}
if (this.menu.first() && /^previous/.test(direction) ||
this.menu.last() && /^next/.test(direction)) {
this.element.val(this.term);
this.menu.deactivate();
return;
}
this.menu[direction](event);
},
widget: function () {
return this.menu.element;
}
});
$.extend($.ui.autocomplete, {
escapeRegex: function (value) {
return value.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
},
filter: function (array, term) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(term), "i");
return $.grep(array, function (value) {
return matcher.test(value.label || value.value || value);
});
}
});
} (jQuery));
Yes, that bug ticket you linked to shows the changeset you need to follow.
Notice how instead of saying $('selector').autocomplete(...) you're expected to do:
$('selector').bind('keydown', function (event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data('autocomplete').menu.active ) {
event.preventDefault();
}
}).autocomplete(...)
Notice that you're intercepting TAB keydowns if the menu is "active" and preventing the event from doing the default behavior, which in a browser is focusing the next statically laid out element.

JavaScript removeEventListener won't work

I have a simple drag / drop script that I am playing around with to learn.. to try the code, just have an element with id "TEST" on a page and place the script on the page.
The element will begin dragging, and when you mouse up it seems like the removeEventListener doesn't seem to be working. I've been messing with it for 2 hours please help! Is there any obvious reason that it is not working? here is the script:
var Example = function() {
var exa = this;
this.elem = null;
this.init = function() {
exa.elem = document.getElementById('TEST');
console.log('exa.init()');
exa.attachEvent(exa.elem, 'mousedown', function(event) {
console.log('mousedown');
exa.drag.anchor(event);
});
}
this.attachEvent = function ( object, event, handler ) {
if (window.attachEvent) {
object.attachEvent( 'on'+event, function() {
handler.apply(object, arguments);
}, false );
} else {
object.addEventListener( event, function() {
handler.apply(object, arguments);
}, false );
}
}
this.detachEvent = function( object, event, handler ){
if (window.detachEvent) {
object.detachEvent( 'on'+event, function(){
handler.apply(object, arguments);
}, false ) ;
} else {
object.removeEventListener( event, function() {
handler.apply(object, arguments);
}, false );
}
}
this.drag = {
'release' : function(event) {
exa.elem.removeEventListener('mousemove', function(event) { exa.drag.move(event) }, true);
console.log('drag.release2');
},
'anchor' : function(event){
console.log('exa.drag.anchor();');
offY= event.clientY-parseInt(exa.elem.offsetTop);
offX= event.clientX-parseInt(exa.elem.offsetLeft);
exa.attachEvent(window, 'mousemove', function(event) {
exa.drag.move(event);
});
},
'move' : function(event) {
exa.elem.style.position = 'absolute';
var topPosition = (event.clientY-offY);
var leftPosition = (event.clientX-offX);
exa.elem.style.top = topPosition+ 'px';
exa.elem.style.left = leftPosition + 'px';
//console.log('FROM THE TOP: ' + topPosition);
//console.log('FROM THE LEFT: ' + leftPosition);
exa.attachEvent(window, 'mouseup', function(event) {
exa.drag.release(event);
});
}
}
}
var example = new Example();
example.attachEvent(window, 'load', function(event) {
example.init(event);
});
Sorry about that, the code I posted had confusing names for the functions and a couple mistakes, please look at the following:
var Example = function() {
var exa = this;
this.elem = null;
this.init = function() {
exa.elem = document.getElementById('TEST');
console.log('exa.init()');
exa.newEvent(exa.elem, 'mousedown', function(event) {
console.log('mousedown');
exa.drag.anchor(event);
});
}
this.newEvent = function ( object, event, handler ) {
if (window.attachEvent) {
object.attachEvent( 'on'+event, function() {
handler.apply(object, arguments);
}, false );
} else {
object.addEventListener( event, function() {
handler.apply(object, arguments);
}, false );
}
}
this.removeEvent = function( object, event, handler ){
if (window.detachEvent) {
object.detachEvent( 'on'+event, function(){
handler.apply(object, arguments);
}, false ) ;
} else {
object.removeEventListener( event, function() {
handler.apply(object, arguments);
}, false );
}
}
this.drag = {
'release' : function(event) {
exa.removeEvent(exa.elem, 'mousemove', exa.drag.move);
console.log('drag.release2');
},
'anchor' : function(event){
console.log('exa.drag.anchor();');
offY= event.clientY-parseInt(exa.elem.offsetTop);
offX= event.clientX-parseInt(exa.elem.offsetLeft);
exa.newEvent(window, 'mousemove', function(event) {
exa.drag.move(event);
});
},
'move' : function(event) {
exa.elem.style.position = 'absolute';
var topPosition = (event.clientY-offY);
var leftPosition = (event.clientX-offX);
exa.elem.style.top = topPosition+ 'px';
exa.elem.style.left = leftPosition + 'px';
exa.newEvent(window, 'mouseup', function(event) {
exa.drag.release(event);
});
}
}
}
var example = new Example();
example.newEvent(window, 'load', function(event) {
example.init(event);
});
You need a variable that refers to first function (callback passed to addEventListener), each time when you passing function with body as argument to removeEventListener, new function is created
var callback = function()
{
alert(1);
}
button.addEventListener('click', callback);
button.removeEventListener('click', callback);

Bind function in jQuery plugin function

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.

JQuery - where to add .on()/.live() to function?

var refreshId = setInterval(function() {
$('#livelist').load('/scripts/livelist.php', { guestlist:'<?php echo $_GET['guestlist']; ?>'});
}, 5000);
$.ajaxSetup({ cache: false });
I know I need to attach the .live() event handler to prevent the function from triggering other events (what's currently happening), but where do I add it?
Full Script:
$(document).ready(function() {
$("input#name").select().focus();
$('#livelist').load('/scripts/livelist.php', { guestlist:'<?php echo $_GET['guestlist']; ?>'});
var refreshId = setInterval(function() {
$('#livelist').load('/scripts/livelist.php', { guestlist:'<?php echo $_GET['guestlist']; ?>'});
}, 5000);
$.ajaxSetup({ cache: false });
$("input#name").swearFilter({words:'bob, dan', mask:"!", sensor:"normal"});
var tagCheckRE = new RegExp("(\\w+)(\\s+)(\\w+)");
jQuery.validator.addMethod("tagcheck", function(value, element) {
return tagCheckRE.test(value);
}, "");
$("#addname").validate({
invalidHandler: function(form, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
$('#naughty').fadeIn('fast');
$('#naughty').delay('1000').fadeOut('fast');
} else {
$('#naughty').hide();
}
}
});
$('#showall').live('click', function() {
$('#showall').hide();
$('div#shownames').slideDown('fast');
});
jQuery(document).ajaxStart(function(){
$("input#name").blur();
$('#working').show();
$('#event-box').fadeTo('fast', 0.5);
})
var names = '';
var dot = '.';
$('#addname').ajaxForm(function() {
var options = {
success: function(html) {
/* $("#showdata").replaceWith($('#showdata', $(html))) */
var value = $("input#name").val().toUpperCase();;
$("span.success").text(value);
if (names == '') {
names = value;
}
else {
names = ' ' + value + ', ' + names;
$("span#dot").text(dot);
}
$("span#name1").text(names);
$('#working').fadeOut('fast');
$('#success').fadeIn('fast');
$('#added-names').fadeIn('fast');
$('#success').delay('600').fadeOut('fast');
$("input#name").delay('1200').select().focus();
$('#event-box').delay('600').fadeTo('fast', 1.0);
$(':input','#addname')
.not(':button, :submit, :reset, :hidden')
.val('')
},
cache: true,
error: function(x, t, m) {
if(t==="timeout") {
$('#working').fadeOut('fast');
$('#fail').fadeIn('fast');
$('#fail').delay('600').fadeOut('fast');
} else {
$('#working').fadeOut('fast');
$('#fail').fadeIn('fast');
$('#fail').delay('600').fadeOut('fast');
alert(t);
}
}
}
$(this).ajaxSubmit(options);
$('body').select().focus();
});
$("input").bind("keydown", function(event) {
var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
if (keycode == 13) {
document.getElementById('#submit').click();
return false;
} else {
return true;
}
});
});
The ajaxForm function is being triggered using my current implementation.
The fault:
jQuery(document).ajaxStart(function(){
$("input#name").blur();
$('#working').show();
$('#event-box').fadeTo('fast', 0.5);
})
As .ajaxStart() is a global parameter, it was being triggered during every AJAX call, including .load(), I'm surprised no one spotted it.

Categories