How to hide a dynamically generated div - javascript

Can someone please show me how to remove this div?
I tried everything I could find. Some of the things I've tried are:
jQuery(document).ready(function ($) {
if (seconds == 0 ) {
$(".meows").hide();
return;
}
});
this:
jQuery(document).ready(function ($) {
if (seconds == 0 ) {
$('.meows').css('display','none');
return;
}
});
this:
document.onreadystatechange = function () {
if (document.readyState == "complete") {
document.getElementsByClassName("meows")[0].style.display = "none";
}
}
this:
document.addEventListener('DOMContentLoaded', function() {
if (seconds == 0 ) {
document.getElementsByClassName("meows")[0].style.display = "none";
//document.getElementById('timer').innerHTML = 'EXPIRED!';
return;
}
});
and more. Most of these actually make the error go away. The error I get is:
TypeError: Cannot read property 'style' of undefined
What it is is a popup notification. It popups right under the body tag. So it's not there all the time.
Here is where the popup gets created:
if (typeof default_meow_area === 'undefined' && typeof options.container === 'undefined') {
default_meow_area = $(window.document.createElement('div'))
.attr({'id': ((new Date()).getTime()), 'class': 'meows'});
$('body').prepend(default_meow_area);
}
I'm not sure this is enough information to figure it out so here is the whole js file:
(function ($, window) {
'use strict';
// Meow queue
var default_meow_area,
meows = {
queue: {},
add: function (meow) {
this.queue[meow.timestamp] = meow;
},
get: function (timestamp) {
return this.queue[timestamp];
},
remove: function (timestamp) {
delete this.queue[timestamp];
},
size: function () {
var timestamp,
size = 0;
for (timestamp in this.queue) {
if (this.queue.hasOwnProperty(timestamp)) { size += 1; }
}
return size;
}
},
// Meow constructor
Meow = function (options) {
var that = this;
this.timestamp = new Date().getTime(); // used to identify this meow and timeout
this.hovered = false; // whether mouse is over or not
if (typeof default_meow_area === 'undefined'
&& typeof options.container === 'undefined') {
default_meow_area = $(window.document.createElement('div'))
.attr({'id': ((new Date()).getTime()), 'class': 'meows'});
$('body').prepend(default_meow_area);
}
if (meows.size() <= 0) {
if (typeof options.beforeCreateFirst === 'function') {
options.beforeCreateFirst.call(that);
}
}
if (typeof options.container === 'string') {
this.container = $(options.container);
} else {
this.container = default_meow_area;
}
if (typeof options.title === 'string') {
this.title = options.title;
}
if (typeof options.message === 'string') {
this.message = options.message;
} else if (options.message instanceof $) {
if (options.message.is('input,textarea,select')) {
this.message = options.message.val();
} else {
this.message = options.message.text();
}
if (typeof this.title === 'undefined' && typeof options.message.attr('title') === 'string') {
this.title = options.message.attr('title');
}
}
if (typeof options.icon === 'string') {
this.icon = options.icon;
}
if (options.sticky) {
this.duration = Infinity;
} else {
this.duration = options.duration || 7000;
}
// Call callback if it's defined (this = meow object)
if (typeof options.beforeCreate === 'function') {
options.beforeCreate.call(that);
}
// Add the meow to the meow area
this.container.append($(window.document.createElement('div'))
.attr('id', 'meow-' + this.timestamp.toString())
.addClass('meow')
.html($(window.document.createElement('div')).addClass('inner').html(this.message))
.hide()
.fadeIn('400', function() {
$('.meows').animate({'bottom':'0'},500);
}));
this.manifest = $('#meow-' + this.timestamp.toString());
// Add title if it's defined
if (typeof this.title === 'string') {
this.manifest.find('.inner').prepend(
$(window.document.createElement('p')).text(this.title)
);
}
// Add icon if it's defined
if (typeof that.icon === 'string') {
this.manifest.find('.inner').prepend(
$(window.document.createElement('div')).addClass('icon').html(
$(window.document.createElement('img')).attr('src', this.icon)
)
);
}
// Add close button if the meow isn't uncloseable
// TODO: this close button needs to be much prettier
if (options.closeable !== false) {
this.manifest.find('.inner').prepend(
$(window.document.createElement('a'))
.addClass('close')
.html('×')
.attr('href', '#close-meow-' + that.timestamp)
.click(function (e) {
e.preventDefault();
that.destroy();
})
);
}
this.manifest.bind('mouseenter mouseleave', function (event) {
if (event.type === 'mouseleave') {
that.hovered = false;
that.manifest.removeClass('hover');
// Destroy the mow on mouseleave if it's timed out
if (that.timestamp + that.duration <= new Date().getTime()) {
that.destroy();
}
} else {
that.hovered = true;
that.manifest.addClass('hover');
}
});
// Add a timeout if the duration isn't Infinity
if (this.duration !== Infinity) {
this.timeout = window.setTimeout(function () {
// Make sure this meow hasn't already been destroyed
if (typeof meows.get(that.timestamp) !== 'undefined') {
// Call callback if it's defined (this = meow DOM element)
if (typeof options.onTimeout === 'function') {
options.onTimeout.call(that.manifest);
}
// Don't destroy if user is hovering over meow
if (that.hovered !== true && typeof that === 'object') {
that.destroy();
}
}
}, that.duration);
}
this.destroy = function () {
if (that.destroyed !== true) {
// Call callback if it's defined (this = meow DOM element)
if (typeof options.beforeDestroy === 'function') {
options.beforeDestroy.call(that.manifest);
}
that.manifest.find('.inner').fadeTo(400, 0, function () {
that.manifest.slideUp(function () {
that.manifest.remove();
that.destroyed = true;
meows.remove(that.timestamp);
if (typeof options.afterDestroy === 'function') {
options.afterDestroy.call(null);
}
if (meows.size() <= 0) {
if (default_meow_area instanceof $) {
default_meow_area.remove();
default_meow_area = undefined;
}
if (typeof options.afterDestroyLast === 'function') {
options.afterDestroyLast.call(null);
}
}
});
});
}
};
};
$.fn.meow = function (args) {
var meow = new Meow(args);
meows.add(meow);
return meow;
};
$.meow = $.fn.meow;
}(jQuery, window));
/*! countdown timer I added below */
var timeoutHandle;
function countdown(minutes,stat) {
var seconds = 60;
var mins = minutes;
if(getCookie("minutes")&&getCookie("seconds")&&stat)
{
var seconds = getCookie("seconds");
var mins = getCookie("minutes");
}
function tick() {
var counter = document.getElementById("timer");
setCookie("minutes",mins,10)
setCookie("seconds",seconds,10)
var current_minutes = mins-1
seconds--;
counter.innerHTML = current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
//save the time in cookie
if( seconds > 0 ) {
timeoutHandle=setTimeout(tick, 1000);
} else {
if(mins > 1){
setTimeout(function () { countdown(parseInt(mins)-1,false); }, 1000);
}
}
jQuery(document).ready(function () {
if (seconds == 0 ) {
document.getElementsByClassName("meows")[0].style.display = "none";
//document.getElementById('timer').innerHTML = 'EXPIRED!';
return;
}
)};
}
tick();
}
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
window.onload = function startingTimer(){
//countdown(prompt("Enter how many minutes you want to count down:"),true);
countdown(1,true);
}

Use event delegation to register events for all present and future elements that match your selector. In your case, you can use something like this
$('body').delegate('.meows', 'click', function() {
console.log(this);
});
The above delegation is for click event but you can bind any event to accomplish your needs.
Another method is to use MutationObserver. I won't go to it's details here because the above method can solve your problem.

Related

Uncaught Error: cannot call methods on prior to initialization; attempted to call method

