… is not a function in javascript {custom code} - javascript

please, could somebody tell me, what he heck I am doing wrong in my syntax?
The problem starts in the statement this.form.onsubmit, where I get this.initData is not a function.
Thanks.
var Contact_Form = function(element){
this.form = element;
this.errors = new Array();
this.invalid = new Array();
this.inSent = false;
this.name = new String();
this.email = new String();
this.message = new String();
this.initData = function()
{
this.name = this.getElementValue('contact-name');
this.email = this.getElementValue('contact-email');
this.message = this.getElementValue('contact-message');
}
this.form.onsubmit = function(event)
{
event.preventDefault();
this.initData();
if(this.verifyData())
this.send();
}
this.verifyData = function()
{
if(!this.isNameLength())
this.setError('name', 'Zadejte, prosím, jméno dlouhé maximálně 30 znaků.');
if(this.isProperEmail())
{
if(!this.isEmailLength())
this.setError('email', 'Váš e-mail smí obsahovat maximálně 50 znaků.');
}
else
this.setError('email', 'Zadejte, prosím, email v korektním formátu.');
if(!this.isMessageLength())
this.setError('name', 'Zadejte, prosím, zprávu v rozsahu 1-999 znaků.');
this.doInvalidFields();
if(0 == this.errors.length)
return true;
return false;
}
this.doInvalidFields = function()
{
if(this.invalid.length > 0)
{
for(var invalid in this.invalid)
this.getElement(invalid).setAttribute('aria-invalid', true);
}
}
this.setError = function(field, message)
{
this.errors.push(message);
this.invalid.push(field);
}
this.getElementValue = function(element) {
return this.getElement(element).value;
}
this.getElement = function(element) {
return document.getElementById(element);
}
this.getElementName = function() {
return this.getElement('contact-name');
}
this.getElementEmail = function() {
return this.getElement('contact-email');
}
this.getElementMessage = function() {
return this.getElement('contact-message');
}
this.isNameLength = function(){
return this.isLength(this.name, 1, 30);
}
this.isEmailLength = function(){
return this.isLength(this.email, 1, 50);
}
this.isMessageLength = function(){
return this.isLength(this.email, 1, 999);
}
this.isProperEmail = function() {
return this.email.match(/^(?:\w){1,100}#{1}(?:\w){1,100}(?:.){1}(?:\w){1,10}$/ig);
}
this.isLength = function isLength(string, _min, _max) {
if(string.length >= _min && string.length <= _max)
return true;
return false;
}
}
window.onload = function()
{
new Contact_Form(document.forms[0]);
}

The problem is that this is not inherited, and has a different value inside each function.
Then, use
var Contact_Form = function(element){
/* ... */
var that = this;
/* Here this===that */
this.form.onsubmit = function(event)
{
/* Here this===that.form */
event.preventDefault();
that.initData();
if(that.verifyData())
this.send();
}
/* ... */
}

this is referring to the form in the onsubmit handler. You could assign this to a local variable, or bind the handler to the correct this with Function.prototype.bind, ie:
this.form.onsubmit = function(event) {
event.preventDefault();
this.initData();
if(this.verifyData())
this.send();
}.bind(this)
or with jQuery.proxy
this.form.onsubmit = $.proxy(function(event) {
event.preventDefault();
this.initData();
if(this.verifyData())
this.send();
}, this);
Both examples are forcing the this context of the function to be the instance of a Contact_Form whenever the handler is called

Related

The function doesn't work

I've got a problem with this code. When I wrote the first code everything is ok but after processing it doesn't work. Why is it like that? I sent an event object to function as an argument so what's the problem?
Initial code:
var isOkej = null;
function isNumber(someValue) {
return !isNaN(someValue);
}
window.onload = function () {
var wykonawca = document.getElementById("informations").artist;
var tytul = document.getElementById("informations").title;
var label = document.getElementById("informations").label;
var kindOftxt = document.getElementById("kindOftxt");
var action = function (e) {
//pokazuje unicode wpisanego znaku
var wpisanyZnak = e.which;
if (isNumber(this.value) || wpisanyZnak === 190) {
e.preventDefault();
if (this === wykonawca)
kindOftxt.innerHTML = "Podaj swój Alias";
else if (this === tytul)
kindOftxt.innerHTML = "Podaj tytuł utworu";
else
kindOftxt.innerHTML = "Gdzie utwór został wydany";
this.style.backgroundColor = "red";
isOkej = false;
} else {
this.style.backgroundColor = "green";
kindOftxt.innerHTML = "";
isOkej = true;
}
};
wykonawca.onkeyup = action;
tytul.onkeyup = action;
label.onkeyup = action;
}
Final code:
function isNumber(someValue) {
return !isNaN(someValue);
}
var isOkej = null;
function action (e, wykonawca, tytul,kindOftxt) {
//pokazuje unicode wpisanego znaku
var wpisanyZnak = e.which;
if (isNumber(this.value) || wpisanyZnak === 190) {
e.preventDefault();
if (this === wykonawca)
kindOftxt.innerHTML = "Podaj swój Alias";
else if (this === tytul)
kindOftxt.innerHTML = "Podaj tytuł utworu";
else
kindOftxt.innerHTML = "Gdzie utwór został wydany";
this.style.backgroundColor = "red";
isOkej = false;
} else {
this.style.backgroundColor = "green";
kindOftxt.innerHTML = "";
isOkej = true;
}
};
window.onload = function () {
var wykonawca = document.getElementById("informations").artist;
var tytul = document.getElementById("informations").title;
var label = document.getElementById("informations").label;
var kindOftxt = document.getElementById("kindOftxt");
wykonawca.onkeyup = function (e) {
action(e, wykonawca,tytul,kindOftxt);
};
tytul.onkeyup = function (e) {
action(e, wykonawca,tytul,kindOftxt);
};
label.onkeyup = function (e) {
action(e, wykonawca,tytul,kindOftxt);
}; }
I really don't know what can be the reason. What do you think can be a problem?
When you bind the events with the following code, the this inside action function is bound to the input element.
wykonawca.onkeyup = action;
tytul.onkeyup = action;
label.onkeyup = action;
When you bind the events with the updated code
wykonawca.onkeyup = function (e) {
action(e, wykonawca,tytul,kindOftxt);
};
tytul.onkeyup = function (e) {
action(e, wykonawca,tytul,kindOftxt);
};
label.onkeyup = function (e) {
action(e, wykonawca,tytul,kindOftxt);
};
the this inside the anonymous event handlers is bound to the input element, but in the action function, this would refer to the global object i.e. the window object.
You can pass the this reference from your anonymous handlers to the action function as an additional argument.

How to call function of JS added in header?

I have following JS which is added in header. I have button in page. I want to call "FulfillOrder" function of JS.
I don't know how to call it.
Can anybody please suggest me how can I call?
JS:
/// <reference path='../../../../ClientCommon/Sales_ClientCommon.d.ts' />
/// <reference path="../../../../../../TypeDefinitions/CRM/ClientUtility.d.ts" />
/// <reference path='../../../../CommandBarActions/SalesCommandBarActions.d.ts' />
var Sales;
(function (Sales) {
var SalesOrderRibbonActionsLibrary = (function () {
function SalesOrderRibbonActionsLibrary() {
var _this = this;
this.CloseOrFulfillOrder = function (closedState) {
var options = { height: 350, width: 475, position: 1 /* center */ };
options.width = 330;
options.height = 400;
var dialogParams = {};
dialogParams[Sales.MetadataDrivenDialogConstantsOrderClose.SalesId] = Xrm.Page.data.entity.getId();
dialogParams[Sales.MetadataDrivenDialogConstantsOrderClose.ClosedState] = closedState;
Xrm.Navigation.openDialog(Sales.DialogName.CloseOrder, options, dialogParams).then(_this.salesOrderDialogCloseCallback);
};
this.salesOrderDialogCloseCallback = function (response) {
var parameters = response.parameters;
var lastButtonClicked = parameters[Sales.MetadataDrivenDialogConstantsOrderClose.LastButtonClicked];
if (ClientUtility.DataUtil.isNullOrUndefined(lastButtonClicked) || lastButtonClicked.toString() !== ClientUtility.MetadataDrivenDialogConstants.DialogOkId) {
return;
}
var salesOrderId = parameters[Sales.MetadataDrivenDialogConstantsOrderClose.SalesId];
var date = new Date(parameters[Sales.MetadataDrivenDialogConstantsOrderClose.Date]);
var closedState = parseInt(parameters[Sales.MetadataDrivenDialogConstantsOrderClose.ClosedState]);
var reason = parseInt(parameters[Sales.MetadataDrivenDialogConstantsOrderClose.Reason]);
var description = null;
if (!ClientUtility.DataUtil.isNullOrUndefined(parameters[Sales.MetadataDrivenDialogConstantsOrderClose.Description])) {
description = parameters[Sales.MetadataDrivenDialogConstantsOrderClose.Description].toString();
}
if (!ClientUtility.DataUtil.isNullOrUndefined(date) && !ClientUtility.DataUtil.isNullOrUndefined(date)) {
_this.commandBarActions.PerformActionAfterCloseOrder(reason, date, description, closedState, salesOrderId);
}
};
/**
* Processes the sales order.
*/
this.ProcessOrder = function () {
if (Xrm.Page.ui.getFormType() !== 4 /* Disabled */ && Xrm.Page.ui.getFormType() !== 3 /* ReadOnly */) {
Xrm.Page.data.save().then(function (successResponse) {
_this.processOrderSuccessResponse();
}, ClientUtility.ActionFailedHandler.actionFailedCallback);
}
else {
_this.processOrderSuccessResponse();
}
};
this.processOrderSuccessResponse = function () {
var columns = new ODataContract.ColumnSet(false, ["invoiceid"]);
if (!_this.IsBackOfficeInstalled()) {
var convertSalesOrderToInvoiceRequest = new ODataContract.ConvertSalesOrderToInvoiceRequest();
convertSalesOrderToInvoiceRequest.SalesOrderId = { guid: Xrm.Page.data.entity.getId() };
convertSalesOrderToInvoiceRequest.ColumnSet = columns;
Xrm.WebApi.online.execute(convertSalesOrderToInvoiceRequest).then(function (response) {
response.json().then(function (jsonResponse) {
var invoiceId = jsonResponse.invoiceid;
Xrm.Utility.openEntityForm(Sales.EntityNames.Invoice, invoiceId, null);
});
}, ClientUtility.ActionFailedHandler.actionFailedCallback);
}
else {
var defaultStatusCode = -1;
XrmCore.Commands.Common.setState(Xrm.Page.data.entity.getId(), Xrm.Page.data.entity.getEntityName(), Sales.SalesOrderState.Submitted, defaultStatusCode);
}
};
this.IsBackOfficeInstalled = function () {
// var isBackOfficeInstalled: string = Xrm.Internal.getResourceString("IS_BACKOFFICE_INSTALLED");
// if (ClientUtility.DataUtil.isNullOrEmptyString(isBackOfficeInstalled)) {
// return false;
// }
// return isBackOfficeInstalled === "1";
//TODO: investigate backoffice.
return false;
};
this.GetProductsForOrder = function () {
_this.commandBarActions.getProducts();
};
this.LockSalesOrder = function () {
debugger;
_this.commandBarActions.lock();
};
this.UnlockSalesOrder = function () {
debugger;
_this.commandBarActions.unlock();
};
this.CloseOrder = function () {
_this.CloseOrFulfillOrder(Sales.SalesOrderState.Canceled);
};
this.FulfillOrder = function () {
_this.CloseOrFulfillOrder(Sales.SalesOrderState.Fulfilled);
};
this.IsSalesOrderActive = function () {
return _this.IsSalesOrderState(Sales.SalesOrderState.Active);
};
this.IsSalesOrderFulfilled = function () {
return _this.IsSalesOrderState(Sales.SalesOrderState.Fulfilled);
};
this.IsSalesOrderSubmitted = function () {
return _this.IsSalesOrderState(Sales.SalesOrderState.Submitted);
};
this.IsSalesOrderState = function (state) {
var stateCodeControl = Xrm.Page.data.entity.attributes.get("statecode");
var orderState = stateCodeControl ? stateCodeControl.getValue() : null;
var returnValue = false;
if (ClientUtility.DataUtil.isNullOrUndefined(orderState)) {
return returnValue;
}
switch (state) {
case 0:
if (orderState === 0) {
returnValue = true;
}
break;
case Sales.SalesOrderState.Submitted:
if (orderState === Sales.SalesOrderState.Submitted) {
returnValue = true;
}
break;
case Sales.SalesOrderState.Fulfilled:
if (orderState === Sales.SalesOrderState.Fulfilled) {
returnValue = true;
}
break;
case Sales.SalesOrderState.FulfilledOrActive:
if (orderState === Sales.SalesOrderState.Fulfilled || orderState === 0) {
returnValue = true;
}
break;
default:
returnValue = false;
break;
}
return returnValue;
};
}
Object.defineProperty(SalesOrderRibbonActionsLibrary.prototype, "commandBarActions", {
get: function () {
if (ClientUtility.DataUtil.isNullOrUndefined(this._commandBarActions)) {
this._commandBarActions = new Sales.SalesCommandBarActions();
}
return this._commandBarActions;
},
enumerable: true,
configurable: true
});
return SalesOrderRibbonActionsLibrary;
}());
Sales.SalesOrderRibbonActionsLibrary = SalesOrderRibbonActionsLibrary;
})(Sales || (Sales = {}));
/**
* #license Copyright (c) Microsoft Corporation. All rights reserved.
*/
/// <reference path="../../../../../TypeDefinitions/CRM/ClientUtility.d.ts" />
/// <reference path="UCI/SalesOrderRibbonActionsLibrary.ts" />
/// <reference path="../../../../../../references/internal/TypeDefinitions/XrmClientApi/XrmClassicWebClientApi.d.ts" />
var Sales;
(function (Sales) {
var SalesOrderRibbonActions = (function () {
function SalesOrderRibbonActions() {
}
return SalesOrderRibbonActions;
}());
SalesOrderRibbonActions.Instance = new Sales.SalesOrderRibbonActionsLibrary();
Sales.SalesOrderRibbonActions = SalesOrderRibbonActions;
})(Sales || (Sales = {}));
//# sourceMappingURL=SalesOrderRibbonActions.js.map
Previous version of this JS have function "fulfillOrder" and it was working properly. But in this version, they updated a lot. I don't know how to call it.
Please suggest.
Thank you.
If you are calling the methods outside then create an instance and call that FulfillOrder method,
var obj = new Sales.SalesOrderRibbonActionsLibrary();
obj.FulfillOrder(); // now call the methods
You need to call in the way mention below.
Sales.SalesOrderRibbonActionsLibrary.FulfillOrder();

There are some simple questions about my JS.please heip me

This is my js's code(I am chinese and not so good at English) computer said that "window is not defined". But it's same as the code in book(JavaScript DOM),so why?
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}
function insertAfter(newElement, targetElement) {
var parent = targetElement.parentNode;
if (parent.lastChild == targetElement) {
parent.appendChild(newElement);
} else {
parent.insertBefore(newElement, targetElement.nextSibling);
}
}
function preparePlaceholder() {
if (!document.createElement) return false;
if (!document.createTextNode) return false;
if (!document.getElementById) return false;
if (!document.getElementById("imagegallery")) return false;
var placeholder = document.createElement("img");
placeholder.setAttribute("id", "placeholder");
placeholder.setAttribute("src", "images/placeholder.jpg");
placeholder.setAttribute("alt", "my image gallery");
var description = document.createElement("p");
description.setAttribute("id", "description");
var desctext = document.createTextNode("Choose an image");
description.appendChild(desctext);
var gallery = document.getElementById("imagegallery");
insertAfter(placeholder, gallery);
insertAfter(description, placeholder);
}
function prepareGallery() {
if (!document.getElementsByTagName) return false;
if (!document.getElementById) return false;
if (!document.getElementById("imagegallery")) return false;
var gallery = document.getElementById("imagegallery");
var links = gallery.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
links[i].onclick = function() {
return showPic(this);
}
links[i].onkeypress = links[i].onclick;
}
}
function showPic(whichpic) {
if (!document.getElementById("placeholder")) return true;
var source = whichpic.getAttribute("href");
var placeholder = document.getElementById("palceholder");
placeholder.setAttribute("src", source);
if (!document.getElementById("description")) return false;
if (whichpic.getAttribute("title")) {
var text = whichpic.getAttribute("title");
} else {
var text = "";
}
var description = document.getElementById("description");
if (description.firstChild.nodeType == 3) {
description.firstChild.nodeValue = text;
}
return false;
}
addLoadEvent(preparePlaceholder);
addLoadEvent(prepareGallery);
and when i do addLoadEvent(prepareGallery); it said "Function lack of objects"..why? it's also same as the code in book.please help me.

