this.property is undefined: Cannot read property 'classList' of undefined - javascript

I'm making something to visualize photographs.
The goal is to select the picture you want in the "list" to make it appear on the main HTML element. But to help you find where you are in the list there's a class putting borders on the element you selected.
The issue :
The function executing with the event this.block.onclick = function () begins well, the .selected is removed from the initial selected element, but when comes this.block.classList.add('selected'); I get this error:
media_visu.js:26 Uncaught TypeError: Cannot read property 'classList' of undefined
I tried to put the function outside, tried className, setAttribute, but nothing changed: my this.block seems to be undefined.
mediavisu.js :
var mediaVisu = function () {
'use strict';
window.console.log('mediaVisu loaded');
var i,
visu = document.querySelector("#img"),
Album = [];
function Photo(nb, folder) {
this.block = document.querySelector("#list_img_" + nb);
this.place = 'url(../src/' + folder + '/' + nb + '.jpg)';
this.block.onclick = function () {
for (i = 0; i < Album.length; i += 1) {
window.console.log(Album[i].block);
if (Album[i].block.classList.contains('selected')) {
Album[i].block.classList.remove('selected');
}
}
visu.style.background = this.place;
window.console.log(visu.style.background);
window.console.log(this.place);
this.block.classList.add('selected');
};
Album[Album.length] = this;
}
var test_a = new Photo(1, "test"),
test_b = new Photo(2, "test"),
test_c = new Photo(3, "test"),
test_d = new Photo(4, "test"),
test_e = new Photo(5, "test");
window.console.log(Album);
for (i = 0; i < Album.length; i += 1) {
window.console.log(Album[i]);
}
};

in the onclick function, this will be the element that was clicked
so you can simply use
this.classList.add('selected');
you may need to rethink using this.place as this wont be the this you think it is .. a common solution is as follows
function Photo(nb, folder) {
this.block = document.querySelector("#list_img_" + nb);
this.place = 'url(../src/' + folder + '/' + nb + '.jpg)';
var self = this;
this.block.onclick = function () {
for (i = 0; i < Album.length; i += 1) {
window.console.log(Album[i].block);
if (Album[i].block.classList.contains('selected')) {
Album[i].block.classList.remove('selected');
}
}
visu.style.background = self.place;
window.console.log(visu.style.background);
window.console.log(self.place);
this.classList.add('selected');
};
Album[Album.length] = this;
}
alternatively, using bind
function Photo(nb, folder) {
this.block = document.querySelector("#list_img_" + nb);
this.place = 'url(../src/' + folder + '/' + nb + '.jpg)';
this.block.onclick = function () {
for (i = 0; i < Album.length; i += 1) {
window.console.log(Album[i].block);
if (Album[i].block.classList.contains('selected')) {
Album[i].block.classList.remove('selected');
}
}
visu.style.background = this.place;
window.console.log(visu.style.background);
window.console.log(this.place);
this.block.classList.add('selected');
}.bind(this);
Album[Album.length] = this;
}
note: now you go back to this.block.classList.add('selected') as this is now the this you were expecting before

You can access to it with 'this' (as mentionned in the previous answer) or with the event target :
this.block.onclick = function (e) {
for (i = 0; i < Album.length; i += 1) {
window.console.log(Album[i].block);
if (Album[i].block.classList.contains('selected')) {
Album[i].block.classList.remove('selected');
}
}
visu.style.background = this.place;
window.console.log(visu.style.background);
window.console.log(this.place);
e.target.classList.add('selected');
};

Related

Getting javascript undefined TypeError