I have a javascript method in a partial view .Net 6 MVC like this: After upgrading to JQuery 3.6.1 and JQuery UI 1.13.2. I am getting errors like:
Uncaught Error: cannot call methods on NumericBox prior to initialization; attempted to call method 'isNumeric'. Please suggest. Thanks.
function CompareDialog() {
var aReleased;
$(".weighting-total").NumericBox("setValue", $(".weighting").NumericBoxSum());
}
The javascript for the NumericBox and NumericBoxSum:
$.widget("Data.NumericBox", {
options: {
allowReservedValues: undefined,
readOnly: undefined,
decimalPlaces: undefined,
showZero: undefined,
allowNegative: undefined,
thousandSeperator: undefined
},
_create: function () {
this._super();
var that = this;
// Option: Allow Reserved Values
if (this.options.allowReservedValues == undefined) {
if (this.element.data("allow-reserved-values") != undefined) {
this.options.allowReservedValues = JSON.parse(this.element.data("allow-reserved-values").toLowerCase());
}
else {
this.options.allowReservedValues = false;
}
}
// Option: Read Only
if (this.options.readOnly != undefined) {
this.element.prop("readonly", this.options.readOnly);
}
// Option: Decimal Places
if (this.options.decimalPlaces == undefined) {
if (this.element.data("decimal-places") != undefined) {
this.options.decimalPlaces = parseInt(this.element.data("decimal-places"));
}
else {
this.options.decimalPlaces = 0;
}
}
// Option: Show Zero
if (this.options.showZero == undefined) {
if (this.element.data("show-zero") != undefined) {
this.options.showZero = JSON.parse(this.element.data("show-zero").toLowerCase());
}
else {
this.options.showZero = true;
}
}
// Option: Allow Negative
if (this.options.allowNegative == undefined) {
if (this.element.data("allow-negative") != undefined) {
this.options.allowNegative = JSON.parse(this.element.data("allow-negative").toLowerCase());
}
else {
this.options.allowNegative = false;
}
}
// Option: Thousand Seperator
if (this.options.thousandSeperator == undefined) {
if (this.element.data("thousand-seperator") != undefined) {
this.options.thousandSeperator = this.element.data("thousand-seperator");
}
else {
this.options.thousandSeperator = ",";
}
}
// Set client-side validation to ignore N/Avail and N/Appl values
if ($.validator.defaults.ignore.indexOf(".fd-not-available") < 0) {
$.validator.setDefaults({
ignore: $.validator.defaults.ignore + ",.fd-not-available,.fd-not-applicable"
});
}
// Define validation for hyphens
if (this.options.allowNegative) {
if ($.validator.methods["val-hyphen"] === undefined) {
$.validator.addMethod("val-hyphen", function (value, element) {
var message = $(element).data("val-number");
if (value == "-") {
return false;
}
return true;
}, $.validator.format("{0}"));
}
this.element.attr("val-hyphen", this.element.data("val-number"));
}
// Handle paste
this.element.on("paste", function (event) {
if ($(this).hasClass("fd-not-available") || $(this).hasClass("fd-not-applicable")) {
$(this).val("").removeClass("fd-not-available fd-not-applicable");
}
});
// Handle clearing of textbox
this.element.on("input", function (event) {
if ($(this).val() == "") {
$(this).removeClass("fd-not-available fd-not-applicable");
}
});
this.element.keydown(function (event) {
if (that.isReserved()) {
if (!$(this).prop("readonly") && (event.which == 8 || event.which == 46)) {
$(this).val("").removeClass("fd-not-available fd-not-applicable").select();
event.preventDefault();
}
}
});
this.element.keypress(function (event) {
if (that.element.prop("readonly")) {
event.preventDefault();
return;
}
if (event.which == 78 || event.which == 110) { // N
if (that.options.allowReservedValues) {
that.setReserved(ReservedValue.NotAvailable);
$(this).change();
}
event.preventDefault();
return;
}
if (event.which == 80 || event.which == 112) { // P
if (that.options.allowReservedValues) {
that.setReserved(ReservedValue.NotApplicable);
$(this).change();
}
event.preventDefault();
return;
}
if (event.which == 45) { // -
if (!that.options.allowNegative) {
event.preventDefault();
return;
}
if (that.isReserved()) {
that.setValue("");
}
that.refresh();
return;
}
if (event.which == 46) { // .
if (that.options.decimalPlaces == 0) {
event.preventDefault();
return;
}
if (that.isReserved()) {
that.setValue("");
}
that.refresh();
return;
}
if (event.which >= 48 && event.which <= 57) { // 0 - 9
if (that.isReserved()) {
$(this).val("");
}
if (that.isReserved()) {
that.setValue("");
}
that.refresh();
return;
}
event.preventDefault();
});
this.element.focusin(function (event) {
var value = that._internalFormat($(this).val());
$(this).val(value);
});
this.element.focusout(function (event) {
var value = that._externalFormat($(this).val());
$(this).val(value);
});
this.element.val(this._externalFormat(this.element.val()));
this.refresh();
},
_externalFormat: function (value) {
if ($.isNumeric(value)) {
if (parseFloat(value) == 0 && !this.options.showZero) {
return "";
}
else if (!ReservedValue.isReserved(value)) {
var signPart = value > -1 && value < 0 ? "-" : ""; // Required: In the following statement parseInt removes the sign for small negative numbers
var integerPart = parseInt(numeral(value).format("0" + (0).toFixed(this.options.decimalPlaces).substr(1)));
var fractionalPart = Big(value).minus(Big(integerPart)).abs();
var display = signPart + numeral(integerPart).format("0" + this.options.thousandSeperator + "0") +
fractionalPart.toFixed(this.options.decimalPlaces).substr(1);
return display;
}
}
return value;
},
_internalFormat: function (value) {
try {
value = value.replace(/,/g, "");
if ($.isNumeric(value)) {
if (this.options.decimalPlaces == 0) {
value = parseInt(value);
}
else {
value = Big(value).format("0" + (0).toFixed(this.options.decimalPlaces).substr(1)).toString();
}
}
return value;
}
catch (e) {
return value;
}
},
refresh: function () {
var value = this._internalFormat(this.element.val());
if (this.options.allowReservedValues) {
if (value == ReservedValue.NotAvailable) {
this.element.val(ReservedValue.text(value)).removeClass("fd-not-applicable").addClass("fd-not-available");
}
else if (value == ReservedValue.NotApplicable) {
this.element.val(ReservedValue.text(value)).removeClass("fd-not-available").addClass("fd-not-applicable");
}
else {
if (this.element.hasClass("fd-not-available") || this.element.hasClass("fd-not-applicable")) {
this.element.removeClass("fd-not-available fd-not-applicable");
}
}
}
return this;
},
setValue: function (value) {
this.element.val(this._externalFormat(value));
this.refresh();
},
getValue: function () {
return this._internalFormat(this.element.val());
},
isNumeric: function (includeReservedValues) {
includeReservedValues = includeReservedValues === undefined ? false : includeReservedValues;
if (!includeReservedValues && this.isReserved()) {
return false;
}
else {
return $.isNumeric(this.getValue());
}
},
isReserved: function (resval) {
var value = ReservedValue.parse(this._internalFormat(this.element.val()));
if (resval === undefined) {
return ReservedValue.isReserved(value);
}
else {
return value == resval;
}
},
setReserved: function (resval) {
this.element.val(resval).valid();
this.refresh();
},
getReserved: function () {
return ReservedValue.parse(this._internalFormat(this.element.val()));
}
});
$.fn.NumericBoxSum = function (blankIfNoNumerics) {
var NumericCount = 0;
var sum = 0.0;
blankIfNoNumerics = blankIfNoNumerics === undefined ? false : blankIfNoNumerics;
this.each(function () {
if ($(this).NumericBox("isNumeric")) {
sum += parseFloat($(this).NumericBox("getValue"));
NumericCount++;
}
});
if (NumericCount == 0 && blankIfNoNumerics) {
sum = "";
}
return sum;
};

I obfuscated my JavaScript. How can someone exactly decode it?