Javascript callback managment

I'm having trouble with designing a class which exposes its actions through callbacks. Yes my approach works for me but also seems too complex.
To illustrate the problem I've drawn the following picture. I hope it is useful for you to understand the class/model.
In my approach, I use some arrays holding user defined callback functions.
....
rocket.prototype.on = function(eventName, userFunction) {
this.callbacks[eventName].push(userFunction);
}
rocket.prototype.beforeLunch = function(){
userFunctions = this.callbacks['beforeLunch']
for(var i in userFunctions)
userFunctions[i](); // calling the user function
}
rocket.prototype.lunch = function() {
this.beforeLunch();
...
}
....
var myRocket = new Rocket();
myRocket.on('beforeLunch', function() {
// do some work
console.log('the newspaper guys are taking pictures of the rocket');
});
myRocket.on('beforeLunch', function() {
// do some work
console.log('some engineers are making last checks ');
});
I'm wondering what the most used approach is. I guess I could use promises or other libraries to make this implementation more understandable. In this slide using callbacks is considered evil. http://www.slideshare.net/TrevorBurnham/sane-async-patterns
So, should I use a library such as promise or continue and enhance my approach?
var Rocket = function () {
this.timer = null;
this.velocity = 200;
this.heightMoon = 5000;
this.goingToMoon = true;
this.rocketStatus = {
velocity: null,
height: 0,
status: null
};
this.listener = {
};
}
Rocket.prototype.report = function () {
for (var i in this.rocketStatus) {
console.log(this.rocketStatus[i]);
};
};
Rocket.prototype.on = function (name,cb) {
if (this.listener[name]){
this.listener[name].push(cb);
}else{
this.listener[name] = new Array(cb);
}
};
Rocket.prototype.initListener = function (name) {
if (this.listener[name]) {
for (var i = 0; i < this.listener[name].length; i++) {
this.listener[name][i]();
}
return true;
}else{
return false;
};
}
Rocket.prototype.launch = function () {
this.initListener("beforeLaunch");
this.rocketStatus.status = "Launching";
this.move();
this.initListener("afterLaunch");
}
Rocket.prototype.move = function () {
var that = this;
that.initListener("beforeMove");
if (that.goingToMoon) {
that.rocketStatus.height += that.velocity;
}else{
that.rocketStatus.height -= that.velocity;
};
that.rocketStatus.velocity = that.velocity;
if (that.velocity != 0) {
that.rocketStatus.status = "moving";
}else{
that.rocketStatus.status = "not moving";
};
if (that.velocity >= 600){
that.crash();
return;
}
if (that.rocketStatus.height == 2000 && that.goingToMoon)
that.leaveModules();
if (that.rocketStatus.height == that.heightMoon)
that.landToMoon();
if (that.rocketStatus.height == 0 && !that.goingToMoon){
that.landToEarth();
return;
}
that.report();
that.initListener("afterMove");
that.timer = setTimeout(function () {
that.move();
},1000)
}
Rocket.prototype.stop = function () {
clearTimeout(this.timer);
this.initListener("beforeStop");
this.velocity = 0;
this.rocketStatus.status = "Stopped";
console.log(this.rocketStatus.status)
this.initListener("afterStop");
return true;
}
Rocket.prototype.crash = function () {
this.initListener("beforeCrash");
this.rocketStatus.status = "Crashed!";
this.report();
this.stop();
this.initListener("afterCrash");
}
Rocket.prototype.leaveModules = function () {
this.initListener("beforeModules");
this.rocketStatus.status = "Leaving Modules";
this.initListener("afterModules");
}
Rocket.prototype.landToMoon = function () {
this.initListener("beforeLandToMoon");
this.rocketStatus.status = "Landing to Moon";
this.goingToMoon = false;
this.initListener("afterLandToMoon");
}
Rocket.prototype.landToEarth = function () {
this.initListener("beforeLandToEarth");
this.stop();
this.rocketStatus.status = "Landing to Earth";
this.initListener("afterLandToEarth");
}
Rocket.prototype.relaunch = function () {
this.initListener("beforeRelaunch");
this.timer = null;
this.velocity = 200;
this.heightMoon = 5000;
this.goingToMoon = true;
this.rocketStatus = {
velocity: 200,
height: 0,
status: "relaunch"
};
this.launch();
this.initListener("afterRelaunch");
}
init;
var rocket = new Rocket();
rocket.on("afterLaunch", function () {console.log("launch1")})
rocket.on("afterLandToMoon", function () {console.log("land1")})
rocket.on("beforeLandToEarth", function () {console.log("land2")})
rocket.on("afterMove", function () {console.log("move1")})
rocket.on("beforeLaunch", function () {console.log("launch2")})
rocket.launch();
You can add any function before or after any event.
This is my solution for this kinda problem. I am not using any special methods anything. I was just wonder is there any good practise for this like problems. I dig some promise,deferred but i just can't able to to this. Any ideas ?