Please help....Tried executing the below mentioned function but web console always shows
TypeError: xml.location.forecast[j] is undefined
I was able to print the values in alert but the code is not giving output to the browser because of this error. Tried initializing j in different locations and used different increment methods.How can i get pass this TypeError
Meteogram.prototype.parseYrData = function () {
var meteogram = this,xml = this.xml,pointStart;
if (!xml) {
return this.error();
}
var j;
$.each(xml.location.forecast, function (i,forecast) {
j= Number(i)+1;
var oldto = xml.location.forecast[j]["#attributes"].iso8601;
var mettemp=parseInt(xml.location.forecast[i]["#attributes"].temperature, 10);
var from = xml.location.forecast[i]["#attributes"].iso8601;
var to = xml.location.forecast[j]["#attributes"].iso8601;
from = from.replace(/-/g, '/').replace('T', ' ');
from = Date.parse(from);
to = to.replace(/-/g, '/').replace('T', ' ');
to = Date.parse(to);
if (to > pointStart + 4 * 24 * 36e5) {
return;
}
if (i === 0) {
meteogram.resolution = to - from;
}
meteogram.temperatures.push({
x: from,
y: mettemp,
to: to,
index: i
});
if (i === 0) {
pointStart = (from + to) / 2;
}
});
this.smoothLine(this.temperatures);
this.createChart();
};
You are trying to access the element after the last one. You can check if there is the element pointed by j before proceeding:
Meteogram.prototype.parseYrData = function () {
var meteogram = this,
xml = this.xml,
pointStart;
if (!xml) {
return this.error();
}
var i = 0;
var j;
$.each(xml.location.forecast, function (i, forecast) {
j = Number(i) + 1;
if (!xml.location.forecast[j]) return;
var from = xml.location.forecast[i]["#attributes"].iso8601;
var to = xml.location.forecast[j]["#attributes"].iso8601;
});
};

add an object or edit if exist (indexeddb)

I have this code and i can add or edit the object if exists, but the "for" finish before the function onsuccess is called, then the index "for" is bad.
How to pass the index onSuccess?
Help!!!
var active = dataBase.result;
var data = "";
var object = "";
var index = null;
var request;
$(".layers").promise().done(function () {
var elements = document.getElementsByClassName('layers');
for (var i = 0; typeof (elements[i]) != 'undefined'; i++) {
if (elements[i].getAttribute("src").split("/")[4] !== "alpha.png") {
data = active.transaction([elements[i].getAttribute("src").split("/")[3]], "readwrite");
object = data.objectStore(elements[i].getAttribute("src").split("/")[3]);
index = object.index("by_Name");
request = index.get(String(elements[i].getAttribute("src").split("/")[4] + "/" + elements[i].getAttribute("src").split("/")[6]));
request.onsuccess = function (e) {
var result = e.target.result;
if (result === undefined) {
var resultPut = object.put({
Name: String(elements[i].getAttribute("src").split("/")[4] + "/" + elements[i].getAttribute("src").split("/")[6]),
Count: 1,
Type: String(elements[i].getAttribute("src").split("/")[4])
});
resultPut.onerror = function (e) {
alert(resultPut.error.name + '\n\n' + resultPut.error.message);
};
} else {
result.Count++;
var requestUpdate = object.put(result);
requestUpdate.onerror = function (event) {
alert(requestUpdate.error.name + '\n\n' + requestUpdate.error.message);
};
}
}(event);
}
}
alert("Finish");
})
The thing is that, by the time the for has ended, the transactions with the object store are not. What you could try is to encapsulate the index like this:
for(var i = 0; i < elements.length; i++) {
(function(myElement) {
if (myElement.getAttribute("src").split("/")[4] !== "alpha.png") {
...
}
})(elements[i]);
}

Array length remains 0 even though I push 'objects' to it