var _0x3424=["\x67\x65\x74","\x2F\x73\x68\x6F\x70\x2F\x61\x6C\x6C","\x69\x6E\x64\x65\x78\x4F\x66","\x68\x72\x65\x66","\x6C\x6F\x63\x61\x74\x69\x6F\x6E","\x6B\x65\x79\x77\x6F\x72\x64","","\x74\x6F\x4C\x6F\x77\x65\x72\x43\x61\x73\x65","\x63\x6F\x6C\x6F\x72","\x73\x69\x7A\x65","\x2E\x69\x6E\x6E\x65\x72\x2D\x61\x72\x74\x69\x63\x6C\x65","\x67\x65\x74\x41\x74\x74\x72\x69\x62\x75\x74\x65","\x2E\x69\x6E\x6E\x65\x72\x2D\x61\x72\x74\x69\x63\x6C\x65\x20\x3E\x20\x61","\x2F","\x73\x70\x6C\x69\x74","\x6C\x65\x6E\x67\x74\x68","\x61\x6C\x74","\x2E\x69\x6E\x6E\x65\x72\x2D\x61\x72\x74\x69\x63\x6C\x65\x20\x3E\x20\x61\x20\x3E\x20\x69\x6D\x67","\x6E\x6F\x74\x20\x66\x6F\x75\x6E\x64","\x6C\x6F\x67","\x68\x74\x74\x70\x3A\x2F\x2F\x77\x77\x77\x2E\x73\x75\x70\x72\x65\x6D\x65\x6E\x65\x77\x79\x6F\x72\x6B\x2E\x63\x6F\x6D\x2F\x73\x68\x6F\x70\x2F\x61\x6C\x6C","\x3A\x76\x69\x73\x69\x62\x6C\x65","\x69\x73","\x2E\x69\x6E\x2D\x63\x61\x72\x74","\x74\x65\x78\x74","\x73\x65\x6C\x65\x63\x74\x65\x64\x49\x6E\x64\x65\x78","\x70\x72\x6F\x70","\x23\x73\x69\x7A\x65","\x65\x61\x63\x68","\x23\x73\x69\x7A\x65\x20\x6F\x70\x74\x69\x6F\x6E","\x63\x6C\x69\x63\x6B","\x5B\x6E\x61\x6D\x65\x3D\x22\x63\x6F\x6D\x6D\x69\x74\x22\x5D","\x69\x73\x63\x68\x65\x63\x6B\x6F\x75\x74","\x73\x68\x6F\x70\x2F\x61\x6C\x6C","\x68\x74\x74\x70\x73\x3A\x2F\x2F\x77\x77\x77\x2E\x73\x75\x70\x72\x65\x6D\x65\x6E\x65\x77\x79\x6F\x72\x6B\x2E\x63\x6F\x6D\x2F\x63\x68\x65\x63\x6B\x6F\x75\x74","\x73\x65\x6E\x64\x4D\x65\x73\x73\x61\x67\x65","\x65\x78\x74\x65\x6E\x73\x69\x6F\x6E"];$(function(){chrome[_0x3424[36]][_0x3424[35]]({method:_0x3424[0]},function(_0xc165x1){var _0xc165x2=false;var _0xc165x3=setInterval(function(){if(window[_0x3424[4]][_0x3424[3]][_0x3424[2]](_0x3424[1])!=-1&&_0xc165x2===false){if(_0xc165x1[_0x3424[5]]!=_0x3424[6]&&_0xc165x1[_0x3424[5]]!=undefined){var _0xc165x4=_0xc165x1[_0x3424[5]][_0x3424[7]]();var _0xc165x5=_0xc165x1[_0x3424[8]][_0x3424[7]]();for(var _0xc165x6=0;_0xc165x6<$(_0x3424[10])[_0x3424[9]]();_0xc165x6++){var _0xc165x7=$(_0x3424[12])[_0xc165x6][_0x3424[11]](_0x3424[3]);var _0xc165x8=_0xc165x7[_0x3424[14]](_0x3424[13]);_0xc165x8=_0xc165x8[_0xc165x8[_0x3424[15]]-1][_0x3424[7]]();var _0xc165x9=$(_0x3424[17])[_0xc165x6][_0x3424[11]](_0x3424[16])[_0x3424[7]]();if(_0xc165x9[_0x3424[2]](_0xc165x4)!=-1&&_0xc165x8[_0x3424[2]](_0xc165x5)!=-1&&_0xc165x2===false){_0xc165x2=true;window[_0x3424[4]][_0x3424[3]]=_0xc165x7;break ;}else {console[_0x3424[19]](_0x3424[18])};};if(_0xc165x2===false){clearInterval(_0xc165x3);window[_0x3424[4]][_0x3424[3]]=_0x3424[20];};}}});var _0xc165xa=setInterval(function(){if(window[_0x3424[4]][_0x3424[3]][_0x3424[2]](_0x3424[1])== -1){if(!$(_0x3424[23])[_0x3424[22]](_0x3424[21])){$(_0x3424[29])[_0x3424[28]](function(_0xc165x6){if($(this)[_0x3424[24]]()==_0xc165x1[_0x3424[9]]){$(_0x3424[27])[_0x3424[26]](_0x3424[25],_0xc165x6)}});$(_0x3424[31])[_0x3424[30]]();}}},100);if(_0xc165x1[_0x3424[32]]==1){var _0xc165xb=setInterval(function(){if($(_0x3424[23])[_0x3424[22]](_0x3424[21])&&window[_0x3424[4]][_0x3424[3]][_0x3424[2]](_0x3424[33])== -1){window[_0x3424[4]]=_0x3424[34];clearInterval(_0xc165xb);}},100)};})});
I'm wondering if this is a strong encryption, how could someone exactly decode it? Any help would be appreciate. Thank you.
It's impossible to recover the EXACT original code once it's obfuscated, but keep in mind that the code still needs to be understandable by the compiler/interpreter so it may be "reassembled" but most likely the original structure, classes, variable names, etc... will be lost.
My try to deobfuscate your code got me this :
var _0x3424 = ["\x67\x65\x74", "\x2F\x73\x68\x6F\x70\x2F\x61\x6C\x6C", "\x69\x6E\x64\x65\x78\x4F\x66", "\x68\x72\x65\x66", "\x6C\x6F\x63\x61\x74\x69\x6F\x6E", "\x6B\x65\x79\x77\x6F\x72\x64", "", "\x74\x6F\x4C\x6F\x77\x65\x72\x43\x61\x73\x65", "\x63\x6F\x6C\x6F\x72", "\x73\x69\x7A\x65", "\x2E\x69\x6E\x6E\x65\x72\x2D\x61\x72\x74\x69\x63\x6C\x65", "\x67\x65\x74\x41\x74\x74\x72\x69\x62\x75\x74\x65", "\x2E\x69\x6E\x6E\x65\x72\x2D\x61\x72\x74\x69\x63\x6C\x65\x20\x3E\x20\x61", "\x2F", "\x73\x70\x6C\x69\x74", "\x6C\x65\x6E\x67\x74\x68", "\x61\x6C\x74", "\x2E\x69\x6E\x6E\x65\x72\x2D\x61\x72\x74\x69\x63\x6C\x65\x20\x3E\x20\x61\x20\x3E\x20\x69\x6D\x67", "\x6E\x6F\x74\x20\x66\x6F\x75\x6E\x64", "\x6C\x6F\x67", "\x68\x74\x74\x70\x3A\x2F\x2F\x77\x77\x77\x2E\x73\x75\x70\x72\x65\x6D\x65\x6E\x65\x77\x79\x6F\x72\x6B\x2E\x63\x6F\x6D\x2F\x73\x68\x6F\x70\x2F\x61\x6C\x6C", "\x3A\x76\x69\x73\x69\x62\x6C\x65", "\x69\x73", "\x2E\x69\x6E\x2D\x63\x61\x72\x74", "\x74\x65\x78\x74", "\x73\x65\x6C\x65\x63\x74\x65\x64\x49\x6E\x64\x65\x78", "\x70\x72\x6F\x70", "\x23\x73\x69\x7A\x65", "\x65\x61\x63\x68", "\x23\x73\x69\x7A\x65\x20\x6F\x70\x74\x69\x6F\x6E", "\x63\x6C\x69\x63\x6B", "\x5B\x6E\x61\x6D\x65\x3D\x22\x63\x6F\x6D\x6D\x69\x74\x22\x5D", "\x69\x73\x63\x68\x65\x63\x6B\x6F\x75\x74", "\x73\x68\x6F\x70\x2F\x61\x6C\x6C", "\x68\x74\x74\x70\x73\x3A\x2F\x2F\x77\x77\x77\x2E\x73\x75\x70\x72\x65\x6D\x65\x6E\x65\x77\x79\x6F\x72\x6B\x2E\x63\x6F\x6D\x2F\x63\x68\x65\x63\x6B\x6F\x75\x74", "\x73\x65\x6E\x64\x4D\x65\x73\x73\x61\x67\x65", "\x65\x78\x74\x65\x6E\x73\x69\x6F\x6E"];
$(function() {
chrome[_0x3424[36]][_0x3424[35]]({
method: _0x3424[0]
}, function(_0xc165x1) {
var _0xc165x2 = false;
var _0xc165x3 = setInterval(function() {
if (window[_0x3424[4]][_0x3424[3]][_0x3424[2]](_0x3424[1]) != -1 && _0xc165x2 === false) {
if (_0xc165x1[_0x3424[5]] != _0x3424[6] && _0xc165x1[_0x3424[5]] != undefined) {
var _0xc165x4 = _0xc165x1[_0x3424[5]][_0x3424[7]]();
var _0xc165x5 = _0xc165x1[_0x3424[8]][_0x3424[7]]();
for (var _0xc165x6 = 0; _0xc165x6 < $(_0x3424[10])[_0x3424[9]](); _0xc165x6++) {
var _0xc165x7 = $(_0x3424[12])[_0xc165x6][_0x3424[11]](_0x3424[3]);
var _0xc165x8 = _0xc165x7[_0x3424[14]](_0x3424[13]);
_0xc165x8 = _0xc165x8[_0xc165x8[_0x3424[15]] - 1][_0x3424[7]]();
var _0xc165x9 = $(_0x3424[17])[_0xc165x6][_0x3424[11]](_0x3424[16])[_0x3424[7]]();
if (_0xc165x9[_0x3424[2]](_0xc165x4) != -1 && _0xc165x8[_0x3424[2]](_0xc165x5) != -1 && _0xc165x2 === false) {
_0xc165x2 = true;
window[_0x3424[4]][_0x3424[3]] = _0xc165x7;
break;
} else {
console[_0x3424[19]](_0x3424[18])
};
};
if (_0xc165x2 === false) {
clearInterval(_0xc165x3);
window[_0x3424[4]][_0x3424[3]] = _0x3424[20];
};
}
}
});
var _0xc165xa = setInterval(function() {
if (window[_0x3424[4]][_0x3424[3]][_0x3424[2]](_0x3424[1]) == -1) {
if (!$(_0x3424[23])[_0x3424[22]](_0x3424[21])) {
$(_0x3424[29])[_0x3424[28]](function(_0xc165x6) {
if ($(this)[_0x3424[24]]() == _0xc165x1[_0x3424[9]]) {
$(_0x3424[27])[_0x3424[26]](_0x3424[25], _0xc165x6)
}
});
$(_0x3424[31])[_0x3424[30]]();
}
}
}, 100);
if (_0xc165x1[_0x3424[32]] == 1) {
var _0xc165xb = setInterval(function() {
if ($(_0x3424[23])[_0x3424[22]](_0x3424[21]) && window[_0x3424[4]][_0x3424[3]][_0x3424[2]](_0x3424[33]) == -1) {
window[_0x3424[4]] = _0x3424[34];
clearInterval(_0xc165xb);
}
}, 100)
};
})
});
OK, how'd I do. Variable names will have changed of course, but the functionality of the code is completely readable
$(function () {
chrome.extension.sendMessage({ method: "get" },
function (param1) {
var var1 = false;
var intHand1 = setInterval(function () {
if (window.location.href.indexOf("/shop/all") != -1 && var1 === false) {
if (param1.keyword != "" && param1.keyword != undefined) {
var kwordlc = param1.keyword.toLowerCase();
var colorlc = param1.color.toLowerCase();
for (var i = 0; i < $(".inner-article").size() ; i++) {
var ahref = $(".inner-article > a")[i].getAttribute("href");
var ahrefsplit = ahref.split("/");
ahrefsplit = ahrefsplit[ahrefsplit.length - 1].toLowerCase();
var altlc = $(".inner-article > a > img")[i].getAttribute("alt").toLowerCase();
if (altlc.indexOf(kwordlc) != -1 && ahrefsplit.indexOf(colorlc) != -1 && var1 === false) {
var1 = true;
window.location.href = ahref;
break;
} else {
console.log("not found")
};
}; if (var1 === false) {
clearInterval(intHand1);
window.location.href = "http://www.supremenewyork.com/shop/all";
};
}
}
});
var intHand2 = setInterval(function () {
if (window.location.href.indexOf("/shop/all") == -1) {
if (!$(".in-cart").is(":visible")) {
$("#size option").each(function (param2) {
if ($(this).text() == param1.size) {
$("#size").prop("selectedIndex", param2)
}
}); $("[name='commit']").click();
}
}
}, 100);
if (param1.ischeckout == 1) {
var intHand3 = setInterval(function () {
if ($(".in-cart").is(":visible") && window.location.href.indexOf("shop/all") == -1) {
window.location = "https://www.supremenewyork.com/checkout";
clearInterval(intHand3);
}
}, 100)
};
})
});
Took me about 50 mins, and I got interrupted by a couple of phone calls, messages and emails.

