Cannot read property `attachEvent` of null - javascript

I have a JavaScript file using speechSynthesis.
I keep having this error:
"Cannot read property 'attachEvent' of null" in line 129:
Here it is:
speech.bind = function(event, element, callback) {
**if (element.attachEvent) {**
element.attachEvent('on'+event, callback )
} else if (window.addEventListener) {
element.addEventListener(event, callback ,false);
};
};
I will put in here the role code in here so anyone can check the entire JavaScript:
var speech_def = speech_def || {
container: "#glb-materia"
,insert_before: true
,ico: "http://edg-1-1242075393.us-east-1.elb.amazonaws.com/speech/listen_icon.jpg"
,bt_txt: "OUÇA A REPORTAGEM"
,bt_stop: "PARAR!"
,source: ".materia-conteudo"
,ignore: [
".foto-legenda"
,".frase-materia"
,"script"
,"style"
,"#speech"
,".sub-header"
,".chamada-materia"
,".data-autor"
,".box-tags"
,".saibamais"
]
};
var speech = speech || {};
//Polyfill remove()
Element.prototype.remove = function() {
this.parentElement.removeChild(this);
};
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
for (var i = 0, len = this.length; i < len; i++) {
if(this[i] && this[i].parentElement) {
this[i].parentElement.removeChild(this[i]);
}
}
};
//Polyfill innerText
if ( (!('innerText' in document.createElement('a'))) && ('getSelection' in window) ) {
HTMLElement.prototype.__defineGetter__("innerText", function() {
var selection = window.getSelection(),
ranges = [],
str;
for (var i = 0; i < selection.rangeCount; i++) {
ranges[i] = selection.getRangeAt(i);
}
selection.removeAllRanges();
selection.selectAllChildren(this);
str = selection.toString();
selection.removeAllRanges();
for (var i = 0; i < ranges.length; i++) {
selection.addRange(ranges[i]);
}
return str;
})
}
speech.iOS = /(iPad|iPhone|iPod)/g.test( navigator.userAgent );
speech.Android = /(Android)/g.test( navigator.userAgent );
speech.include = function() {
var bt = ""
bt += '<div id="speech" '
+'title="'+speech_def.bt_txt+'" '
+'style="'
+'display: none; '
+'margin: 5px; '
+'font-size: 12px; '
+'font-style: italic; '
+'color: #bbbbbb; '
+'cursor: pointer;"'
+'>';
bt += '<img style="width: 25px; height: 25px;" src="'+speech_def.ico+'"> ';
bt += '<i style="vertical-align: top; line-height: 28px;">'+speech_def.bt_txt+'</i>';
bt += '</div>';
var button = document.createElement("SPAN");
button.innerHTML = bt;
var box = document.querySelectorAll(speech_def.container)[0];
if (speech_def.insert_before) {
box.insertBefore(button,box.firstChild);
} else {
box.appendChild(button)
};
};
speech.stop = function() {
window.speechSynthesis.cancel();
}
speech.stop();
speech.content = function() {
var result = "";
var boxes = speech_def.source.split(",");
boxes.reverse();
for (var n = boxes.length - 1; n >= 0; n--) {
var doc = document.querySelector(boxes[n]);
if (doc) {
doc = doc.cloneNode(true);
for (var i = speech_def.ignore.length - 1; i >= 0; i--) {
var els = doc.querySelectorAll(speech_def.ignore[i]);
for (var j = els.length - 1; j >= 0; j--) {
els[j].remove();
};
};
result += "." + doc.innerText;
};
};
return result;
};
speech.start_speech = function() {
var content = speech.content();
// Note: some voices don't support altering params
if (!speech.Android) speech.msg.voice = speech.voices[0];
// msg.voiceURI = 'native';
speech.msg.volume = speech.iOS?1:1; // 0 to 1
speech.msg.rate = speech.iOS?0.6:1; // 0.1 to 10
speech.msg.pitch = speech.iOS?1:1; // 0 to 2
speech.msg.text = content;
speech.msg.lang = 'pt-BR';
speech.msg.onend = function(e) {
// console.log('Finished in ' + event.elapsedTime + ' seconds.');
};
window.speechSynthesis.speak(speech.msg);
};
speech.read = function(){}; //chrome problem
speech.bind = function(event, element, callback) {
if (element.attachEvent) {
element.attachEvent('on'+event, callback )
} else if (window.addEventListener) {
element.addEventListener(event, callback ,false);
};
};
speech.click = function(e){
event.stopPropagation()
if (window.event) window.event.cancelBubble = true;
var control = document.getElementById("speech");
var label;
if (window.speechSynthesis.speaking) {
label = speech_def.bt_txt;
speech.stop();
} else {
label = speech_def.bt_stop;
speech.start_speech();
};
control.querySelector("i").innerHTML = label;
}
speech.bind_button = function() {
var control = document.getElementById("speech");
speech.bind("click",control,speech.click);
};
speech.show_button = function() {
if (!speech.on_page) {
speech.on_page = true;
speech.include();
speech.bind_button();
};
var control = document.getElementById("speech");
control.style.display="inline-block";
};
speech.test_portuguese = function() {
speech.voices = [];
window.speechSynthesis.getVoices().forEach(function(voice) {
if (voice.lang == "pt-BR") {
speech.voices.push(voice);
};
});
if (speech.Android) {
var control = document.getElementById("speech");
var complement = (speech.voices.length > 0)?"*":"";
// control.querySelector("i").innerHTML = "OUÇA A REPORTAGEM"+complement;
return true;
} else {
return (speech.voices.length > 0);
};
};
speech.start = function() {
if ('speechSynthesis' in window) {
speech.msg = new SpeechSynthesisUtterance();
if (speech.test_portuguese()) {
speech.show_button();
} else {
window.speechSynthesis.onvoiceschanged = function() {
if (speech.test_portuguese()) {
speech.show_button();
};
};
};
speech.bind_button();
};
};
speech.start();
speech.bind("load",window,speech.start)
How can i solve this problem?
Thanks so much.