I have a little piece of code that reads some ajax (this bit works) from a server.
var self = this;
var serverItems = new Array();
var playersOnlineElement = $("#playersOnline");
function DataPair(k, v) {
this.key = k;
console.log("new datapair: " + k + ", " + v);
this.value = v;
}
DataPair.prototype.getKey = function() {
return this.key;
}
DataPair.prototype.getValue = function() {
return this.value;
}
$.getJSON("http://127.0.0.1", function(data) {
$.each(data, function(key, val) {
var pair = new DataPair(key, val);
self.serverItems.push(pair);
});
});
console.log(serverItems.length); //Problem is here
for (var i = 0; i < serverItems.length; i = i + 1) {
var dpair = serverItems[i];
if (dpair.getKey() === "playersOnline") {
self.playersOnlineElement.text("Players Online: " + dpair.getValue());
}
}
The datapair and the JSON get loaded but when they are pushed to the array it doesn't seem to work. I tried with self.serverItems and just serverItems because netbeans showed me the scope of the variables being good if I used just serverItems but I am a bit confused as to why this doesn't work. Can anyone help me?
I put in comments where the error is. serverItems.length is 0 even though when debugging in a browser in the DOM tree it has an array serverItems with all the data inside.
Assumingly this serverItems is in another scope and not the one I am calling when I want to get the length?
add this code into the success part, since its asynchronous...
for (var i = 0; i < serverItems.length; i = i + 1) {
var dpair = serverItems[i];
if (dpair.getKey() === "playersOnline") {
self.playersOnlineElement.text("Players Online: " + dpair.getValue());
}
to...
$.getJSON("http://127.0.0.1", function(data) {
$.each(data, function(key, val) {
var pair = new DataPair(key, val);
self.serverItems.push(pair);
for (var i = 0; i < serverItems.length; i = i + 1) {
var dpair = serverItems[i];
if (dpair.getKey() === "playersOnline") {
self.playersOnlineElement.text("Players Online: " + dpair.getValue());
}
});
});

Can this jQuery be done in vanilla JS?

I've got this working on mobile devices, but because of the 32kb gzip-ed of jQuery I wonder if it's possible to create this code
$(document).ready(function() {
$('body').addClass('js');
var $menu = $('#menu'),
$menulink = $('.menu-link'),
$wrap = $('#wrap');
$menulink.click(function() {
$menulink.toggleClass('active');
$wrap.toggleClass('active');
return false;
});
});
can be written in no library dependany vanilla JavaScript.
Can it be done? Where would I start?
JQuery uses javascript/DOMscripting to create its framework. Everything JQuery does, can be done in basic scripting. For example $('body').addClass('js') can be written as:
document.querySelector('body').className += ' js';
And $menulink.toggleClass('active'); as something like
var current = $menulink.className.split(/\s+/)
,toggleClass = 'active'
,exist = ~current.indexOf(toggleClass)
;
current.splice(exist ? current.indexOf(toggleClass) : 0,
exist ? 1 : 0,
exist ? null : toggleClass);
$menulink.className = current.join(' ').replace(/^\s+|\s+$/,'');
That's why JQuery wrapped this kind of code.
This jsfiddle contains a working example using javascript without a framework. Besides that it demonstrates how to program your own element wrapper.
Where to start? You'll have to dive into javascript I suppose. Or check this SO-question
For modern browsers only.®
document.addEventListener('DOMContentLoaded', function() {
document.body.classList.add('js');
var wrap = document.getElementById('wrap');
var menuLinks = Array.prototype.slice.call(document.getElementsByClassName('menu-link'));
var toggleActive = function(element) {
element.classList.toggle('active');
};
menuLinks.forEach(function(menuLink) {
menuLink.addEventListener('click', function(e) {
menuLinks.forEach(toggleActive);
toggleActive(wrap);
}, false);
});
}, false);
var toggleClass = function (el, className) {
if(el) {
if(el.className.indexOf(className)) {
el.className = el.className.replace(className, '');
}
else {
el.className += ' ' + className;
}
}
};
document.addEventListener('DOMContentLoaded', function () {
document.body.className += ' js';
var $menu = document.querySelector('#menu'),
$menulink = document.querySelectorAll('.menu-link'),
$wrap = document.querySelector('#wrap');
$menulink.addEventListener('click', function (e) {
toggleClass($menulink, 'active');
toggleClass($wrap, 'active');
e.preventDefault();
});
});
There's always classList (workaround for incompatible browsers included).
Absolutely. Since jQuery is a subset of JavaScript (written entirely in JavaScript) any function you like can be duplicated. It's a matter of how much effort you want to put into it. Below is how I would duplicate the limited subset of jQuery in your post and it's reasonably cross-browser compatible (if a wee bit long...).
var Vanilla;
if (!Vanilla) {
Vanilla = {};
}
//execute this now to have access to it immediately.
(function () {
'use strict';
Vanilla.addHandler = function (elem, event, handler) {
if (elem.addEventListener) {
elem.addEventListener(event, handler, false);
} else if (elem.attachEvent) {
elem.attachEvent('on' + event, handler);
}
};
Vanilla.hasClass = function (elem, cssClass) {
var classExists = false;
//
if (elem && typeof elem.className === 'string' && (/\S+/g).test(cssClass)) {
classExists = elem.className.indexOf(cssClass) > -1;
}
//
return classExists;
};
Vanilla.addClass = function (elem, cssClass) {
if (elem && typeof elem.className === 'string' && (/\S+/g).test(cssClass)) {
//put spaces on either side of the new class to ensure boundaries are always available
elem.className += ' ' + cssClass + ' ';
}
};
Vanilla.removeClass = function (elem, cssClass) {
if (elem && typeof elem.className === 'string'&& (/\S+/g).test(cssClass)) {
//replace the string with regex
cssClass = new RegExp('\\b' + cssClass + '\\b', 'g');
elem.className = elem.className.replace(cssClass, '').replace(/^\s+/g, '').replace(/\s+$/g, ''); //trim className
}
};
Vanilla.toggleClass = function (elem, cssClass) {
if (Vanilla.hasClass(elem, cssClass)) {
Vanilla.removeClass(elem, cssClass);
} else {
Vanilla.addClass(elem, cssClass);
}
};
Vanilla.getElementsByClassName = function (cssClass) {
var nodeList = [],
classList = [],
allNodes = null,
i = 0,
j = 0;
if (document.getElementsByClassName1) {
//native method exists in browser.
nodeList = document.getElementsByClassName(cssClass);
} else {
//need a custom function
classList = cssClass.split(' ');
allNodes = document.getElementsByTagName('*');
for (i = 0; i < allNodes.length; i += 1) {
for (j = 0; j < classList.length; j += 1) {
if (Vanilla.hasClass(allNodes[i], classList[j])) {
nodeList.push(allNodes[i]);
}
}
}
}
return nodeList;
};
}());
//Now we have a proper window onload
Vanilla.addHandler(window, 'load', function () {
'use strict';
var body = document.body,
menu = document.getElementById('menu'),
menulink = [],
wrap = document.getElementById('wrap'),
i = 0,
menulinkClickHandler = function (e) {
var i = 0;
for (i = 0; i < menulink.length; i += 1) {
Vanilla.toggleClass(menulink[i], 'active');
}
Vanilla.toggleClass(wrap, 'active');
return false;
};
Vanilla.addClass(body, 'js');
menulink = Vanilla.getElementsByClassName('menu-link');
for (i = 0; i < menulink.length; i += 1) {
Vanilla.addHandler(menulink[i], 'click', menulinkClickHandler);
}
});

javascript abstract console logging

I want to make a function, like this.
For example:
function Logger() {
this.log = function(msg) {
console.log(msg);
}
}
And I want to use it in functions/modules etc, and that all works fine.
But the default console in my browser normally give the fileName + lineNumber.
Now when I abstract this functionality, the fileName and lineNumber is not where I put my instance.log(). Because it will say from where the console.log is being called, not the function itself.
So my question:
How can I get the correct information from where I want to use my logger?
Or give me, please, any tips to improve this functionality.
function Logger() {
this.log = console.log.bind(console);
}
I asked about this some time ago: Create shortcut to console.log() in Chrome.
Try using backtrace function like this one :
function printStackTrace() {
var callstack = [];
var isCallstackPopulated = false;
try {
i.dont.exist += 0; //doesn't exist- that's the point
} catch (e) {
if (e.stack) { //Firefox
var lines = e.stack.split('\n');
for (var i = 0, len = lines.length; i & lt; len; i++) {
if (lines[i].match(/^\s*[A-Za-z0-9\-_\$]+\(/)) {
callstack.push(lines[i]);
}
}
//Remove call to printStackTrace()
callstack.shift();
isCallstackPopulated = true;
}
else if (window.opera & amp; & amp; e.message) { //Opera
var lines = e.message.split('\n');
for (var i = 0, len = lines.length; i & lt; len; i++) {
if (lines[i].match(/^\s*[A-Za-z0-9\-_\$]+\(/)) {
var entry = lines[i];
//Append next line also since it has the file info
if (lines[i + 1]) {
entry += ' at ' + lines[i + 1];
i++;
}
callstack.push(entry);
}
}
//Remove call to printStackTrace()
callstack.shift();
isCallstackPopulated = true;
}
}
if (!isCallstackPopulated) { //IE and Safari
var currentFunction = arguments.callee.caller;
while (currentFunction) {
var fn = currentFunction.toString();
var fname = fn.substring(fn.indexOf( & amp; quot;
function & amp; quot;) + 8, fn.indexOf('')) || 'anonymous';
callstack.push(fname);
currentFunction = currentFunction.caller;
}
}
output(callstack);
}
function output(arr) {
//Optput however you want
alert(arr.join('\n\n'));
}
Try assigning the function:
(function () {
window.log = (console && console.log
? console.log
: function () {
// Alternative log
});
})();
Later just call log('Message') in your code.

Categories

Resources