How to set width on this javascript button?

in the html i have this call to a java script function:
<span class="lotusBtn lotusBtnAction">
<a dojoType="quickr.widgets.menu.placeActionsMenu" linkText="##[PLACE.ACTIONS.PLACE_ACTIONS]##"></a>
</span>
this java script file looks as follows:
dojo.provide("quickr.widgets.menu.placeActionsMenu");
dojo.require("quickr.widgets.menu.baseMenu");
dojo.require("quickr.widgets.modal.list");
dojo.require("quickr.widgets.misc.connectors");
dojo.declare("quickr.widgets.menu._placeActionsMenu",
[quickr.widgets.menu.baseMenu],
{
linkText: "",
// Assumes that the page must reload in order to go between a place and a room
// TODO: Replace this with an event based system
isRoom: q_GeneralUtils.isRoom(),
postMixInProperties: function() {
this.inherited('postMixInProperties', arguments);
},
postCreate: function() {
// make dropdown menu
var label = (this.isRoom ? "PLACE.ACTIONS.ROOM_ACTIONS": "PLACE.ACTIONS.PLACE_ACTIONS");
this.createDropDownMenuOnButton(this.domNode, label, true);
this._populate();
if(dojo.isIE < 8) {
dojo.addOnLoad(function() {
if(document.body.dir == 'rtl') {
var container = dojo.query('#pagePlaceBar .lotusBtnContainer');
var actionsNode = container.query('.lotusBtnAction');
actionsNode.removeClass('lotusLeft');
actionsNode.addClass('lotusRight');
container.addContent(actionsNode[0], "last");
}
});
}
},
_item: function(label, action, bDisabled) {
return {label: q_LocaleUtils.getStringResource(label), action: action, disabled: bDisabled};
},
_addItem: function(label, action) {
this.addItem(q_LocaleUtils.getStringResource(label), action);
},
_addItemDisabled: function(label) {
this.addItemDisabled(q_LocaleUtils.getStringResource(label));
},
_createFromForm: function(formUnid, defFolder) {
if (!defFolder || defFolder == "") {
defFolder = this._getLibraryOrRoomIndex();
}
// TO DO: CHANGE THIS WHEN THERE IS A FOLDER PICKER!
var oEvt = new quickr.widgets.misc.eventlink(
{
event: this.ACTION.PAGE.CREATE,
args: { folderUnid: defFolder, formUnid: formUnid }
}
);
window.location.href = oEvt.getEventLinkFromProperties(oEvt.getLinkArguments());
oEvt.destroyRecursive();
},
_populate: function() {
if (q_BaseLoader.user.baseAccess > window.q_GeneralUtils.access.level.reader) {
var aForms = q_BaseLoader.defaultForms;
var createList = [];
var aForms = this._getFormsList(true);
for (var ii = 0; ii < aForms.length; ii++) {
var oFrm = aForms[ii];
if (this._isPredefinedForm(oFrm, "CustomLibrary"))
{
if (true == q_BaseLoader.ecm.enabled) createList.push(this._item("PLACE.PLACE_ACTIONS.NEW_WIDGET", dojo.hitch(this, "_getDefaultCreateFolder", dojo.hitch(this, "_createLibraryConnectorPage"), undefined),false));
}
else
if (this._isPredefinedForm(oFrm, "SingleUpload")) {
createList.push(this._item("PLACE.PLACE_ACTIONS.NEW_UPLOAD", dojo.hitch(this, "_getDefaultCreateFolder", dojo.hitch(this, "_createUpload"), undefined),false));
}
else
if (this._isPredefinedForm(oFrm, "ImportedFile")) {
createList.push(this._item("PLACE.PLACE_ACTIONS.NEW_IMPORTED_PAGE", dojo.hitch(this, "_getDefaultCreateFolder", dojo.hitch(this, "_createImportedPage"), undefined), false));
}
else
if (this._isPredefinedForm(oFrm, "List")) {
if (q_BaseLoader.user.baseAccess < window.q_GeneralUtils.access.level.manager && window.q_FolderUtils.getFirstFolderInTOC(null, false) == null) {
createList.push(this._item("PLACE.PLACE_ACTIONS.NEW_LIST", null, true));
} else {
createList.push(this._item("PLACE.PLACE_ACTIONS.NEW_LIST", dojo.hitch(this, "_getDefaultCreateFolder", dojo.hitch(this, "_createListFolder"), false), false));
}
}
else
if (this._isPredefinedForm(oFrm, "HTMLPage")) {
}
else
{
createList.push(this._item(oFrm.name, dojo.hitch(this, "_getDefaultCreateFolder", dojo.hitch(this, "_createFromForm", oFrm.unid), undefined),false));
}
}
//Comment by haoxiangyu on10/14/2011. for lineitem "Editor can not create folder"
//Originally, blow code makes editor can not create folder in room, but can do it in place
/*
if (q_BaseLoader.user.baseAccess < window.q_GeneralUtils.access.level.manager && window.q_FolderUtils.getFirstFolderInTOC(null, false) == null) {
createList.push(this._item("PLACE.PLACE_ACTIONS.NEW_FOLDER", null, true));
} else {
createList.push(this._item("PLACE.PLACE_ACTIONS.NEW_FOLDER", dojo.hitch(this, "_getDefaultCreateFolder", dojo.hitch(this, "_createFolder"), false)));
}*/
if (window.q_FolderUtils.canCreateFolder() ){
if (q_BaseLoader.user.baseAccess < window.q_GeneralUtils.access.level.manager && window.q_FolderUtils.getFirstFolderInTOC(null, false) == null) {
createList.push(new dijit.MenuSeparator());
createList.push(this._item("PLACE.PLACE_ACTIONS.NEW_FOLDER", null, true));
} else {
createList.push(new dijit.MenuSeparator());
createList.push(this._item("PLACE.PLACE_ACTIONS.NEW_FOLDER", dojo.hitch(this, "_getDefaultCreateFolder", dojo.hitch(this, "_createFolder"), false)));
}
}else{
createList.push(new dijit.MenuSeparator());
createList.push(this._item("PLACE.PLACE_ACTIONS.NEW_FOLDER", null, true));
}
//if no folders, add a disabled "New" item...
if (q_BaseLoader.user.baseAccess < window.q_GeneralUtils.access.level.manager && window.q_FolderUtils.getFirstFolderInTOC() == null) {
this._addItemDisabled("PLACE.PLACE_ACTIONS.NEW_PAGE");
} else {
var submenu = this.addSubmenu(q_LocaleUtils.getStringResource("PLACE.PLACE_ACTIONS.NEW_PAGE"), createList);
}
}
if (q_BaseLoader.user.baseAccess > window.q_GeneralUtils.access.level.reader && q_BaseLoader.user.canManageTOC == true) {
//this._addItemDisabled("PLACE.PLACE_ACTIONS.NEW_FORM"); // would use listfolder.htm
if ((q_BaseLoader.user.canManagePlace) && (q_BaseLoader.environment.createRoom) && (!q_BaseLoader.environment.isOffline)) {
this._addItem("PLACE.PLACE_ACTIONS.NEW_ROOM", dojo.hitch(this, "_createRoom"));
}
}
this.addSeparator();
//if(!q_BaseLoader.sametime.enabled85 && q_BaseLoader.sametime.serverLocation != '')
// this._addItem("PLACE.PLACE_ACTIONS.CHAT_WITH_MEMBERS", dojo.hitch(this, "_chatwithMembers"));
if (q_BaseLoader.place.show.sitemap) {
this._addItem("PLACE.PLACE_ACTIONS.SITE_MAP", dojo.hitch(this, "_goToSiteMap"));
}
if (q_BaseLoader.place.show.placeoffline == true && (this.getRoomName().toLowerCase() =="main.nsf") && (this.baseContext.user.DN != "Anonymous")) {
if (q_BaseLoader.offline.enabled && (dojo.isIE || dojo.isFF)) {
this._addItem("PLACE.PLACE_ACTIONS.OFFLINE", dojo.hitch(this, "_offline"));
}
else if (q_BaseLoader.offline.enabled == false) {
this._addItemDisabled("PLACE.PLACE_ACTIONS.OFFLINE");
}
}
if (q_BaseLoader.place.show.whatsNew) {
this._addItem("WHATS_NEW.TITLE", dojo.hitch(this, "_whatsNew"));
}
var showPrefs = window.connectors.showPreferences();
var showAddToConnectorsUI = window.connectors.showAddToConnectors();
if (showPrefs || (showAddToConnectorsUI == true )) //AVAILABLE))
{
this.addSeparator();
}
if (showPrefs) this._addItem(q_LocaleUtils.getStringResource("PLACE.PLACE_ACTIONS.PREFERENCES").replace("{0}", window.q_BaseLoader.place.title), dojo.hitch(this, "_showPreferences"));
if (showAddToConnectorsUI== 1) this._addItem(q_LocaleUtils.getStringResource("PLACE.PLACE_ACTIONS.ADD_TO_CONNECTORS").replace("{0}", window.q_BaseLoader.place.title), dojo.hitch(this, "_addToConnectors"));
this.publishEvent(this.ACTION.MENU.POPCOM.PLACE_ACTIONS, this._menu);
},
_publishEvent: function(e, a) {
if (typeof a == "undefined") a = new Object();
/* No need to put it in the url
var oEvt = new quickr.widgets.misc.eventlink(
{
event: e,
args: a
}
);
window.location.href = oEvt.getEventLinkFromProperties(oEvt.getLinkArguments());
oEvt.destroyRecursive();
*/
//just publish the event directly. No neeed to put it in the url
this.publishEvent(e, a);
},
_getFolderUnid: function()
{
var _LIBRARYFOLDER = 'CD0EF97D625305B90525670800167213';
var _ROOMINDEX = 'A7986FD2A9CD47090525670800167225';
return this.isRoom ? _ROOMINDEX : _LIBRARYFOLDER;
},
_getLibraryOrRoomIndex: function() {
var _PLACEINDEX = 'CE6A3D6B1F546C9405256708001671FF';
var _ROOMINDEX = 'A7986FD2A9CD47090525670800167225';
return this.isRoom ? _ROOMINDEX : _PLACEINDEX;
},
_chatwithMembers: function() {
openPeopleOnline();
},
_getDefaultCreateFolder: function(callback, bAllowIndex) {
if (typeof callback == "undefined") callback = null;
// SPR: #ESEO89JKU9
var unid = window.q_GeneralUtils.getUnidFromUrl();
if (unid) {
var folder = window.q_BaseLoader.allViews[unid];
if (typeof folder == "undefined") {
var type = window.q_GeneralUtils.getParameterFromUrl('type');
if (type == "0") {
var document_xml = "";
var document_url = window.q_RestUtils.getURI("document",unid) + "/feed?includePropertySheets=true&includeAllFields=true";
window.q_AjaxUtils.get ( {
sync: true,
url: document_url,
//I found out that the response is NOT declared as XML.
handleAs: "text",
timeout: 5000,
load: function(response, ioArgs){
document_xml = response;
},
// The ERROR function will be called in an error case.
error: function(response, ioArgs){
}
});
if(document_xml != null && document_xml != "") {
var document_xmldoc = window.q_XmlUtils.getXmlDocFromString(document_xml);
var document_FolderUNID = window.q_XmlUtils.getDocSnxValue(document_xmldoc, "h_FolderUNID");
if (document_FolderUNID) {
folder = window.q_BaseLoader.allViews[document_FolderUNID];
}
}
if (typeof folder == "undefined") {
return window.q_FolderUtils.getFirstFolderInTOC(callback, bAllowIndex);
}
} else {
return window.q_FolderUtils.getFirstFolderInTOC(callback, bAllowIndex);
}
}
// filter out Index, Forums, Calendar, Tasks, Customize and Trash in TOC
// also filter out Lists
if ((folder.systemName && (folder.systemName == "h_Index"
|| folder.systemName == "h_49B9AB68350FB355482576890021FE8D"
|| folder.systemName == "h_Calendar"
|| folder.systemName == "h_TaskList"
|| folder.systemName == "h_Tailor"
|| folder.systemName == "h_TrashList")) ||
(folder.folderSubStyle && (folder.folderSubStyle == "h_List"))) {
return window.q_FolderUtils.getFirstFolderInTOC(callback, bAllowIndex);
}
if (folder && folder.proxyUnid && folder.proxyUnid.length > 0) {
unid = folder.proxyUnid;
if (callback && typeof callback == "function") {
callback(unid);
}
return unid;
}
} else {
window.q_FolderUtils.getFirstFolderInTOC(callback, bAllowIndex);
}
},
_allowPageNav: function() {
return q_DocUtils.state.allowPageNav();
},
_createFolder: function(defFolder) {
if (!defFolder || defFolder == "") {
if (q_BaseLoader.user.baseAccess < window.q_GeneralUtils.access.level.manager) {//if not a manager need to alert the user they can't do this
window.q_GeneralUtils.qkrWarning(q_LocaleUtils.getStringResource("PLACE.PLACE_ACTIONS.NO_FOLDERS"));
return;
}
defFolder = "toc";
}
if (this._allowPageNav()) {
this.publishEvent(this.ACTION.FOLDER.CREATE, {folderUnid: defFolder});
}
},
_createRoom: function() {
if (this._allowPageNav()) {
this.publishEvent(this.ACTION.ROOM.CREATE, {});
}
},
_createImportedPage: function(defFolder) {
if (!defFolder || defFolder == "") {
defFolder = this._getLibraryOrRoomIndex();
}
if (this._allowPageNav()) {
this.publishEvent(
this.ACTION.MODALPAGE.CREATE,
{
folderUnid: defFolder,
modal: true,
formUnid: q_BaseLoader.defaultForms["ImportedFile"].unid,
createParms: {
xsl: "importedPage_create.xsl",
formName: "CreateModalPage",
title: "FOLDER.NEW_MENU.IMPORTED_PAGE"
}
}
);
}
},
_createPage: function(defFolder) {
if (!defFolder || defFolder == "") {
defFolder = this._getLibraryOrRoomIndex();
}
// TO DO: CHANGE THIS WHEN THERE IS A FOLDER PICKER!
var oEvt = new quickr.widgets.misc.eventlink(
{
event: this.ACTION.PAGE.CREATE,
args: {folderUnid: defFolder, formUnid: q_BaseLoader.defaultForms["BasicPage"].unid}
}
);
window.location.href = oEvt.getEventLinkFromProperties(oEvt.getLinkArguments());
oEvt.destroyRecursive();
},
_createLinkPage: function(defFolder) {
if (!defFolder || defFolder == "") {
defFolder = this._getLibraryOrRoomIndex();
}
// TO DO: CHANGE THIS WHEN THERE IS A FOLDER PICKER!
var oEvt = new quickr.widgets.misc.eventlink(
{
event: this.ACTION.PAGE.CREATE,
args: { folderUnid: defFolder, formUnid: q_BaseLoader.defaultForms["URLLinkPage"].unid }
}
);
window.location.href = oEvt.getEventLinkFromProperties(oEvt.getLinkArguments());
oEvt.destroyRecursive();
},
_createUpload: function(defFolder) {
// TO DO: CHANGE THIS WHEN THERE IS A FOLDER PICKER!
if (!defFolder || defFolder == "") {
defFolder = this._getLibraryOrRoomIndex();
}
if (this._allowPageNav()) {
this.publishEvent(this.ACTION.UPLOAD.CREATE,
{folderUnid: defFolder, modal: true, formUnid: q_BaseLoader.defaultForms["SingleUpload"].unid });
}
},
_createLibraryConnectorPage: function(defFolder) {
// TO DO: CHANGE THIS WHEN THERE IS A FOLDER PICKER!
if (!defFolder || defFolder == "") {
defFolder = this._getLibraryOrRoomIndex();
}
if (this._allowPageNav()) {
this.publishEvent(this.ACTION.CUSTOMLIBRARY.CREATE,
{ folderUnid: defFolder, modal: true, unid: q_BaseLoader.defaultForms["CustomLibrary"].unid });
}
},
_addToConnectors: function() {
window.location.href = window.connectors.getAddPlaceURL();
},
_showPreferences: function() {
window.connectors.showPreferencesDialog("");
},
_goToCreatePage: function() {
q_GeneralUtils.goToCreatePage();
},
_createListFolder: function (defFolder) {
if (this._allowPageNav()) {
if (!defFolder || defFolder == "") {
if (q_BaseLoader.user.baseAccess < window.q_GeneralUtils.access.level.manager) {//if not a manager need to alert the user they can't do this
window.q_GeneralUtils.qkrWarning(q_LocaleUtils.getStringResource("PLACE.PLACE_ACTIONS.NO_FOLDERS"));
return;
}
defFolder = "toc";
}
this.publishEvent(this.ACTION.LIST.CREATE, {folderUnid: defFolder});
}
},
_whatsNew: function () {
var oEvt = new quickr.widgets.misc.eventlink(
{
event: this.ACTION.PAGE.OPEN,
args: {systemName: "h_WhatsNew", period: "day" }
}
);
document.location.href = oEvt.getEventLinkFromProperties(oEvt.getLinkArguments());
oEvt.destroyRecursive();
},
_offline: function() {
this.publishEvent(
this.ACTION.DIALOG.OPEN,
{
fullScreen: true,
title: 'PLACE.PLACE_ACTIONS.OFFLINE_TITLE',
href: this.getRootUrl() + this.getBaseUrl() + '/$defaultview/A22C4328A85E9873052568B0005C0C98/?OpenDocument'
}
);
},
_goToSiteMap: function () {
var windowWidth=275;
var windowHeight=300;
window.currentRoom = { roomNsf: window.q_GeneralUtils.getRoomNSF() };
var remoteUrl = window.q_GeneralUtils.getPlaceUrl() + "/" + "Main.nsf" + "/?OpenDatabase&Form=h_SiteMapUI&NoWebCaching";
var remoteWindow = window.open( remoteUrl, "Remote", "resizable=yes,width=" + windowWidth + ",height=" + windowHeight + ",top=20,left=20,toolbar=no,scrollbars=yes,menubar=no,status=no");
if (remoteWindow != null) {
remoteWindow.focus();
}
}
});
dojo.declare("quickr.widgets.menu.placeActionsMenu",
[quickr.widgets.menu._placeActionsMenu],
{
}
);
Where would i change the width of this button?
Width is changed using CSS.
You can do it inline like...
<span class="lotusBtn lotusBtnAction" style="width:300px">
or in a CSS file like..
.lotusBtn{width:300px}

