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

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.

Related

TypeError on load .js

I have code before , but console showing TypeError: $ is not function on line 1 :(
Can you help me with reason? Thanks!
$('.day.event').parent().each(function (i, e) {
var element = $(e);
var prevElement=$(e).prev();
var hasPrevElement = true;
if(prevElement.size() === 0) {
var prevRow = element.parent().prev();
if(prevRow.size() === 0) {
hasPrevElement = false;
}
prevElement = prevRow.children().last();
}
var nextElement=$(e).next();
var hasNextElement = true;
if(nextElement.size() === 0) {
var nextRow = element.parent().next();
if(nextRow.size() === 0) {
hasNextElement = false;
}
nextElement = nextRow.children().first();
}
if(hasPrevElement && prevElement.children().first().attr("class").indexOf("event") === -1 || !hasPrevElement) {
element.addClass('first-day')
}
if(hasNextElement && nextElement.children().first().attr("class").indexOf("event") === -1) {
nextElement.addClass('after-event');
}
});
You should import jQuery library before the code above as #Wendelin said or check the path of your file

Disable/Enable HTML Button based on Existing Functions

I have a function running onclick from HTML button and need to add disabling the button on success but NOT on return = false.
I've tried toggling, disabling directly in the HTML and inserting changing the HTML attribute within my current function.
var amtCount = 0;
function addToLineItem()
{
var totalAmount = 0.0;
var valid = true;
var difference = [];
$.each($(".tbodys tr"),function(index,vs)
{
for(var tdcnt = 0; tdcnt < vs.children.length - 1; tdcnt++)
{
if(tdcnt != 5)
if(vs.children[tdcnt].firstElementChild.value == "" || vs.children[tdcnt].firstElementChild.value == undefined)
valid = false;
}
if(vs.children[9].firstChild.value != "" && vs.children[9].firstChild.value != undefined)
{
RMID.push(vs.children[9].firstChild.value);
}
});
if(CodingListItem.length > 0)
{
difference = arr_diff(CodingListItem,RMID);
}
if(valid == false)
{
alert("Message");
return false;
}
if($("#aprDate").val() == "")
{
alert("Please date.");
return false;
}
$.each($(".tbodys tr .nine"),function(index,vs){
totalAmount += parseFloat(vs.firstElementChild.value.replace(/,/g, ""));
});
if($("#Total")[0].innerText == "")
{
alert("Please .");
return false;
}
//if(parseFloat($("#invTotal").val().replace(/,/g, "")) != totalAmount)
if(parseFloat($("#invTotal").val().replace(/,/g, "")) != parseFloat($("#Total")[0].innerText.replace(/,/g, "")))
{
alert("total amount does not match.");
return false;
}
SP.SOD.executeFunc("sp.js", 'SP.ClientContext', function()
{
try
{
var clientContext = SP.ClientContext.get_current();
var web = clientContext.get_web();
var oList = clientContext.get_web().get_lists().getByTitle('Invoice');
if(difference.length > 0)
{
$.each(difference, function( index, value )
{
deleteListItem(parseInt(value));
});
}
$.each($(".tbodys tr"),function(i,v)
{
if(v.children[9].firstChild.value != "" && v.children[9].firstChild.value != undefined)
{
var itemType1 = GetItemTypeForListName("InvoiceLineItem");
var item1 = {
"__metadata": { "type": itemType1 },
"Title": v.children[0].firstChild.value,
"InvoiceIDId": parseInt(INV),
"Entity": v.children[1].firstChild.value,
"MS": v.children[2].firstChild.value,
"LocationId": parseInt(v.children[3].firstChild.value),
"DepartmentId": parseInt(v.children[4].firstChild.value),
"Account": v.children[5].children[1].options[v.children[5].children[1].selectedIndex].text,
"SubAccount": v.children[6].firstChild.value,
"GLCode": v.children[7].firstChild.value,
"Amount": v.children[8].firstChild.value
};
updateListItem(parseInt(v.children[9].firstChild.value), "Invoice Approval and Coding", _spPageContextInfo.webAbsoluteUrl, item1, function () {
amtCount = amtCount + 1;
updatePendingInvoice(amtCount);
}, function () { errorMsg = true; });
}
else
{
var itemCreateInfo = new SP.ListItemCreationInformation();
var oListItem = oList.addItem(itemCreateInfo);
oListItem.set_item('Title', v.children[0].firstChild.value); //Line Description
oListItem.set_item('InvoiceID', INV);
oListItem.set_item('Entity', v.children[1].firstChild.value);
oListItem.set_item('MS', v.children[2].firstChild.value);
oListItem.set_item('Location', v.children[3].firstChild.value);
oListItem.set_item('Department', v.children[4].firstChild.value);
oListItem.set_item('Account', v.children[5].children[1].options[v.children[5].children[1].selectedIndex].text);
oListItem.set_item('SubAccount', v.children[6].firstChild.value);
oListItem.set_item('GLCode', v.children[7].firstChild.value);
oListItem.set_item('Amount', v.children[8].firstChild.value);
oListItem.set_item('Date', $("#aprDate").val());
oListItem.set_item('Comment', $("#cmt").val());
oListItem.update();
clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);
}
});
}
catch(err)
{
alert(err.message);
}
});
}
function onQuerySucceeded()
{
amtCount = amtCount + 1;
updatePendingInvoice(amtCount);
}
function onQueryFailed(sender, args)
{
alert('not inserted');
}
This runs fine but if the HTML Button is clicked quickly, the function runs and creates duplicate data.
You should disable the button while you are acting on the click. Then the user cannot queue up another update until the first one finishes. Set an internal variable saying that the work is in progress, disable the button, and then clear the flag when you get the result (success or fail).
For instance:
$("#btnSubmit").click(function() {
$("#btnSubmit").prop("disabled", true);
// do your work here, waiting for success or failure
$('#btnSubmit').prop("disabled", false);
})
or:
$("button").click(function(e) {
$(e.currentTarget).prop('disabled', true);
window.setTimeout(function() {
$(e.currentTarget).prop('disabled', false);
}, 5000);
})
I found what I needed and with some experimentation with where to put the "disabled", false lines was able to get to the solution. I got the simple code from Palash
https://stackoverflow.com/users/1823841/palaѕн
All versions of jQuery after 1.6
Disabling and enabling a html input button
Thank you all for helping... New Code....
var amtCount = 0;
function addToLineItem()
{
**$("#IApprove").attr("disabled", true);**
var totalAmount = 0.0;
var valid = true;
var difference = [];
$.each($(".tbodys tr"),function(index,vs)
{
for(var tdcnt = 0; tdcnt < vs.children.length - 1; tdcnt++)
{
if(tdcnt != 5)
if(vs.children[tdcnt].firstElementChild.value == "" || vs.children[tdcnt].firstElementChild.value == undefined)
valid = false;
}
if(vs.children[9].firstChild.value != "" && vs.children[9].firstChild.value != undefined)
{
RMID.push(vs.children[9].firstChild.value);
}
});
if(CodingListItem.length > 0)
{
difference = arr_diff(CodingListItem,RMID);
}
if(valid == false)
{
alert("Please add Line Items with Required Information. GL coding missing.");
**$("#IApprove").attr("disabled", false);**
return false;
}
if($("#aprDate").val() == "")
{
alert("Please add approver date.");
**$("#IApprove").attr("disabled", false);**
return false;
}
$.each($(".tbodys tr .nine"),function(index,vs){
totalAmount += parseFloat(vs.firstElementChild.value.replace(/,/g, ""));
});
if($("#Total")[0].innerText == "")
{
alert("Please add Line items.");
**$("#IApprove").attr("disabled", false);**
return false;
}
//if(parseFloat($("#invTotal").val().replace(/,/g, "")) != totalAmount)
if(parseFloat($("#invTotal").val().replace(/,/g, "")) != parseFloat($("#Total")[0].innerText.replace(/,/g, "")))
{
alert("Line item's total amount does not match with total invoice amount.");
**$("#IApprove").attr("disabled", false);**
return false;
}
SP.SOD.executeFunc("sp.js", 'SP.ClientContext', function()
{
try
{
var clientContext = SP.ClientContext.get_current();
var web = clientContext.get_web();
var oList = clientContext.get_web().get_lists().getByTitle('Invoice Approval and Coding');
///////////// Delete Items //////////////////
if(difference.length > 0)
{
$.each(difference, function( index, value )
{
deleteListItem(parseInt(value));
});
}
$.each($(".tbodys tr"),function(i,v)
{
if(v.children[9].firstChild.value != "" && v.children[9].firstChild.value != undefined)
{
var itemType1 = GetItemTypeForListName("InvoiceLineItem");
var item1 = {
"__metadata": { "type": itemType1 },
"Title": v.children[0].firstChild.value,
"InvoiceIDId": parseInt(INV),
"Entity": v.children[1].firstChild.value,
"MS": v.children[2].firstChild.value,
"LocationId": parseInt(v.children[3].firstChild.value),
"DepartmentId": parseInt(v.children[4].firstChild.value),
"Account": v.children[5].children[1].options[v.children[5].children[1].selectedIndex].text,
"SubAccount": v.children[6].firstChild.value,
"GLCode": v.children[7].firstChild.value,
"Amount": v.children[8].firstChild.value
};
updateListItem(parseInt(v.children[9].firstChild.value), "Invoice Approval and Coding", _spPageContextInfo.webAbsoluteUrl, item1, function () {
amtCount = amtCount + 1;
updatePendingInvoice(amtCount);
}, function () { errorMsg = true; });
}
else
{
var itemCreateInfo = new SP.ListItemCreationInformation();
var oListItem = oList.addItem(itemCreateInfo);
oListItem.set_item('Title', v.children[0].firstChild.value); //Line Description
oListItem.set_item('InvoiceID', INV);
oListItem.set_item('Entity', v.children[1].firstChild.value);
oListItem.set_item('MS', v.children[2].firstChild.value);
oListItem.set_item('Location', v.children[3].firstChild.value);
oListItem.set_item('Department', v.children[4].firstChild.value);
oListItem.set_item('Account', v.children[5].children[1].options[v.children[5].children[1].selectedIndex].text);
oListItem.set_item('SubAccount', v.children[6].firstChild.value);
oListItem.set_item('GLCode', v.children[7].firstChild.value);
oListItem.set_item('Amount', v.children[8].firstChild.value);
oListItem.set_item('Date', $("#aprDate").val());
oListItem.set_item('Comment', $("#cmt").val());
oListItem.update();
clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);
}
});
}
catch(err)
{
alert(err.message);
}
});
}