attach event in loop, javascript

I know this is a "classic" and I already tried to read different explanatory articles on this subject, but I still manage to do it wrong somehow. I am talking about adding event handlers and functions in a javascript loop.
Here is my code with problems (it's a suggest-box / auto complete)
function autoCompleteCB(results) {
document.getElementById('autocom').innerHTML = '';
if (results.length == 0) {
document.getElementById('autocom').style.display = 'none';
} else {
document.getElementById('autocom').style.display = 'block';
var divholders = [];
for (var i = 0; i < results.length; i++) {
divholders[i] = document.createElement('div');
divholders[i].style.width = '350px';
var divrestext = document.createElement('div');
divrestext.className = 'autocom0';
divrestext.innerHTML = results[i][0];
divholders[i].appendChild(divrestext);
var divrestype = document.createElement('div');
divrestype.className = 'autocom1' + results[i][1];
divrestype.innerHTML = results[i][1];
divholders[i].appendChild(divrestype);
divholders[i].attachEvent('onmouseover', (function(i) { return function() { divholders[i].style.backgroundColor='#266699'; }; })(i));
divholders[i].attachEvent('onmouseout', (function (i) { return function() { divholders[i].style.backgroundColor = '#F5F5F5'; }; })(i));
document.getElementById('autocom').appendChild(divholders[i]);
}
}
}
It is (of course) the attachevent lines that do not work. This part of javascript is so weird/tricky :) Can a kind expert help me fix those two lines?
This is a half-way fix (I think(:
function bindEvent(element, type, listener) {
if (element.addEventListener) {
element.addEventListener(type, listener, false);
} else if (element.attachEvent) {
element.attachEvent('on' + type, listener);
}
}
function autoCompleteCB(results) {
document.getElementById('autocom').innerHTML = '';
if (results.length == 0) {
document.getElementById('autocom').style.display = 'none';
} else {
document.getElementById('autocom').style.display = 'block';
var divholders = [];
for (var i = 0; i < results.length; i++) {
divholders[i] = document.createElement('div');
divholders[i].style.width = '350px';
var divrestext = document.createElement('div');
divrestext.className = 'autocom0';
divrestext.innerHTML = results[i][0];
divholders[i].appendChild(divrestext);
var divrestype = document.createElement('div');
divrestype.className = 'autocom1' + results[i][1];
divrestype.innerHTML = results[i][1];
// BIND THE EVENTS
divholders[i].appendChild(divrestype);
document.getElementById('autocom').appendChild(divholders[i]);
}
}
}
It looks like this now, but still no "action"
function autoComplete() {
var ss = document.getElementById('txbkeyword').value;
if (ss.length > 0) { CSearch.SearchAutoComplete(ss, 3, autoCompleteCB); }
else { document.getElementById('autocom').style.display = 'none'; }
}
function bindEvent(element, type, listener) {
if (element.addEventListener) {
element.addEventListener(type, listener, false);
} else if (element.attachEvent) {
element.attachEvent('on' + type, listener);
}
}
function autoCompleteCB(results) {
document.getElementById('autocom').innerHTML = '';
if (results.length == 0) {
document.getElementById('autocom').style.display = 'none';
} else {
document.getElementById('autocom').style.display = 'block';
var divholders = [];
for (var i = 0; i < results.length; i++) {
divholders[i] = document.createElement('div');
divholders[i].style.width = '350px';
var divrestext = document.createElement('div');
divrestext.className = 'autocom0';
divrestext.innerHTML = results[i][0];
divholders[i].appendChild(divrestext);
var divrestype = document.createElement('div');
divrestype.className = 'autocom1' + results[i][1];
divrestype.innerHTML = results[i][1];
(function (i) {
bindEvent(divholders[i], 'mouseover', function () {
divholders[i].style.backgroundColor = '#266699';
});
bindEvent(divholders[i], 'mouseout', function () {
divholders[i].style.backgroundColor = '#F5F5F5';
});
})(i);
divholders[i].appendChild(divrestype);
document.getElementById('autocom').appendChild(divholders[i]);
}
}
}
One possibility is because attachEvent is IE-specific. You'll have to use attachEventListener in many other browsers.
And, to use the "proper" method for the current browser, you'll need to feature-detect them (snippet from MDN):
if (el.addEventListener){
el.addEventListener('click', modifyText, false);
} else if (el.attachEvent){
el.attachEvent('onclick', modifyText);
}
You can also create a function to aid in this:
function bindEvent(element, type, listener) {
if (element.addEventListener) {
element.addEventListener(type, listener, false);
} else if (element.attachEvent) {
element.attachEvent('on' + type, listener);
}
}
Then, in place of these 2 lines:
divholders[i].attachEvent('onmouseover', (function(i) { return function() { divholders[i].style.backgroundColor='#266699'; }; })(i));
divholders[i].attachEvent('onmouseout', (function (i) { return function() { divholders[i].style.backgroundColor = '#F5F5F5'; }; })(i));
...use the function to bind your handlers (skipping the on in the event type argument):
(function (i) {
bindEvent(divholders[i], 'mouseover', function () {
divholders[i].style.backgroundColor = '#266699';
});
bindEvent(divholders[i], 'mouseout', function () {
divholders[i].style.backgroundColor = '#F5F5F5';
});
})(i);
You could also just enclose the <div>:
(function (div, i) {
bindEvent(div, 'mouseover', function () {
div.style.backgroundColor = '#266699';
});
bindEvent(div, 'mouseout', function () {
div.style.backgroundColor = '#F5F5F5';
});
})(divholders[i], i);
Try this:
divholders[i].attachEvent('onmouseover', this.style.backgroundColor='#266699');

Categories

Resources