The problem is that element is null at that point.
Probably, because there is no element with id="speech", so control in null in this code:
speech.bind_button = function() {
var control = document.getElementById("speech");
speech.bind("click",control,speech.click);
};

Related

SharePoint 2016 - JSLink - save not working with IE but working with Chrome

I've got a strange behaviour with a JSLINK I'm using on my SP. The save button of the form is not working with IE if I change the value of the field that the JSLINK is transforming but it's ok with Chrome.
The field is type of Multiline plain text. I'm using using to save some JSON.
Here is the code:
(function() {
var loaded = false;
var repeaterFormArr = [
"<input type='text' id='nameInput' placeholder='Nom complet' class='ms-long ms-spellcheck-true intervenantsBox' required>",
"<input type='text' id='addressInput' placeholder='Adresse' class='ms-long ms-spellcheck-true intervenantsBox'>",
"<input type='text' id='phoneInput' placeholder='Telephone' class='ms-long ms-spellcheck-true intervenantsBox'>",
"<input type='text' id='emailInput' placeholder='Email' pattern=\"[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$\" title='xxx#yyy.zzz' class='ms-long ms-spellcheck-true intervenantsBox'>",
"<select name='typeActor' id='typeActor' class='ms-long intervenantsBox'><option value='plaignant'>Plaignant</option><option value='avocat'>Avocat</option><option value='DPO'>DPO</option><option value='demandeur'>Demandeur</option></select>",
];
var ControlRenderModeIntervenant;
var repeaterFormValues = [];
function includeCss() {
if (loaded) return;
loaded = true;
var link = document.createElement('link');
link.href = _spPageContextInfo.siteAbsoluteUrl + '/Style%20Library/CSS/intervenantsEditCustom.css';
link.rel = 'stylesheet';
document.head.appendChild(link);
}
// This function provides the rendering logic
function IntervenantsRepeaterFiledViewTemplate(ctx) {
ControlRenderModeIntervenant = ctx.ControlMode;
if (ctx.CurrentItem[ctx.CurrentFieldSchema.Name] && ctx.CurrentItem[ctx.CurrentFieldSchema.Name] != '[]') {
var fieldValue = ctx.CurrentItem[ctx.CurrentFieldSchema.Name].replace(/"/g, "\"").replace(/(<([^>]+)>)/g, "");
repeaterFormValues = JSON.parse(fieldValue);
}
return GetRenderHtmlRepeaterValuesIntervenants();
}
// This function provides the rendering logic
function IntervenantsRepeaterFiledEditFTemplate(ctx) {
var field = ctx.CurrentFieldSchema,
encodedName = field.Name + '_' + field.Id + '_$NumberField';
ControlRenderModeIntervenant = ctx.ControlMode;
var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);
if (formCtx.fieldValue) {
repeaterFormValues = JSON.parse(formCtx.fieldValue);
}
// Register a callback just before submit.
ctx.FormContext.registerGetValueCallback(field.Name, function() {
return JSON.stringify(repeaterFormValues);
});
ctx.FormContext.registerInitCallback(field.Name, function() {
document.getElementById('innerFormIntervenants').addEventListener('submit', function(evt) {
evt.preventDefault();
AddIntervenant();
return false;
});
var deleteLinks = document.getElementsByClassName('delete-link');
if (deleteLinks.length > 0) {
for (var i = 0; i < deleteLinks.length; i++) {
deleteLinks[i].addEventListener("onclick", function(evt) {
evt.preventDefault();
DeleteItem(deleteLinks[i].getAttribute('data-myAttri'));
return false;
});
}
}
});
// formCtx.registerGetValueCallback(formCtx.fieldName, function() {
// return JSON.stringify(repeaterFormValues);
// });
var HTMLViewTemplate = "<form id='innerFormIntervenants'>{Controls}<div><input type='submit' value='Add' style='margin-left:0'></div><br/><div id='divRepeaterValues'>{RepeaterValues}</div><br/></form>";
var returnHTML = "";
for (index = 0; index < repeaterFormArr.length; ++index) {
returnHTML += repeaterFormArr[index];
}
returnHTML = HTMLViewTemplate.replace(/{Controls}/g, returnHTML);
returnHTML = returnHTML.replace(/{RepeaterValues}/g, GetRenderHtmlRepeaterValuesIntervenants());
return returnHTML;
}
function GetRenderHtmlRepeaterValuesIntervenants() {
var index;
var innerindex;
var HTMLItemsTemplate = "<table width='600px' style='border:1px solid #ababab;'>{Items}</table>";
var HTMLItemTemplate = "<tr>{Item}</tr>";
var HTMLValueTemplate = "<td>{Value}</td>";
if (ControlRenderModeIntervenant == SPClientTemplates.ClientControlMode.EditForm || ControlRenderModeIntervenant == SPClientTemplates.ClientControlMode.NewForm) {
HTMLItemTemplate = "<tr>{Item}<td><a class='delete-link' data-myAttri='{Index}' href='#'><img src='/SiteAssets/IMG/user-delete.png' class='deleteUserButton'/></a></td></tr>";
}
var returnHTML = "";
var tempValueHtml;
for (index = 0; index < repeaterFormValues.length; ++index) {
tempValueHtml = "";
for (innerindex = 0; innerindex < repeaterFormValues[index]["Intervenant"].length; ++innerindex) {
tempValueHtml += HTMLValueTemplate.replace(/{Value}/g, repeaterFormValues[index]["Intervenant"][innerindex]["Value"]);
}
returnHTML += HTMLItemTemplate.replace(/{Item}/g, tempValueHtml);
returnHTML = returnHTML.replace(/{Index}/g, index);
}
if (repeaterFormValues.length) {
returnHTML = HTMLItemsTemplate.replace(/{Items}/g, returnHTML);
}
return returnHTML;
}
function AddIntervenant() {
var innerFormIntervenants = document.getElementById('innerFormIntervenants');
if (innerFormIntervenants.checkValidity()) {
var index;
var tempRepeaterValue = [];
for (index = 0; index < innerFormIntervenants.length; index++) {
if (innerFormIntervenants[index].type != "submit" && innerFormIntervenants[index].type != "button" && innerFormIntervenants[index].type != "reset") {
tempRepeaterValue.push({
"ID": innerFormIntervenants[index].id,
"Value": innerFormIntervenants[index].value
});
innerFormIntervenants[index].value = "";
}
}
repeaterFormValues.push({ "Intervenant": tempRepeaterValue });
document.getElementById("divRepeaterValues").innerHTML = GetRenderHtmlRepeaterValuesIntervenants();
}
}
function DeleteItem(index) {
repeaterFormValues.splice(index, 1);
document.getElementById("divRepeaterValues").innerHTML = GetRenderHtmlRepeaterValuesIntervenants();
}
var overrideCtx = {};
overrideCtx.Templates = {};
overrideCtx.Templates.OnPreRender = includeCss;
overrideCtx.Templates.Fields = {
myCustomField: {
View: IntervenantsRepeaterFiledViewTemplate,
DisplayForm: IntervenantsRepeaterFiledViewTemplate,
NewForm: IntervenantsRepeaterFiledEditFTemplate,
EditForm: IntervenantsRepeaterFiledEditFTemplate
}
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCtx);
})();
In Debug, I can see that the callback function is called. Then it goes inside the JS of SharePoint for saving the item. But the save button is just going to grey and then nothing append.