How to remove a property from an item which was added using jquery

The following jquery I am using in my jsp page for adding an autocomplete option to a text field which is having an id mytextfield.
jQuery(function(){
$("#mytextfield").autocomplete("popuppages/listall.jsp");
});
Within the same page, there are some cases in which I will have to remove this autocomplete feature from this text field. ( That is the same field will have to act as a textfield without autocomplete based on the user's inputs to previous fields and options)
Is there any way so that I could remove this newly added 'autocomplete' property from the particular item, that is from $("#mytextfield").
What actually I want to know is is there any option for removing added property
Incase anyone want to refer that autocomplete code, I have attached it below..
;(function($) {
$.fn.extend({
autocomplete: function(urlOrData, options) {
var isUrl = typeof urlOrData == "string";
options = $.extend({}, $.Autocompleter.defaults, {
url: isUrl ? urlOrData : null,
data: isUrl ? null : urlOrData,
delay: isUrl ? $.Autocompleter.defaults.delay : 10,
max: options && !options.scroll ? 10 : 150
}, options);
// if highlight is set to false, replace it with a do-nothing function
options.highlight = options.highlight || function(value) { return value; };
// if the formatMatch option is not specified, then use formatItem for backwards compatibility
options.formatMatch = options.formatMatch || options.formatItem;
return this.each(function() {
new $.Autocompleter(this, options);
});
},
result: function(handler) {
return this.bind("result", handler);
},
search: function(handler) {
return this.trigger("search", [handler]);
},
flushCache: function() {
return this.trigger("flushCache");
},
setOptions: function(options){
return this.trigger("setOptions", [options]);
},
unautocomplete: function() {
return this.trigger("unautocomplete");
}
});
$.Autocompleter = function(input, options) {
var KEY = {
UP: 38,
DOWN: 40,
DEL: 46,
TAB: 9,
RETURN: 13,
ESC: 27,
COMMA: 188,
PAGEUP: 33,
PAGEDOWN: 34,
BACKSPACE: 8
};
// Create $ object for input element
var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);
var timeout;
var previousValue = "";
var cache = $.Autocompleter.Cache(options);
var hasFocus = 0;
var lastKeyPressCode;
var config = {
mouseDownOnSelect: false
};
var select = $.Autocompleter.Select(options, input, selectCurrent, config);
var blockSubmit;
// prevent form submit in opera when selecting with return key
$.browser.opera && $(input.form).bind("submit.autocomplete", function() {
if (blockSubmit) {
blockSubmit = false;
return false;
}
});
// only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
$input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
// a keypress means the input has focus
// avoids issue where input had focus before the autocomplete was applied
hasFocus = 1;
// track last key pressed
lastKeyPressCode = event.keyCode;
switch(event.keyCode) {
case KEY.UP:
event.preventDefault();
if ( select.visible() ) {
select.prev();
} else {
onChange(0, true);
}
break;
case KEY.DOWN:
event.preventDefault();
if ( select.visible() ) {
select.next();
} else {
onChange(0, true);
}
break;
case KEY.PAGEUP:
event.preventDefault();
if ( select.visible() ) {
select.pageUp();
} else {
onChange(0, true);
}
break;
case KEY.PAGEDOWN:
event.preventDefault();
if ( select.visible() ) {
select.pageDown();
} else {
onChange(0, true);
}
break;
// matches also semicolon
case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
case KEY.TAB:
case KEY.RETURN:
if( selectCurrent() ) {
// stop default to prevent a form submit, Opera needs special handling
event.preventDefault();
blockSubmit = true;
return false;
}
break;
case KEY.ESC:
select.hide();
break;
default:
clearTimeout(timeout);
timeout = setTimeout(onChange, options.delay);
break;
}
}).focus(function(){
// track whether the field has focus, we shouldn't process any
// results if the field no longer has focus
hasFocus++;
}).blur(function() {
hasFocus = 0;
if (!config.mouseDownOnSelect) {
hideResults();
}
}).click(function() {
// show select when clicking in a focused field
if ( hasFocus++ > 1 && !select.visible() ) {
onChange(0, true);
}
}).bind("search", function() {
// TODO why not just specifying both arguments?
var fn = (arguments.length > 1) ? arguments[1] : null;
function findValueCallback(q, data) {
var result;
if( data && data.length ) {
for (var i=0; i < data.length; i++) {
if( data[i].result.toLowerCase() == q.toLowerCase() ) {
result = data[i];
break;
}
}
}
if( typeof fn == "function" ) fn(result);
else $input.trigger("result", result && [result.data, result.value]);
}
$.each(trimWords($input.val()), function(i, value) {
request(value, findValueCallback, findValueCallback);
});
}).bind("flushCache", function() {
cache.flush();
}).bind("setOptions", function() {
$.extend(options, arguments[1]);
// if we've updated the data, repopulate
if ( "data" in arguments[1] )
cache.populate();
}).bind("unautocomplete", function() {
select.unbind();
$input.unbind();
$(input.form).unbind(".autocomplete");
});
function selectCurrent() {
var selected = select.selected();
if( !selected )
return false;
var v = selected.result;
previousValue = v;
if ( options.multiple ) {
var words = trimWords($input.val());
if ( words.length > 1 ) {
var seperator = options.multipleSeparator.length;
var cursorAt = $(input).selection().start;
var wordAt, progress = 0;
$.each(words, function(i, word) {
progress += word.length;
if (cursorAt <= progress) {
wordAt = i;
return false;
}
progress += seperator;
});
words[wordAt] = v;
// TODO this should set the cursor to the right position, but it gets overriden somewhere
//$.Autocompleter.Selection(input, progress + seperator, progress + seperator);
v = words.join( options.multipleSeparator );
}
v += options.multipleSeparator;
}
$input.val(v);
hideResultsNow();
$input.trigger("result", [selected.data, selected.value]);
return true;
}
function onChange(crap, skipPrevCheck) {
if( lastKeyPressCode == KEY.DEL ) {
select.hide();
return;
}
var currentValue = $input.val();
if ( !skipPrevCheck && currentValue == previousValue )
return;
previousValue = currentValue;
currentValue = lastWord(currentValue);
if ( currentValue.length >= options.minChars) {
$input.addClass(options.loadingClass);
if (!options.matchCase)
currentValue = currentValue.toLowerCase();
request(currentValue, receiveData, hideResultsNow);
} else {
stopLoading();
select.hide();
}
};
function trimWords(value) {
if (!value)
return [""];
if (!options.multiple)
return [$.trim(value)];
return $.map(value.split(options.multipleSeparator), function(word) {
return $.trim(value).length ? $.trim(word) : null;
});
}
function lastWord(value) {
if ( !options.multiple )
return value;
var words = trimWords(value);
if (words.length == 1)
return words[0];
var cursorAt = $(input).selection().start;
if (cursorAt == value.length) {
words = trimWords(value)
} else {
words = trimWords(value.replace(value.substring(cursorAt), ""));
}
return words[words.length - 1];
}
// fills in the input box w/the first match (assumed to be the best match)
// q: the term entered
// sValue: the first matching result
function autoFill(q, sValue){
// autofill in the complete box w/the first match as long as the user hasn't entered in more data
// if the last user key pressed was backspace, don't autofill
if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) {
// fill in the value (keep the case the user has typed)
$input.val($input.val() + sValue.substring(lastWord(previousValue).length));
// select the portion of the value not typed by the user (so the next character will erase)
$(input).selection(previousValue.length, previousValue.length + sValue.length);
}
};
function hideResults() {
clearTimeout(timeout);
timeout = setTimeout(hideResultsNow, 200);
};
function hideResultsNow() {
var wasVisible = select.visible();
select.hide();
clearTimeout(timeout);
stopLoading();
if (options.mustMatch) {
// call search and run callback
$input.search(
function (result){
// if no value found, clear the input box
if( !result ) {
if (options.multiple) {
var words = trimWords($input.val()).slice(0, -1);
$input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") );
}
else {
$input.val( "" );
$input.trigger("result", null);
}
}
}
);
}
};
function receiveData(q, data) {
if ( data && data.length && hasFocus ) {
stopLoading();
select.display(data, q);
autoFill(q, data[0].value);
select.show();
} else {
hideResultsNow();
}
};
function request(term, success, failure) {
if (!options.matchCase)
term = term.toLowerCase();
var data = cache.load(term);
// recieve the cached data
if (data && data.length) {
success(term, data);
// if an AJAX url has been supplied, try loading the data now
} else if( (typeof options.url == "string") && (options.url.length > 0) ){
var extraParams = {
timestamp: +new Date()
};
$.each(options.extraParams, function(key, param) {
extraParams[key] = typeof param == "function" ? param() : param;
});
$.ajax({
// try to leverage ajaxQueue plugin to abort previous requests
mode: "abort",
// limit abortion to this input
port: "autocomplete" + input.name,
dataType: options.dataType,
url: options.url,
data: $.extend({
q: lastWord(term),
limit: options.max
}, extraParams),
success: function(data) {
var parsed = options.parse && options.parse(data) || parse(data);
cache.add(term, parsed);
success(term, parsed);
}
});
} else {
// if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
select.emptyList();
failure(term);
}
};
function parse(data) {
var parsed = [];
var rows = data.split("\n");
for (var i=0; i < rows.length; i++) {
var row = $.trim(rows[i]);
if (row) {
row = row.split("|");
parsed[parsed.length] = {
data: row,
value: row[0],
result: options.formatResult && options.formatResult(row, row[0]) || row[0]
};
}
}
return parsed;
};
function stopLoading() {
$input.removeClass(options.loadingClass);
};
};
$.Autocompleter.defaults = {
inputClass: "ac_input",
resultsClass: "ac_results",
loadingClass: "ac_loading",
minChars: 1,
delay: 400,
matchCase: false,
matchSubset: true,
matchContains: false,
cacheLength: 10,
max: 100,
mustMatch: false,
extraParams: {},
selectFirst: true,
formatItem: function(row) { return row[0]; },
formatMatch: null,
autoFill: false,
width: 0,
multiple: false,
multipleSeparator: ", ",
highlight: function(value, term) {
return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
},
scroll: true,
scrollHeight: 180
};
$.Autocompleter.Cache = function(options) {
var data = {};
var length = 0;
function matchSubset(s, sub) {
if (!options.matchCase)
s = s.toLowerCase();
var i = s.indexOf(sub);
if (options.matchContains == "word"){
i = s.toLowerCase().search("\\b" + sub.toLowerCase());
}
if (i == -1) return false;
return i == 0 || options.matchContains;
};
function add(q, value) {
if (length > options.cacheLength){
flush();
}
if (!data[q]){
length++;
}
data[q] = value;
}
function populate(){
if( !options.data ) return false;
// track the matches
var stMatchSets = {},
nullData = 0;
// no url was specified, we need to adjust the cache length to make sure it fits the local data store
if( !options.url ) options.cacheLength = 1;
// track all options for minChars = 0
stMatchSets[""] = [];
// loop through the array and create a lookup structure
for ( var i = 0, ol = options.data.length; i < ol; i++ ) {
var rawValue = options.data[i];
// if rawValue is a string, make an array otherwise just reference the array
rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;
var value = options.formatMatch(rawValue, i+1, options.data.length);
if ( value === false )
continue;
var firstChar = value.charAt(0).toLowerCase();
// if no lookup array for this character exists, look it up now
if( !stMatchSets[firstChar] )
stMatchSets[firstChar] = [];
// if the match is a string
var row = {
value: value,
data: rawValue,
result: options.formatResult && options.formatResult(rawValue) || value
};
// push the current match into the set list
stMatchSets[firstChar].push(row);
// keep track of minChars zero items
if ( nullData++ < options.max ) {
stMatchSets[""].push(row);
}
};
// add the data items to the cache
$.each(stMatchSets, function(i, value) {
// increase the cache size
options.cacheLength++;
// add to the cache
add(i, value);
});
}
// populate any existing data
setTimeout(populate, 25);
function flush(){
data = {};
length = 0;
}
return {
flush: flush,
add: add,
populate: populate,
load: function(q) {
if (!options.cacheLength || !length)
return null;
/*
* if dealing w/local data and matchContains than we must make sure
* to loop through all the data collections looking for matches
*/
if( !options.url && options.matchContains ){
// track all matches
var csub = [];
// loop through all the data grids for matches
for( var k in data ){
// don't search through the stMatchSets[""] (minChars: 0) cache
// this prevents duplicates
if( k.length > 0 ){
var c = data[k];
$.each(c, function(i, x) {
// if we've got a match, add it to the array
if (matchSubset(x.value, q)) {
csub.push(x);
}
});
}
}
return csub;
} else
// if the exact item exists, use it
if (data[q]){
return data[q];
} else
if (options.matchSubset) {
for (var i = q.length - 1; i >= options.minChars; i--) {
var c = data[q.substr(0, i)];
if (c) {
var csub = [];
$.each(c, function(i, x) {
if (matchSubset(x.value, q)) {
csub[csub.length] = x;
}
});
return csub;
}
}
}
return null;
}
};
};
$.Autocompleter.Select = function (options, input, select, config) {
var CLASSES = {
ACTIVE: "ac_over"
};
var listItems,
active = -1,
data,
term = "",
needsInit = true,
element,
list;
// Create results
function init() {
if (!needsInit)
return;
element = $("<div/>")
.hide()
.addClass(options.resultsClass)
.css("position", "absolute")
.appendTo(document.body);
list = $("<ul/>").appendTo(element).mouseover( function(event) {
if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
$(target(event)).addClass(CLASSES.ACTIVE);
}
}).click(function(event) {
$(target(event)).addClass(CLASSES.ACTIVE);
select();
// TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
input.focus();
return false;
}).mousedown(function() {
config.mouseDownOnSelect = true;
}).mouseup(function() {
config.mouseDownOnSelect = false;
});
if( options.width > 0 )
element.css("width", options.width);
needsInit = false;
}
function target(event) {
var element = event.target;
while(element && element.tagName != "LI")
element = element.parentNode;
// more fun with IE, sometimes event.target is empty, just ignore it then
if(!element)
return [];
return element;
}
function moveSelect(step) {
listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
movePosition(step);
var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
if(options.scroll) {
var offset = 0;
listItems.slice(0, active).each(function() {
offset += this.offsetHeight;
});
if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
} else if(offset < list.scrollTop()) {
list.scrollTop(offset);
}
}
};
function movePosition(step) {
active += step;
if (active < 0) {
active = listItems.size() - 1;
} else if (active >= listItems.size()) {
active = 0;
}
}
function limitNumberOfItems(available) {
return options.max && options.max < available
? options.max
: available;
}
function fillList() {
list.empty();
var max = limitNumberOfItems(data.length);
for (var i=0; i < max; i++) {
if (!data[i])
continue;
var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term);
if ( formatted === false )
continue;
var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
$.data(li, "ac_data", data[i]);
}
listItems = list.find("li");
if ( options.selectFirst ) {
listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
active = 0;
}
// apply bgiframe if available
if ( $.fn.bgiframe )
list.bgiframe();
}
return {
display: function(d, q) {
init();
data = d;
term = q;
fillList();
},
next: function() {
moveSelect(1);
},
prev: function() {
moveSelect(-1);
},
pageUp: function() {
if (active != 0 && active - 8 < 0) {
moveSelect( -active );
} else {
moveSelect(-8);
}
},
pageDown: function() {
if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
moveSelect( listItems.size() - 1 - active );
} else {
moveSelect(8);
}
},
hide: function() {
element && element.hide();
listItems && listItems.removeClass(CLASSES.ACTIVE);
active = -1;
},
visible : function() {
return element && element.is(":visible");
},
current: function() {
return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
},
show: function() {
var offset = $(input).offset();
element.css({
width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
top: offset.top + input.offsetHeight,
left: offset.left
}).show();
if(options.scroll) {
list.scrollTop(0);
list.css({
maxHeight: options.scrollHeight,
overflow: 'auto'
});
if($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
var listHeight = 0;
listItems.each(function() {
listHeight += this.offsetHeight;
});
var scrollbarsVisible = listHeight > options.scrollHeight;
list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight );
if (!scrollbarsVisible) {
// IE doesn't recalculate width when scrollbar disappears
listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) );
}
}
}
},
selected: function() {
var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
return selected && selected.length && $.data(selected[0], "ac_data");
},
emptyList: function (){
list && list.empty();
},
unbind: function() {
element && element.remove();
}
};
};
$.fn.selection = function(start, end) {
if (start !== undefined) {
return this.each(function() {
if( this.createTextRange ){
var selRange = this.createTextRange();
if (end === undefined || start == end) {
selRange.move("character", start);
selRange.select();
} else {
selRange.collapse(true);
selRange.moveStart("character", start);
selRange.moveEnd("character", end);
selRange.select();
}
} else if( this.setSelectionRange ){
this.setSelectionRange(start, end);
} else if( this.selectionStart ){
this.selectionStart = start;
this.selectionEnd = end;
}
});
}
var field = this[0];
if ( field.createTextRange ) {
var range = document.selection.createRange(),
orig = field.value,
teststring = "<->",
textLength = range.text.length;
range.text = teststring;
var caretAt = field.value.indexOf(teststring);
field.value = orig;
this.selection(caretAt, caretAt + textLength);
return {
start: caretAt,
end: caretAt + textLength
}
} else if( field.selectionStart !== undefined ){
return {
start: field.selectionStart,
end: field.selectionEnd
}
}
};
})(jQuery);
Looks like you are looking for destroy or disable method of autocomplete..
Check Documentation...
destroy
disable
$("#mytextfield").autocomplete( "destroy" )
$("#mytextfield").autocomplete( "disable" )
The difference is after destroy you cannot enable it back...but after disable by using enable you can enable it back..
You can use .removeAttr()
$(target).removeAttr('propertyName');
This will totally remove that property.
But if you want to change any property then use .prop() or .attr()