How to hide a dynamically generated div

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.

Validate form function jump to error?

I have a form with a validation script that works perfectly. I would however like the form to jump to the fields that doesn't validate or display the name of the fields in the error message.
The code I use to validate is:
else
{
var valid = document.formvalidator.isValid(f);
}
if (flag == 0 || valid == true) {
f.check.value = '<?php echo JUtility::getToken(); ?>';//send token
}
else {
alert('There was an error with the fields..');
return false;
}
return true;
How can I get the alert to name the fields that need to be filled in correctly or jump to the specific field?
Edited ----------
Hi,
Thanks for help so far. I'm very new to JS. The form is in a component of Joomla.
The full function that validates the form is
function validateForm(f){
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer"){
var flag = 0;
for (var i=0;i < f.elements.length; i++) {
el = f.elements[i];
if ($(el).hasClass('required')) {
var idz= $(el).getProperty('id');
if(document.getElementById(idz)){
if (!document.getElementById(idz).value) {
document.formvalidator.handleResponse(false, el);
flag = flag + 1;
}
}
}
}
}
else {
var valid = document.formvalidator.isValid(f);
}
if(flag == 0 || valid == true){
f.check.value='<?php echo JUtility::getToken(); ?>';//send token
}
else {
alert('<?php echo JText::_('JBJOBS_FIEDS_HIGHLIGHTED_RED_COMPULSORY'); ?>');
return false;
}
return true;
}
External js file:
var JFormValidator = new Class(
{
initialize : function() {
this.handlers = Object();
this.custom = Object();
this.setHandler("username", function(b) {
regex = new RegExp("[<|>|\"|'|%|;|(|)|&]", "i");
return !regex.test(b)
});
this.setHandler("password", function(b) {
regex = /^\S[\S ]{2,98}\S$/;
return regex.test(b)
});
this.setHandler('passverify',
function (value) {
return ($('password').value == value);
}
); // added March 2011
this.setHandler("numeric", function(b) {
regex = /^(\d|-)?(\d|,)*\.?\d*$/;
return regex.test(b)
});
this
.setHandler(
"email",
function(b) {
regex = /^[a-zA-Z0-9._-]+(\+[a-zA-Z0-9._-]+)*#([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
return regex.test(b)
});
var a = $$("form.form-validate");
a.each(function(b) {
this.attachToForm(b)
}, this)
},
setHandler : function(b, c, a) {
a = (a == "") ? true : a;
this.handlers[b] = {
enabled : a,
exec : c
}
},
attachToForm : function(a) {
a.getElements("input,textarea,select")
.each(
function(b) {
if (($(b).get("tag") == "input" || $(b)
.get("tag") == "button")
&& $(b).get("type") == "submit") {
if (b.hasClass("validate")) {
b.onclick = function() {
return document.formvalidator
.isValid(this.form)
}
}
} else {
b.addEvent("blur", function() {
return document.formvalidator
.validate(this)
})
}
})
},
validate : function(c) {
c = $(c);
if (c.get("disabled")) {
this.handleResponse(true, c);
return true
}
if (c.hasClass("required")) {
if (c.get("tag") == "fieldset"
&& (c.hasClass("radio") || c.hasClass("checkboxes"))) {
for ( var a = 0;; a++) {
if (document.id(c.get("id") + a)) {
if (document.id(c.get("id") + a).checked) {
break
}
} else {
this.handleResponse(false, c);
return false
}
}
} else {
if (!(c.get("value"))) {
this.handleResponse(false, c);
return false
}
}
}
var b = (c.className && c.className
.search(/validate-([a-zA-Z0-9\_\-]+)/) != -1) ? c.className
.match(/validate-([a-zA-Z0-9\_\-]+)/)[1]
: "";
if (b == "") {
this.handleResponse(true, c);
return true
}
if ((b) && (b != "none") && (this.handlers[b])
&& c.get("value")) {
if (this.handlers[b].exec(c.get("value")) != true) {
this.handleResponse(false, c);
return false
}
}
this.handleResponse(true, c);
return true
},
isValid : function(c) {
var b = true;
var d = c.getElements("fieldset").concat($A(c.elements));
for ( var a = 0; a < d.length; a++) {
if (this.validate(d[a]) == false) {
b = false
}
}
new Hash(this.custom).each(function(e) {
if (e.exec() != true) {
b = false
}
});
return b
},
handleResponse : function(b, a) {
if (!(a.labelref)) {
var c = $$("label");
c.each(function(d) {
if (d.get("for") == a.get("id")) {
a.labelref = d
}
})
}
if (b == false) {
a.addClass("invalid");
a.set("aria-invalid", "true");
if (a.labelref) {
document.id(a.labelref).addClass("invalid");
document.id(a.labelref).set("aria-invalid", "true");
}
} else {
a.removeClass("invalid");
a.set("aria-invalid", "false");
if (a.labelref) {
document.id(a.labelref).removeClass("invalid");
document.id(a.labelref).set("aria-invalid", "false");
}
}
}
});
document.formvalidator = null;
window.addEvent("domready", function() {
document.formvalidator = new JFormValidator()
});
Where would I edit the code as some of you have answered below?
with jquery js library, scroll to element (id selector or class)
<p class="error">There was a problem with this element.</p>
This gets passed to the ScrollTo plugin in the following way.
$.scrollTo($('p.error:1'));
see source
Using jQuery's .each, loop over the fields. On every iteration the item that is being invesitigated will be under the this variable.
Therefore, this.id gives the id of the element you're looking for. Store these to collect all the incorrect fields, then highlight them or print their names in a message.
Keep in mind, this is the basic idea, I cannot give an actual answer until you show the code that handles the form.
Kind regards,
D.
You can have your isValid routine return the error message instead of returning a boolean.
In isValid, you can build up the error message to include the field names with errors.
Instead of checking "valid == true", you will check "errorMessage.length == 0".
If you want to focus on an error field (you can only focus on one), then do that in the isValid routine as well.
function isValid(f) {
var errorMessage = "";
var errorFields = "";
var isFocused = false;
...
if (field has an error) {
errorFields += " " + field.name;
if (!isFocused) {
field.focus();
isFocused = true;
}
}
...
if (errorFields.length > 0) {
errorMessage = "Errors in fields: " + errorFields;
}
return (errorMessage);
}
then, in your calling routine:
var errorMessage = isValid(f);
if (flag == 0 || errorMessage.length == 0) {
f.check.value='<?php echo JUtility::getToken(); ?>';//send token
}
else {
alert(errorMessage);
return false;
}
return true;

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