ASP.NET referencing a javascript function

I have an ASP.NET page, written in VB.NET, that I'm trying to use javascript on. The script takes the value from one listbox and inserts it into another list box. I'm using a master page, which I'm pretty sure is the issue.
Here's the javascript:
function OT_transferLeft() { moveSelectedOptions(this.right, this.left, this.autoSort, this.staticOptionRegex); this.update(); }
function OT_transferRight() { moveSelectedOptions(this.left, this.right, this.autoSort, this.staticOptionRegex); this.update(); }
function OT_transferAllLeft() { moveAllOptions(this.right, this.left, this.autoSort, this.staticOptionRegex); this.update(); }
function OT_transferAllRight() { moveAllOptions(this.left, this.right, this.autoSort, this.staticOptionRegex); this.update(); }
function OT_saveRemovedLeftOptions(f) { this.removedLeftField = f; }
function OT_saveRemovedRightOptions(f) { this.removedRightField = f; }
function OT_saveAddedLeftOptions(f) { this.addedLeftField = f; }
function OT_saveAddedRightOptions(f) { this.addedRightField = f; }
function OT_saveNewLeftOptions(f) { this.newLeftField = f; }
function OT_saveNewRightOptions(f) { this.newRightField = f; }
function OT_update() {
var removedLeft = new Object();
var removedRight = new Object();
var addedLeft = new Object();
var addedRight = new Object();
var newLeft = new Object();
var newRight = new Object();
for (var i = 0; i < this.left.options.length; i++) {
var o = this.left.options[i];
newLeft[o.value] = 1;
if (typeof (this.originalLeftValues[o.value]) == "undefined") {
addedLeft[o.value] = 1;
removedRight[o.value] = 1;
}
}
for (var i = 0; i < this.right.options.length; i++) {
var o = this.right.options[i];
newRight[o.value] = 1;
if (typeof (this.originalRightValues[o.value]) == "undefined") {
addedRight[o.value] = 1;
removedLeft[o.value] = 1;
}
}
if (this.removedLeftField != null) { this.removedLeftField.value = OT_join(removedLeft, this.delimiter); }
if (this.removedRightField != null) { this.removedRightField.value = OT_join(removedRight, this.delimiter); }
if (this.addedLeftField != null) { this.addedLeftField.value = OT_join(addedLeft, this.delimiter); }
if (this.addedRightField != null) { this.addedRightField.value = OT_join(addedRight, this.delimiter); }
if (this.newLeftField != null) { this.newLeftField.value = OT_join(newLeft, this.delimiter); }
if (this.newRightField != null) { this.newRightField.value = OT_join(newRight, this.delimiter); }
}
function OT_join(o, delimiter) {
var val; var str = "";
for (val in o) {
if (str.length > 0) { str = str + delimiter; }
str = str + val;
}
return str;
}
function OT_setDelimiter(val) { this.delimiter = val; }
function OT_setAutoSort(val) { this.autoSort = val; }
function OT_setStaticOptionRegex(val) { this.staticOptionRegex = val; }
function OT_init(theform) {
this.form = theform;
if (!theform[this.left]) { alert("OptionTransfer init(): Left select list does not exist in form!"); return false; }
if (!theform[this.right]) { alert("OptionTransfer init(): Right select list does not exist in form!"); return false; }
this.left = theform[this.left];
this.right = theform[this.right];
for (var i = 0; i < this.left.options.length; i++) {
this.originalLeftValues[this.left.options[i].value] = 1;
}
for (var i = 0; i < this.right.options.length; i++) {
this.originalRightValues[this.right.options[i].value] = 1;
}
if (this.removedLeftField != null) { this.removedLeftField = theform[this.removedLeftField]; }
if (this.removedRightField != null) { this.removedRightField = theform[this.removedRightField]; }
if (this.addedLeftField != null) { this.addedLeftField = theform[this.addedLeftField]; }
if (this.addedRightField != null) { this.addedRightField = theform[this.addedRightField]; }
if (this.newLeftField != null) { this.newLeftField = theform[this.newLeftField]; }
if (this.newRightField != null) { this.newRightField = theform[this.newRightField]; }
this.update();
}
// -------------------------------------------------------------------
// OptionTransfer()
// This is the object interface.
// -------------------------------------------------------------------
function OptionTransfer(l, r) {
this.form = null;
this.left = l;
this.right = r;
this.autoSort = true;
this.delimiter = ",";
this.staticOptionRegex = "";
this.originalLeftValues = new Object();
this.originalRightValues = new Object();
this.removedLeftField = null;
this.removedRightField = null;
this.addedLeftField = null;
this.addedRightField = null;
this.newLeftField = null;
this.newRightField = null;
this.transferLeft = OT_transferLeft;
this.transferRight = OT_transferRight;
this.transferAllLeft = OT_transferAllLeft;
this.transferAllRight = OT_transferAllRight;
this.saveRemovedLeftOptions = OT_saveRemovedLeftOptions;
this.saveRemovedRightOptions = OT_saveRemovedRightOptions;
this.saveAddedLeftOptions = OT_saveAddedLeftOptions;
this.saveAddedRightOptions = OT_saveAddedRightOptions;
this.saveNewLeftOptions = OT_saveNewLeftOptions;
this.saveNewRightOptions = OT_saveNewRightOptions;
this.setDelimiter = OT_setDelimiter;
this.setAutoSort = OT_setAutoSort;
this.setStaticOptionRegex = OT_setStaticOptionRegex;
this.init = OT_init;
this.update = OT_update;
}
var lb1 = document.getElementById("<%=lbSiteType.ClientID%>");
var lb2 = document.getElementById("<%=lbSelectedSiteType.ClientID%>");
var opt = new OptionTransfer(lb1, lb2);
alert(opt);
opt.setAutoSort(true);
opt.setDelimiter(",");
opt.setStaticOptionRegex("^(Bill|Bob|Matt)$");
opt.saveRemovedLeftOptions("removedLeft");
opt.saveRemovedRightOptions("removedRight");
opt.saveAddedLeftOptions("addedLeft");
opt.saveAddedRightOptions("addedRight");
opt.saveNewLeftOptions("newLeft");
opt.saveNewRightOptions("newRight");
and here's the code from the control:
<asp:Button ID="btnMoveAll" Text=" >> " CssClass="button7" CausesValidation="false"
ONCLICK="opt.transferRight()"
runat="server" /><br />
In short, it doesn't work. I keep getting an 'opt' is not a member of the page. Can someone explain how I can properly call this code?
To invoke client Methods(javascript) use OnClientClick
<asp:Button ID="btnMoveAll" Text="" CssClass="button7" CausesValidation="false"
OnClientClick="opt.transferRight()"
runat="server" />