How to import data of gmail contacts, using javascript Google Contact API, in more detailed format?

I'm using code from this page http://code.google.com/apis/contacts/docs/1.0/developers_guide_js.html to get list of gmail contacts. Actually it works ok, but I get data of name, address, etc like a simple string, with "\n" as separator, for example:
<script type="text/javascript">
var contactsService;
var scope = 'https://www.google.com/m8/feeds';
function setupContactsService() {
//contactsService = new google.gdata.contacts.ContactsService('exampleCo-exampleApp-1.0');
contactsService = new google.gdata.contacts.ContactsService('GoogleInc-jsguide-1.0');
}
function getMyContacts() {
var contactsFeedUri = 'https://www.google.com/m8/feeds/contacts/default/full'; //?max-results=9999&alt=json&v=3.0
var query = new google.gdata.contacts.ContactQuery(contactsFeedUri);
setupContactsService();
contactsService.getContactFeed(query, handleContactsFeed, handleError);
}
var handleContactsFeed = function(result) {
var entries = result.feed.entry;
for (var i = 0; i < entries.length; i++) {
var entry = entries[i];
var addrs = entry.getPostalAddresses();
var name = entry.getTitle();
// logging
console.log(addrs[0]);
console.log(name);
}
}
function handleError(e) {
alert(e.cause ? e.cause.statusText : e.message);
}
</script>
it gives me an object where name and address values are simple strings.
Can I get somehow data in like associative array format, where address will contains separate values of street, zip, city, country; and name separate values of first name, last name etc.
Like:
{
"type": "address",
"value":
{
"street": "Starret 1234",
"city": "City name",
"stateOrProvince": "ca",
"postalCode": "73000",
"country": "USA"
}
},
{
"type": "name",
"value":
{
"firstName": "Allen",
"lastName" : "Iverson",
.....
}
}
Thanks in advance!
Seems I found an answer, for get more detailed and formatted info need to add additional parameter to contactsFeedUri for google.gdata.contacts.ContactQuery.
This additional parameter is: ?v=3.0
So in my case function will looks like:
function getMyContacts() {
var contactsFeedUri = 'https://www.google.com/m8/feeds/contacts/default/full?v=3.0&alt=json';
var query = new google.gdata.contacts.ContactQuery(contactsFeedUri);
setupContactsService();
contactsService.getContactFeed(query, handleContactsFeed, handleError);
}
And for get necessary data I create a simple obj, which can be useful for somebody:
function contactEntry(entry) {
this.entry = entry;
this.testEntry = function() {
alert( 'test entry' )
};
this.getFirstName = function() {
if ((entry.gd$name == null) || (entry.gd$name.gd$givenName == null) || (entry.gd$name.gd$givenName.$t == null)) {
return '';
} else {
return entry.gd$name.gd$givenName.$t;
}
};
this.getLastName = function() {
if ((entry.gd$name == null) || (entry.gd$name.gd$familyName == null) || (entry.gd$name.gd$familyName.$t == null)) {
return '';
} else {
return entry.gd$name.gd$familyName.$t;
}
};
this.getAdditionalName = function() {
if ((entry.gd$name == null) || (entry.gd$name.gd$AdditionalName == null) || (entry.gd$name.gd$AdditionalName.$t == null)) {
return '';
} else {
return entry.gd$name.gd$familyName.$t;
}
};
this.getEmail = function() {
if ((entry.gd$email == null) || (entry.gd$email.length == 0) || (entry.gd$email[0].address == null)) {
return '';
} else {
return entry.gd$email[0].address;
}
};
this.getStreet = function() {
if (!this._addrExists() || (entry.gd$structuredPostalAddress[0].gd$street == null)) {
return '';
} else {
return entry.gd$structuredPostalAddress[0].gd$street.$t;
}
};
this.getCity = function() {
if (!this._addrExists() || (entry.gd$structuredPostalAddress[0].gd$city == null)) {
return '';
} else {
return entry.gd$structuredPostalAddress[0].gd$city.$t;
}
};
this.getCountry = function() {
if (!this._addrExists() || (entry.gd$structuredPostalAddress[0].gd$country == null)) {
return '';
} else {
return entry.gd$structuredPostalAddress[0].gd$country.$t;
}
};
this.getPostcode = function() {
if (!this._addrExists() || (entry.gd$structuredPostalAddress[0].gd$postcode == null)) {
return '';
} else {
return entry.gd$structuredPostalAddress[0].gd$postcode.$t;
}
};
this.getPhone = function() {
if ((entry.gd$phoneNumber == null) || (entry.gd$phoneNumber.length == 0) || (entry.gd$phoneNumber[0].$t == null)) {
return '';
} else {
return entry.gd$phoneNumber[0].$t
}
};
this.getOrganization = function() {
if ((entry.gd$organization == null) || (entry.gd$organization.length == 0) || (entry.gd$organization[0].getOrgName() == null)) {
return '';
} else {
return entry.gd$organization[0].getOrgName().getValue();
}
};
this.getBirthday = function() {
if ((entry.gContact$birthday == null) || (entry.gContact$birthday.when == null)) {
return '';
} else {
return entry.gContact$birthday.when;
}
};
this.getEvent = function() {
if ((entry.gContact$event == null) || (entry.gContact$event.length == 0) || (entry.gContact$event[0].gd$when == null)) {
return '';
} else {
return entry.gContact$event[0].gd$when.startTime;
}
};
// protected methods
this._addrExists = function() {
if ((entry.gd$structuredPostalAddress == null) || (entry.gd$structuredPostalAddress.length == 0)) {
return false;
}
return true;
};
}
It can be used in this way:
var handleContactsFeed = function(result) {
var entries = result.feed.entry;
var contact = new contactEntry(entries[0]);
var address = {};
address['fname'] = contact.getFirstName();
address['lname'] = contact.getLastName() + (contact.getAdditionalName() != '' ? ' ' + contact.getAdditionalName() : '');
address['address'] = contact.getStreet();
address['city'] = contact.getCity();
address['country'] = contact.getCountry();
address['zip'] = contact.getPostcode();
address['phone'] = contact.getPhone();
address['mail'] = contact.getEmail();
address['organization'] = contact.getOrganization();
address['birthday'] = contact.getBirthday();
address['event'] = contact.getEvent();
}

Categories

Resources