Autocompleter Javascript-for Wordpress site

I need help ...
I have an autocomplete plugin that installed on my site and it works perfect...My need for autocomplete was bacause i have posts to which i want to redirect when clicked on autocompleted list item .
for example : i have one search form and when typed and autococompleted some post name then it redirects me to post like example.com/post/namePost .Now i cloned that website and my new website is example1.com ... now autocompleter in new site redirects me on autocomplete to example1.com/post/namePost .
My problem is , that i need that autocompleter on new site,redirects me to old website link - in this case www.example.com/post/postName. Note that after www.example.com both url data is same
Here is my autocomplete.js code :
/*
original jQuery plugin by http://www.pengoworks.com/workshop/jquery/autocomplete.htm
just replaced $ with jQuery in order to be complaint with other JavaScript libraries.
*/
jQuery.autocomplete = function(input, options) {
// Create a link to self
var me = this;
var link="http://telecoms-group.com/";
// Create jQuery object for input element
var $input = jQuery(input).attr("autocomplete", "off");
// Apply inputClass if necessary
if (options.inputClass) $input.addClass(options.inputClass);
// Create results
var results = document.createElement("div");
// Create jQuery object for results
var $results = jQuery(results);
$results.hide().addClass(options.resultsClass).css("position", "absolute");
if( options.width > 0 ) $results.css("width", options.width);
// Add to body element
jQuery("body").append(results);
input.autocompleter = me;
var timeout = null;
var prev = "";
var active = -1;
var cache = {};
var keyb = false;
var hasFocus = false;
var lastKeyPressCode = null;
// flush cache
function flushCache(){
cache = {};
cache.data = {};
cache.length = 0;
};
// flush cache
flushCache();
// if there is a data array supplied
if( options.data != null ){
var sFirstChar = "", stMatchSets = {}, row = [];
// no url was specified, we need to adjust the cache length to make sure it fits the local data store
if( typeof options.url != "string" ) options.cacheLength = 1;
// loop through the array and create a lookup structure
for( var i=0; i < options.data.length; i++ ){
// if row is a string, make an array otherwise just reference the array
row = ((typeof options.data[i] == "string") ? [options.data[i]] : options.data[i]);
// if the length is zero, don't add to list
if( row[0].length > 0 ){
// get the first character
sFirstChar = row[0].substring(0, 1).toLowerCase();
// if no lookup array for this character exists, look it up now
if( !stMatchSets[sFirstChar] ) stMatchSets[sFirstChar] = [];
// if the match is a string
stMatchSets[sFirstChar].push(row);
}
}
// add the data items to the cache
for( var k in stMatchSets ){
// increase the cache size
options.cacheLength++;
// add to the cache
addToCache(k, stMatchSets[k]);
}
}
$input
.keydown(function(e) {
// track last key pressed
lastKeyPressCode = e.keyCode;
switch(e.keyCode) {
case 38: // up
e.preventDefault();
moveSelect(-1);
break;
case 40: // down
e.preventDefault();
moveSelect(1);
break;
case 9: // tab
case 13: // return
if( selectCurrent() ){
// make sure to blur off the current field
$input.get(0).blur();
e.preventDefault();
}
break;
default:
active = -1;
if (timeout) clearTimeout(timeout);
timeout = setTimeout(function(){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 = true;
})
.blur(function() {
// track whether the field has focus
hasFocus = false;
hideResults();
});
hideResultsNow();
function onChange() {
// ignore if the following keys are pressed: [del] [shift] [capslock]
if( lastKeyPressCode == 46 || (lastKeyPressCode > 8 && lastKeyPressCode < 32) ) return $results.hide();
var v = $input.val();
if (v == prev) return;
prev = v;
if (v.length >= options.minChars) {
$input.addClass(options.loadingClass);
requestData(v);
} else {
$input.removeClass(options.loadingClass);
$results.hide();
}
};
function moveSelect(step) {
var lis = jQuery("li", results);
if (!lis) return;
active += step;
if (active < 0) {
active = 0;
} else if (active >= lis.size()) {
active = lis.size() - 1;
}
lis.removeClass("ac_over");
jQuery(lis[active]).addClass("ac_over");
// Weird behaviour in IE
// if (lis[active] && lis[active].scrollIntoView) {
// lis[active].scrollIntoView(false);
// }
};
function selectCurrent() {
var li = jQuery("li.ac_over", results)[0];
if (!li) {
var $li = jQuery("li", results);
if (options.selectOnly) {
if ($li.length == 1) li = $li[0];
} else if (options.selectFirst) {
li = $li[0];
}
}
if (li) {
selectItem(li);
return true;
} else {
return false;
}
};
function selectItem(li) {
if (!li) {
li = document.createElement("li");
li.extra = [];
li.selectValue = "";
}
var v = jQuery.trim(li.selectValue ? li.selectValue : li.innerHTML);
input.lastSelected = v;
prev = v;
$results.html("");
$input.val(v);
hideResultsNow();
if (options.onItemSelect) setTimeout(function() { options.onItemSelect(li) }, 1);
};
// selects a portion of the input string
function createSelection(start, end){
// get a reference to the input element
var field = $input.get(0);
if( field.createTextRange ){
var selRange = field.createTextRange();
selRange.collapse(true);
selRange.moveStart("character", start);
selRange.moveEnd("character", end);
selRange.select();
} else if( field.setSelectionRange ){
field.setSelectionRange(start, end);
} else {
if( field.selectionStart ){
field.selectionStart = start;
field.selectionEnd = end;
}
}
field.focus();
};
// fills in the input box w/the first match (assumed to be the best match)
function autoFill(sValue){
// if the last user key pressed was backspace, don't autofill
if( lastKeyPressCode != 8 ){
// fill in the value (keep the case the user has typed)
$input.val($input.val() + sValue.substring(prev.length));
// select the portion of the value not typed by the user (so the next character will erase)
createSelection(prev.length, sValue.length);
}
};
function showResults() {
// get the position of the input field right now (in case the DOM is shifted)
var pos = findPos(input);
// either use the specified width, or autocalculate based on form element
var iWidth = (options.width > 0) ? options.width : $input.width();
// reposition
$results.css({
width: parseInt($input.width()+15)+ "px",
top: (pos.y + input.offsetHeight+ input.offsetHeight) + "px",
left: pos.x + "px"
}).show();
};
function hideResults() {
if (timeout) clearTimeout(timeout);
timeout = setTimeout(hideResultsNow, 200);
};
function hideResultsNow() {
if (timeout) clearTimeout(timeout);
$input.removeClass(options.loadingClass);
if ($results.is(":visible")) {
$results.hide();
}
if (options.mustMatch) {
var v = $input.val();
if (v != input.lastSelected) {
selectItem(null);
}
}
};
function receiveData(q, data) {
if (data) {
$input.removeClass(options.loadingClass);
results.innerHTML = "";
// if the field no longer has focus or if there are no matches, do not display the drop down
if( !hasFocus || data.length == 0 ) return hideResultsNow();
if (jQuery.browser.msie) {
// we put a styled iframe behind the calendar so HTML SELECT elements don't show through
$results.append(document.createElement('iframe'));
}
results.appendChild(dataToDom(data));
// autofill in the complete box w/the first match as long as the user hasn't entered in more data
if( options.autoFill && ($input.val().toLowerCase() == q.toLowerCase()) ) autoFill(data[0][0]);
showResults();
} else {
hideResultsNow();
}
};
function parseData(data) {
if (!data) return null;
var parsed = [];
var rows = data.split(options.lineSeparator);
for (var i=0; i < rows.length; i++) {
var row = jQuery.trim(rows[i]);
if (row) {
parsed[parsed.length] = row.split(options.cellSeparator);
}
}
return parsed;
};
function dataToDom(data) {
var ul = document.createElement("ul");
var num = data.length;
// limited results to a max number
if( (options.maxItemsToShow > 0) && (options.maxItemsToShow < num) ) num = options.maxItemsToShow;
for (var i=0; i < num; i++) {
var row = data[i];
if (!row) continue;
var li = document.createElement("li");
if (options.formatItem) {
li.innerHTML = options.formatItem(row, i, num);
li.selectValue = row[0];
} else {
li.innerHTML = row[0];
li.selectValue = row[0];
}
var extra = null;
if (row.length > 1) {
extra = [];
for (var j=1; j < row.length; j++) {
extra[extra.length] = row[j];
}
}
li.extra = extra;
ul.appendChild(li);
jQuery(li).hover(
function() { jQuery("li", ul).removeClass("ac_over"); jQuery(this).addClass("ac_over"); active = jQuery("li", ul).indexOf(jQuery(this).get(0)); },
function() { jQuery(this).removeClass("ac_over"); }
).click(function(e) { e.preventDefault(); e.stopPropagation(); selectItem(this) });
}
return ul;
};
function requestData(q) {
if (!options.matchCase) q = q.toLowerCase();
var data = options.cacheLength ? loadFromCache(q) : null;
// recieve the cached data
if (data) {
receiveData(q, data);
// if an AJAX url has been supplied, try loading the data now
} else if( (typeof options.url == "string") && (options.url.length > 0) ){
jQuery.get(makeUrl(q), function(data) {
data = parseData(data);
addToCache(q, data);
receiveData(q, data);
});
// if there's been no data found, remove the loading class
} else {
$input.removeClass(options.loadingClass);
}
};
function makeUrl(q) {
var url = options.url + "?q=" + encodeURI(q);
for (var i in options.extraParams) {
url += "&" + i + "=" + encodeURI(options.extraParams[i]);
}
return url;
};
function loadFromCache(q) {
if (!q) return null;
if (cache.data[q]) return cache.data[q];
if (options.matchSubset) {
for (var i = q.length - 1; i >= options.minChars; i--) {
var qs = q.substr(0, i);
var c = cache.data[qs];
if (c) {
var csub = [];
for (var j = 0; j < c.length; j++) {
var x = c[j];
var x0 = x[0];
if (matchSubset(x0, q)) {
csub[csub.length] = x;
}
}
return csub;
}
}
}
return null;
};
function matchSubset(s, sub) {
if (!options.matchCase) s = s.toLowerCase();
var i = s.indexOf(sub);
if (i == -1) return false;
return i == 0 || options.matchContains;
};
this.flushCache = function() {
flushCache();
};
this.setExtraParams = function(p) {
options.extraParams = p;
};
this.findValue = function(){
var q = $input.val();
if (!options.matchCase) q = q.toLowerCase();
var data = options.cacheLength ? loadFromCache(q) : null;
if (data) {
findValueCallback(q, data);
} else if( (typeof options.url == "string") && (options.url.length > 0) ){
jQuery.get(makeUrl(q), function(data) {
data = parseData(data)
addToCache(q, data);
findValueCallback(q, data);
});
} else {
// no matches
findValueCallback(q, null);
}
}
function findValueCallback(q, data){
if (data) $input.removeClass(options.loadingClass);
var num = (data) ? data.length : 0;
var li = null;
for (var i=0; i < num; i++) {
var row = data[i];
if( row[0].toLowerCase() == q.toLowerCase() ){
li = document.createElement("li");
if (options.formatItem) {
li.innerHTML = options.formatItem(row, i, num);
li.selectValue = row[0];
} else {
li.innerHTML = row[0];
li.selectValue = row[0];
}
var extra = null;
if( row.length > 1 ){
extra = [];
for (var j=1; j < row.length; j++) {
extra[extra.length] = row[j];
}
}
li.extra = extra;
}
}
if( options.onFindValue ) setTimeout(function() { options.onFindValue(li) }, 1);
}
function addToCache(q, data) {
if (!data || !q || !options.cacheLength) return;
if (!cache.length || cache.length > options.cacheLength) {
flushCache();
cache.length++;
} else if (!cache[q]) {
cache.length++;
}
cache.data[q] = data;
};
function findPos(obj) {
var curleft = obj.offsetLeft || 0;
var curtop = obj.offsetTop || 0;
while (obj = obj.offsetParent) {
curleft += obj.offsetLeft
curtop += obj.offsetTop
}
return {x:curleft,y:curtop};
}
}
jQuery.fn.autocomplete = function(url, options, data) {
// Make sure options exists
options = options || {};
// Set url as option
options.url = url;
// set some bulk local data
options.data = ((typeof data == "object") && (data.constructor == Array)) ? data : null;
// Set default values for required options
options.inputClass = options.inputClass || "ac_input";
options.resultsClass = options.resultsClass || "ac_results";
options.lineSeparator = options.lineSeparator || "\n";
options.cellSeparator = options.cellSeparator || "|";
options.minChars = options.minChars || 1;
options.delay = options.delay || 400;
options.matchCase = options.matchCase || 0;
options.matchSubset = options.matchSubset || 1;
options.matchContains = options.matchContains || 0;
options.cacheLength = options.cacheLength || 1;
options.mustMatch = options.mustMatch || 0;
options.extraParams = options.extraParams || {};
options.loadingClass = options.loadingClass || "ac_loading";
options.selectFirst = options.selectFirst || false;
options.selectOnly = options.selectOnly || false;
options.maxItemsToShow = options.maxItemsToShow || -1;
options.autoFill = options.autoFill || false;
options.width = parseInt(options.width, 10) || 0;
this.each(function() {
var input = this;
new jQuery.autocomplete(input, options);
});
// Don't break the chain
return this;
}
jQuery.fn.autocompleteArray = function(data, options) {
return this.autocomplete(null, options, data);
}
jQuery.fn.indexOf = function(e){
for( var i=0; i<this.length; i++ ){
if( this[i] == e ) return i;
}
return -1;
};
Can somebody tell me where is that part with url redirection , and how can i change that

XML Javascript undefined error in ie9

I have a 'jargon buster' on my site that uses an xml file to load an A-Z of words which when clicked display a brief short explanation of each word. This works fine in all browsers bar the latest ie's which i get an 'undefined' error with. The jscript im using is below
Jargon = {
xmlfile: 'http://www.mysite.com/jargon.xml',
xml: null,
wordHolder: 'words',
defHolder: 'definition',
idprefix: 'jargon_',
selected: null,
init: function () {
var con = Jargon.xhcon();
Jargon.wordHolder = $(Jargon.wordHolder);
Jargon.defHolder = $(Jargon.defHolder);
if (!con || !Jargon.wordHolder || !Jargon.defHolder) {
return;
}
function conComplete(oXML) {
Jargon.xml = oXML.responseXML;
//Jargon.showWords('a');
}
con.connect(Jargon.xmlfile, 'GET', Math.random(), conComplete);
},
showWords: function (c) {
if (Jargon.selected) {
Jargon.selected.className = '';
}
var words = Jargon.getWords(c);
while (Jargon.wordHolder.childNodes.length > 0) {
Jargon.wordHolder.removeChild(Jargon.wordHolder.childNodes[0]);
}
while (Jargon.defHolder.childNodes.length > 0) {
Jargon.defHolder.removeChild(Jargon.defHolder.childNodes[0]);
}
for (var i = 0; i < words.length; i++) {
var o = document.createElement('a');
o.href = 'javascript:Jargon.showDef(\'' + words[i].id + '\');';
o.id = Jargon.idprefix + words[i].id;
//o.onclick = Jargon.showDef;
o.appendChild($t(words[i].name));
Jargon.wordHolder.appendChild(o);
Jargon.wordHolder.appendChild(document.createElement('br'));
}
if (!words.length) {
var o = document.createElement('p');
var s = 'There are no words for the letter ' + c.toUpperCase();
Jargon.wordHolder.appendChild(o.appendChild($t(s)));
}
},
showDef: function (id) {
var o = $(Jargon.idprefix + id);
if (Jargon.selected) {
Jargon.selected.className = '';
}
if (o) {
o.className = 'selected';
Jargon.selected = o;
}
var defobjs = Jargon.getDef(id);
while (Jargon.defHolder.childNodes.length > 0) {
Jargon.defHolder.removeChild(Jargon.defHolder.childNodes[0]);
}
var heading = document.createElement('span');
heading.className = "jargtitle";
heading.appendChild(document.createTextNode(defobjs[1][0].textContent));
Jargon.defHolder.appendChild(heading);
var definition = document.createElement('span');
definition.className = "jargdefinition";
definition.appendChild(document.createTextNode(defobjs[0][0].textContent));
Jargon.defHolder.appendChild(definition);
},
getWords: function(c) {
var x = Jargon.xml;
var letters = x.getElementsByTagName('letter');
var oLetter = null;
for (var i = 0; i < letters.length; i++) {
if (letters[i].getAttribute('id') == c) {
oLetter = letters[i];
break;
}
}
if (!oLetter) {
return [];
}
var words = [];
for (i = 0; i < oLetter.childNodes.length; i++) {
var oJargon = oLetter.childNodes[i];
if (oJargon.nodeName == 'jargon') {
var s = Jargon.getName(oJargon);
words[words.length] = {
id: oLetter.childNodes[i].getAttribute('id'),
name: s
};
}
}
return words;
},
getDef: function (id) {
var x = Jargon.xml;
var j = null;
var temp = new Array(2);
var jargons = x.getElementsByTagName('jargon');
for (var i = 0; i < jargons.length; i++) {
if (jargons[i].getAttribute('id') == id) {
j = jargons[i];
break;
}
}
if (!j) {
return [];
}
//return [];
for (i = 0; i < j.childNodes.length; i++) {
if (j.childNodes[i].nodeName == 'name') {
temp[1] = j.childNodes[i].childNodes;
}
}
for (i = 0; i < j.childNodes.length; i++) {
if (j.childNodes[i].nodeName == 'desc') {
temp[0] = j.childNodes[i].childNodes;
}
}
//return [];
return temp;
},
cloneNode: function (oldNode, deep) {
deep = (deep) ? true : false;
// a replacement to the normal dom clone node
// this will copy xml nodes to html nodes
// which can then be inserted into the document
// scope in all browsers
// See for for the bug http://www.quirksmode.org/blog/archives/2005/12/xmlhttp_notes_c.html
var newNode = null;
if (oldNode.nodeType == '3') {
// textnode
newNode = $t(oldNode.nodeValue);
}
else if (oldNode.nodeType == '1') {
// element node
newNode = document.createElement(oldNode.nodeName);
if (deep) {
for (var i = 0; i < oldNode.childNodes.length; i++) {
newNode.appendChild(Jargon.cloneNode(oldNode.childNodes[i], true));
}
}
}
return newNode;
},
getName: function (oJargon) {
for (var i = 0; i < oJargon.childNodes.length; i++) {
if (oJargon.childNodes[i].nodeName == 'name') {
var oName = oJargon.childNodes[i];
var s = '';
for (var j = 0; j < oName.childNodes.length; j++) {
if (oName.childNodes[j].nodeType == 3) {
// text node
s += oName.childNodes[j].nodeValue;
}
}
return s;
}
}
return '';
},
xhcon: function () {
var xmlhttp, bComplete = false;
try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) { try { xmlhttp = new XMLHttpRequest(); }
catch (e) { xmlhttp = false; }}}
if (!xmlhttp) {
return null;
}
this.connect = function(sURL, sMethod, sVars, fnDone) {
if (!xmlhttp) {
return false;
}
bComplete = false;
sMethod = sMethod.toUpperCase();
try {
if (sMethod == "GET") {
xmlhttp.open(sMethod, sURL+"?"+sVars, true);
sVars = "";
}
else {
xmlhttp.open(sMethod, sURL, true);
xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && !bComplete) {
bComplete = true;
fnDone(xmlhttp);
}
};
xmlhttp.send(sVars);
}
catch(z) { return false; }
return true;
};
return this;
}
}
In terms of how im calling the jscript im using <li>a</li>
which loads a list of all items that begin with f then when i click one of items from that list say "Fiduciary" it triggers javascript:Jargon.showDef('f1'); which in turns loads the and into a definition div
however in ie9 it displays "undefined" . It works in all other browers
Example of the XML below:
<letter id="f"> -<jargon id="f1"> <name>Fiduciary</name> <desc>in a position of trust. This includes people such as trustees looking after trust assets for the beneficiaries and company directors running a company for the shareholders' benefit.</desc> </jargon> -<jargon id="f2"> <name>Forfeiture</name> <desc>the loss of possession of a property because the tenancy conditions have not been met by the tenant.</desc> </jargon> -<jargon id="f3"> <name>Freehold</name> <desc>describing land that only the owner has any rights over.</desc> </jargon> -<jargon id="f4"> <name>Free of encumbrances</name> <desc>no one else having any rights over something. When property is owned by someone and nobody else has any rights over it, it is owned free of encumbrances.</desc> </jargon> </letter>

Firefox Addon Development : Detecting non-compatible addons?

Few addons are not compatible with mine, so how to detect their presence and inform the user.
Thanks
OK got it here is how this is done :
function isExtEnabled(){
if(!Application.extensions.has('EXTENSION_ID_HERE')) {
return false;
}
return true;
}
Here is an example from the evil noscript-1.9.2.xpi which modified adblock plugin settings
function MRD(ns) {
this.enabled = ns.getPref("mrd", true);
if (!this.enabled) return;
var c = CC[this.id];
if (c) {
this.ns = ns;
this.c = c.createInstance().wrappedJSObject;
this._w._mrd = this;
var eh = this.c["elemhide"];
eh.watch("url", this._w);
eh.apply();
ns.mrd = this;
ns.initContentPolicy();
} else this.enabled = false;
}
MRD.prototype = {
id: "#mozilla.org/adblockplus;1",
_nobind: "{-moz-binding: none !important}",
_ms: null,
_w: function(p, o, n) {
if (!n) return n;
var mrd = arguments.callee._mrd;
var u = decodeURIComponent(n.spec);
var mm = u.match(/#-moz-document\s+domain[^\)]*?(?:(?:noscript|flashgot|hackademix)\.net|informaction\.com|googlesyndication\.com)[^\}]*\}/g);
if (mm) {
var ns = mrd.ns;
mrd._ms = mm.join('').replace(/(\{[^\{\}]*)\{[^\}]*/g, '$1' + mrd._nobind);
}
/*
var uu = n.spec.split(',');
uu[1] = encodeURIComponent(decodeURIComponent(uu[1]).replace(/#-moz-document\s+domain[^\)]*?(?:(?:noscript|flashgot|hackademix)\.net|informaction\.com|googlesyndication\.com)[^\}]*\}/g, ''));
n.spec = uu.join(',');
*/
mrd.ns.delayExec(function() { mrd.apply(); }, 0);
return n;
},
_dd: function(a, s) {
return "#-moz-document domain(" + a.join("),domain(") + "){" + s + "} ";
},
get _def() {
delete this.__proto__._def;
return this.__proto__._def = this.ns.prefService.getDefaultBranch(this.ns.prefs.root).getCharPref("default");
},
get _wl() {
delete this.__proto__._wl;
return this.__proto__._wl = this._def.match(/\w+[^r].\.n\w+|in\w+on\.c\w+/g).concat(this.ns.getPref("xblHack", "").split(/\s+/));
},
get _wlrx() {
delete this.__proto__._wlrx;
return this.__proto__._wlrx = new RegExp("^(?:[\\w\\-\\.]*\\.)?(?:" + this._wl.join("|").replace(/\./g, "\\.").concat(")$"));
},
get _es() {
delete this.__proto__._es;
try {
var ss = [], lastS = '';
for(var j = 0; j < 5; j++) {
ss.push(lastS += " #k" + j);
}
es = this._dd(this._wl, ss.join(' *,') + ' *' + this._nobind) +
this._dd(this._def.match(/\w+[^r].\.n\w+|\w+on\.c\w+/g), "#a\u0064s, #\u0061ds .ad" + this._nobind);
} catch (e) {
if (this.ns.consoleDump) this.ns.dump("MRD ES Error: " + e);
}
return this.__proto__._es = es;
},
apply: function() {
var ns = this.ns;
for each(var s in [this._es, this._ms]){
if (s) {
ns.updateStyleSheet(s, false);
ns.updateStyleSheet(s, true);
}
}
},
attach: function() {
if (!this.enabled) return false;
try {
var p = this.c.policy;
var ns = this.ns;
var wlrx = this._wlrx;
if (!wlrx) return false;
ns._mrd_shouldLoad = ns.shouldLoad;
ns.shouldLoad = function(ct, cl, ro, ctx, mm, internal) {
if (!internal) try {
var w = ctx && (ctx.defaultView || ctx.ownerDocument && ctx.ownerDocument.defaultView || ctx);
if (w) {
l = w.top.location;
if (!(/^https?/.test(l.protocol) && wlrx.test(l.hostname))) {
var res = p.shouldLoad(ct, cl, ro, ctx, mm, internal);
if (res != CP_OK) return res;
}
}
} catch(e) {
if (ns.consoleDump) ns.dump(e);
}
return ns._mrd_shouldLoad(ct, cl, ro, ctx, mm, internal);
};
} catch(e) {
if (this.ns.consoleDump) this.ns.dump("MRD Attach Error: " + e);
return false;
}
return true;
}
}

Categories

Resources