I am building a drag'n'drop gui builder in Javascript. So far so good.
As I add items to the GUI and configure them; I have two mechanisms for addressing them:
the 'class' - which I use for doing things to all instances of an item (eg CSS, generic functionality and so on and so forth) and which I can bind javascript libraries to... and I can make full use of polymorphic class names (ie class="name1 name2 name3 name4" with different things bound to each class name...)
the 'id' - which refers to this particular instance of a text box or a paragraph and which I can bind javascript libraries to
My problem is this: the 'id' must be unique across all html items on the page (by definition) so how do I ensure this? I need to get all the id's of all the items and then maintain some sort of state table.
Starting from a blank bit of html this is pretty reasonable - but I need to start from a partly created bit of html with a mixture of existing 'id's - some of which will be in my unique scheme and some of which wont be...
The way to do this best ought to be a solved problem.
Suggestions, tips, examples?
The best way to do this will depend entirely upon the structure and organization of your javascript. Assuming that you are using objects to represent each of your GUI elements you could use a static counter to increment your ids:
// Your element constructor
function GuiElement() {
this.id = GuiElement.getID();
}
GuiElement.counter = 0;
GuiElement.getID = function() { return 'element_' + GuiElement.counter++; };
Of course you probably have more than one type of element, so you could either set each of them up so that they have their own counter (e.g. form_1, form_2, label_1, label_2) or so that they all share a counter (e.g. element_1, element_2, element_3), but either way you will probably want them to inherit from some base object:
// Your base element constructor
function GuiElement(tagName, className) {
this.tagName = tagName;
this.className = className;
}
GuiElement.counter = 0;
GuiElement.getID = function() { return 'element_' + GuiElement.counter++; };
GuiElement.prototype.init = function() {
this.node = document.createElement(this.tagName);
this.node.id = this.id = GuiElement.getID();
this.node.className = this.className;
}
// An element constructor
function Form() {
this.init();
}
Form.prototype = new GuiElement('form', 'form gui-element');
// Another element constructor
function Paragraph() {
this.init();
}
Paragraph.prototype = new GuiElement('p', 'paragraph gui-element');
You could also go this route if you would rather keep some variables "private":
// Your element constructor constructor
var GuiElement = (function() {
var counter = 0;
function getID() {
return 'element_' + counter++;
}
return function GuiElement(tagName, className) {
return function() {
this.node = document.createElement(tagName);
this.node.id = this.id = getID();
this.node.className = className + ' gui-element';
this.className = className;
};
}
})();
// Create your element constructors
var Form = GuiElement('form', 'form'),
Paragraph = GuiElement('p', 'paragraph');
// Instantiate elements
var f1 = new Form(),
f2 = new Form(),
p1 = new Paragraph();
Update: If you need to verify that an id is not already in use then you could add the check you and of the getID methods:
var counter = 0;
function getID() {
var id = 'element_' + counter++;
while(document.getElementById(id)) id = 'element_' + counter++;
return id;
}
function uniqueId() {
return 'id_' + new Date().getTime();
}
If you happen to be using the Prototype library (or want to check it out), you can use the Element.identify() method.
Otherwise, Darin's response is a good idea as well.
function generateId() {
var chars = "0123456789abcdefghiklmnopqrstuvwxyz",
string_length = 8,
id = '';
for (var i = 0; i < string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
id += chars.substring(rnum, rnum + 1);
}
return id;
}
Close enough to unique is good enough. Don't use the Date() solution unless you're only generating a single ID at any given time...
Related
In my code like ,
function ElementBase(name) {
this.tagName = typeof name != "" ? name : 'div';
this.createElem();
}
ElementBase.prototype = {
createElem: function() {
this.elem = document.createElement(this.tagName);
},
getIndex: function() {
var nodes = this.elem.parentNode.childNodes,
node;
var i = count = 0;
while ((node = nodes.item(i++)) && node != this.elem)
if (node.nodeType == 1) count++;
return (count);
}
};
I try to create the DOM element tag is "div".
function Div() {
this.tagName = 'div'
ElementBase.call(this, this.tagName);
}
Div.prototype = Object.create(ElementBase.prototype);
My Question is,
1) How to access the getIndex function from the html document after inserting the created objects?
example:
var div = new Div();
div.id = "d1"
document.body.appendChild(div.elem);
// After div.getIndex() working
Then some situation i need the index value of that div (id="d1") element from document.
var d= document.getElementById("d1");
d.getIndex() //not working
What mistakes i did it in above code?
thanks advance..
I think when you do document.body.appendChild(div.elem) you just do document.body.appendChild(document.createElement('div')) nothing more.
And when you do var d= document.getElementById("d1"); d is just an object return from the DOM that has nothing to do with your var div
what you can do is:
Div.prototype.getIndex.call(d);
But that doesn't actually extend your object. Actually extending a DOM object is a bad practice (check this http://perfectionkills.com/whats-wrong-with-extending-the-dom/).
Look closely at your code.
div is an instance of Div and it has a property .elem that holds the actual DOM element.
So when you do div.id = "d1", you are not setting the id of the DOM element.
var div = new Div();
div.id = 'd1'; // <div></div>
div.elem.id = 'd1'; // <div id="d1"></div>
But there's one more problem: when you do d= document.getElementById("d1"), what you get is a DOM element, not an instance of Div().
Since .getIndex() is defined on .prototype of Div(), plain old DOM elements don't have access to it.
How you solve this situation depends on what exactly you need to accomplish with your code.
Edit 1: In response to OP's comment:
document.getElementById() returns an instance of HTMLDivElement, which is fundamentally different from an instance of Div.
One solution is to use a setter method:
function Div() {
// ...
}
Div.prototype.setId = function setId(id) {
this.elem.id = id;
}
var div = new Div();
div.setId('d1'); // same as doing div.elem.id = 'd1';
another solution is to use id in the constructor function itself:
function Div(id) {
// ...
this.elem.id = id; // or you can use "this.setId(id)"
/*
if "id" is provided,
it will take that value,
else it is set to "undefined",
which is the same as not being set
*/
}
Div.prototype.setId = function setId(id) {
this.elem.id = id;
}
var div = new Div('d1'); // same as doing div.elem.id = 'd1';
div.setId('d2'); // same as doing div.elem.id = 'd2';
I have 3 "dice" objects created from this custom constructor:
function Dice() {
this.value = 0;
this.keep = false;
this.roll = function() {
this.value = Math.floor(Math.random()*6)+1;
};
}
Then, inside function rollOnce(), I have 3 HTML buttons inside a document.getElementById("paragraph1").innerHTML command that will display each dice's value as follows:
function rollOnce() {
(...)
document.getElementById("paragraph1").innerHTML =
'<button id="diceOne" class="unkept" onclick="keepDice(this.id)">'+dice1.value+'</button> ' +
'<button id="diceTwo" class="unkept" onclick="keepDice(this.id)">'+dice2.value+'</button> ' +
'<button id="diceThree" class="unkept" onclick="keepDice(this.id)">'+dice3.value+'</button> ';
}
Now, function keepDice(diceId) will set attribute class="kept" for each dice/button that has been clicked.
The next thing I want to do is to know which dice variable (dice1, dice2, dice3) has been clicked (in order to keep their value by doing diceN.keep = true;. Because after that there will be another round of the game in which only those dice which are "unkept" will get another diceN.roll() call. But my knowledge is still very limited and I only know how to access (HTML only) elements by using document.getElementsBy(...) (this is the HTML DOM, right? I'm currently learning this at W3Schools).
I have not yet learned about jQuery, AngularJS and all the other cool webdev stuff. So if it is possible to answer using only Javascript it would be much appreciated (even if other libs would make it easier! It's a bonus if there are alternative solutions and I would be happy to learn too!). Is this possible at all?
Thanks in advance,
Maybe something like class="kept-'+dice1.keet+'" onclick="keepDice(1)"
then
function keepDice(index){
dices[index].keep = true;
turns--;
if (turns > 0) {
rollOnce()
}
}
Try this:
function keepDice(id) {
var whichDice;
switch(id) {
case 'diceOne':
whichDice = dice1;
break;
case 'diceTwo':
whichDice = dice2;
break;
case 'diceThree':
whichDice = dice3;
break;
}
whichDice.keep = true;
}
If you stored your dice in an associative array like this:
dice['diceOne'] = new Dice();
dice['diceTwo'] = new Dice();
dice['diceThree'] = new Dice();
you would create the buttons almost the same way
<button id="diceOne" class="unkept" onclick="keepDice(this.id)">dice["diceOne"].value</button>
you could then write your dice function like this
function keepDice(id)
{
dice[id].keep = true;
document.GetElementById(id).setAttribute("class","kept");
//...
}
I came back to this again and realised there's a better way. It's quite a different approach than what you've got so far, but let me explain...
I know your question title is "How to get Javascript object from HTML element" but my answer better serves the question "How to get HTML element from Javascript object" and also better solves the problem you're facing.
First, I set the stage by creating a container element #paragraph1 and a "Roll Once" button which runs the rollOnce() function
<p id="paragraph1"></p>
<button onclick="rollOnce()">Roll Once</button>
Then I create the Dice() Object which takes a parameter - this parameter is the id of the element we wish to use as a container. We must wait for the HTML to load before we can find that container because until then, it simply doesn't exist yet. That's why I have bound a function to the document.onreadystatechange event.
So when the HTML has loaded and the document is ready, I initialise the Object, storing it in a var and the Object has all the required functions built-in for managing it's button.
function Dice(container) {
this.button = document.createElement("button");
this.button.innerHTML = 0;
document.getElementById(container).appendChild(this.button);
this.button.addEventListener('click', function() {
this.className = 'kept';
});
this.roll = function() {
if(this.button.className != 'kept') {
this.button.innerHTML = Math.floor(Math.random()*6)+1;
}
}
}
var dice1;
var dice2;
var dice3;
document.onreadystatechange = function () {
if(document.readyState == "complete") {
dice1 = new Dice("paragraph1");
dice2 = new Dice("paragraph1");
dice3 = new Dice("paragraph1");
rollOnce();
}
}
function rollOnce() {
dice1.roll();
dice2.roll();
dice3.roll();
}
Fully working demonstration is here: http://codepen.io/anon/pen/groEmg
Edit: If you want to get the values of the dice later, you can access the Objects' properties like so: dice1.button.innerHTML
You need to keep track of what has been kept and what has not been kept. It would be useful to hold all the dice functionality inside the dice class. every time you run rollOnce() you must also represent the kept/unkept state in the className.
Here's an example including what I gather is your current initialisation - define var dice then define rollOnce() then run rollOnce()
function Dice() {
this.value = 0;
this.kept = false;
this.roll = function() {
if(!this.kept) this.value = Math.floor(Math.random()*6)+1;
};
this.keep = function(id) {
this.kept = true;
document.getElementById(id).className = 'kept';
}
}
var dice1 = new Dice();
var dice2 = new Dice();
var dice3 = new Dice();
function rollOnce() {
dice1.roll();
dice2.roll();
dice3.roll();
document.getElementById("paragraph1").innerHTML =
'<button id="diceOne" class="'+(dice1.kept?'kept':'keep')+'" onclick="dice1.keep(\'diceOne\')">'+dice1.value+'</button> ' +
'<button id="diceTwo" class="'+(dice2.kept?'kept':'keep')+'" onclick="dice2.keep(\'diceTwo\')">'+dice2.value+'</button> ' +
'<button id="diceThree" class="'+(dice3.kept?'kept':'keep')+'" onclick="dice3.keep(\'diceThree\')">'+dice3.value+'</button> ';
}
rollOnce();
I've made it pass an ID to Dice.keep(id) just to have a live update of the DOM element which represents this Object variable.
Some clarification on the classnames since you're a beginner: I used ternary logic operators to quickly perform an IF THEN ELSE
So the part that says dice1.kept?'kept':'keep'
Actually means IF dice1.kept THEN 'kept' ELSE 'keep'
You can put a blank '' instead of 'keep' if you like since I don't think it's being used (but you might use it for CSS). Of course, there is plenty of room for improvement all over this code, but I wanted to keep it as similar to your sample code as possible. In fact, the first thing I would do is probably change the onclick to this: onclick="dice1.keep(this)" and then change your object like:
this.keep = function(button) {
this.kept = true;
button.className = 'kept';
}
http://codepen.io/anon/pen/MyrxyX
Edit: here's a slightly modified version where the Dice() object is agnostic to the DOM but still provides all the relevant data: http://codepen.io/anon/pen/MyrxbB
I really need help with an aspect of my project. My ultimate goal is to capture the changes made by a user and once they select confirm, post it to SQL for updating. I will use AJAX and PHP for the latter part of the project but I thought JSON would be a great idea to hold all the changes made by a user (the first part).
I am new to JSON and I'm having trouble putting the results in one large object that will be transferred to the server when the user selects "OK". Can someone help me with the coding of this? Is JSON the best way to accomplish the goal (of storing temporary?
Heres what I have so far (just a snippet):
HTML
<div class="button" data-info='2' data-id='8-7' onclick=addDeskid(e)></div>
<div class="button" data-info='4' data-id='2-5' onclick=remDeskId()></div>
<div class="button" value="submit">submit</div>
JS
function addDeskId(e){
$adjustment;
userObject = $(this);
userObjectChange = 'CHANGE_SEAT_TO'; //This is what i will use with AJAX and PHP to determine the SQL statement
userObjectID = userObject.attr('data-info'); //This is the unique SQL ID for the object being modified
userObjectDeskID = userObject.attr('data-id'); //This is the attribute for the object being modified
userObjectSeatID = 9-4; //This is what the attribute is being modified to, for the question, ill make it a solid value
var addUserObject = new jsonAddTest(userObjectID, userObjectChange, userObjectDeskID, userObjectSeatID,);
//this is what the function is actually doing on the user side
//$dragObject.attr("data-id",newSeat); //change desk number for new user location
//$dragObject.attr("previousseat", "T");
//var extPass = e;
//moveOrSetupAccountLog(extPass);
}
function remDeskId(){
userObject = $dropObject.find('div.dragTest');
userObjectChange = 'REMOVESEAT'; //This is what i will use with AJAX and PHP to determine the SQL statement
userObjectID = userObject.attr('data-info'); //This is the unique SQL ID for the object being modified
userObjectDeskID = userObject.attr('data-id'); //This is the attribute for the object being modified
userObjectDeskIDVal = 0; //This is what the attribute is being modified to
var remUserObject = new jsonRemTest(userObjectID, userObjectChange, userObjectDeskID, userObjectDeskIDVal);
//this is what the function is actually doing on the user side
//userObject.attr({"data-id":""}); //remove desk number for new user location
//userObject.appendTo('#userPool');
}
//JSON functions test
function jsonRemTest(id, change, name, seat, value){
this.ID = id;
this.ChangeType = change;
this.Name = name;
this.Seat = seat;
this.setTo = value;
userMoves.push(jsonRemTest);
}
function jsonAddTest(id, change, name, desk, seat, previousseat, previousseatnewvalue){
this.ID = id;
this.ChangeType = change;
this.Name = name;
this.Seat = desk;
this.setTo = seat;
this.PreviousSeatValue = previousseat;
this.PreviousSeatNewValue = previousseatnewvalue;
userMoves.push(jsonAddTest);
}
console.log(JSON.stringify(userMoves));
I am getting the error: userMoves is undefined. I understand why this is happening but I don't know how to correct it.
TL;DR
Every time the user clicks on this button, it generates an array. I want to combine all the arrays into one object that contains all of them. When the user clicks on a submit button, the object is sent to the server using AJAX/PHP. Is this the best way to do this and if so, how do I combine the output of the JSON functions into one object in preparation for sending?
Thanks in advance
OK, Let's tackle this with some recommendations.
First off your onclick=addDeskid(e) is not properly cased to call your function and well, it is in the markup not the code, so let's address that.
I also changed your markup slightly to work with my event handlers better using a class for myAddButton and myRemButton, do what you will with that but I used it. I also added a button to get the results logged after all the events fired. This is the reason you get [] you have nothing in there when it gets logged. I did nothing with the submit, that is yours to handle (ajax call?)
<div class="button myAddButton" data-info='2' data-id='8-7'>add</div>
<div class="button myRemButton" data-info='4' data-id='2-5'>remove</div>
<div class="button mySubmitButton">submit</div>
<button id="ShowResults" type='button'>ShowResults</button>
Now the code - I re-engineered this to create a "class" for the object using makeClass. This is just one way but does allow for instance objects when needed and makes it easier to namespace some functions. I artificially put a private function in there just to demonstrate use as well as a public function. Note the the "this" inside that function is the instance object NOT a global object. (google makeClass with the attributed authors for more info)
I created a "class" with generic attributes. You COULD create different functions for "add" and "remove" instead of the SetChangeObject function - like one for each...I used a generic one so the "object" has the same signature.
Now the code: this is definitely a bit artificial in some places just to demonstrate use:
// makeClass - By Hubert Kauker (MIT Licensed)
// original by John Resig (MIT Licensed).
function makeClass() {
var isInternal;
return function (args) {
if (this instanceof arguments.callee) {
if (typeof this.init == "function") {
this.init.apply(this, isInternal ? args : arguments);
}
} else {
isInternal = true;
var instance = new arguments.callee(arguments);
isInternal = false;
return instance;
}
};
}
var SeatGroup = makeClass(); //create our class
//the method that gets called on creation instance object of class
SeatGroup.prototype.init = function (id, changeType, name, desk, seat, setToValue, previousseat, previousseatnewvalue) {
// a default value
var defaultSeat = "default";
var defaultName = "default";
this.ID = id;
this.ChangeType = changeType;
this.Name = name ? name : defaultName;
this.Desk = desk ? desk : "";
this.Seat = seat ? seat : privateFunction(defaultSeat);;
this.SetTo = setToValue ? setToValue : this.ID;
this.PreviousSeatValue = previousseat ? previousseat : "";
this.PreviousSeatNewValue = previousseatnewvalue ? previousseatnewvalue : "";
this.changeObject = {};
// public method
this.SetChangeObject = function () {
this.changeObject.ID = this.ID;
this.changeObject.ChangeType = this.ChangeType;
this.changeObject.Name = this.Name;
this.changeObject.Seat = this.Seat;
this.changeObject.Desk = this.Desk;
this.changeObject.SetTo = this.SetTo;
this.changeObject.PreviousSeatValue = this.PreviousSeatValue;
this.changeObject.PreviousSeatNewValue = this.PreviousSeatNewValue;
};
function privateFunction(name) {
return name + "Seat";
}
};
var userMoves = [];//global warning-global object!!
//event handlers
$('.myAddButton').on('click', addDeskId);
$('.myRemButton').on('click', remDeskId);
$('#ShowResults').on('click', function () {
console.log(JSON.stringify(userMoves));//log this after all are pushed
});
//function called with the "add" that can be customized
function addDeskId(e) {
var uo = $(this);//jQuery of the "myAddButton" element
var userObjectChange = 'CHANGE_SEAT_TO';
var userObjectID = uo.data('info');
var userObjectDeskID = uo.data('id');
var userObjectSeatID = '9-4';
// create a private instance of our class (calls init function)
var uChange = SeatGroup(userObjectID, userObjectChange, userObjectDeskID, userObjectSeatID);
uChange.SetChangeObject();//call public function
//log what we created
console.dir(uChange.changeObject);
//does not work, its private: console.log( uChange.privateFunction('hi'));
// push to our global
userMoves.push(uChange.changeObject);
}
// event function, customize as needed
function remDeskId() {
var userObject = $(this);
var userObjectChange = 'REMOVESEAT';
var userObjectID = userObject.data('info');//use jQuery data, easier/better
var userObjectDeskID = userObject.data('id');
var userObjectDeskIDVal = 0;
var remUserObject = SeatGroup(userObjectID, userObjectChange, userObjectDeskID);
remUserObject.PreviousSeatValue = "FreddySeat";//show how we set a properly of our object
remUserObject.SetChangeObject();//call public function
console.dir(remUserObject.changeObject);
userMoves.push(remUserObject.changeObject);
}
Play around with it here: http://jsfiddle.net/q43cp0vd/1/
I have a card game, and cards are represented by Javascript objects that are created as instances of class (card > card-type > card-instance). I did it like this so that the cards can share methods.
Then I construct the HTML, and the cards suppose to be able to do all kinds of stuff, like move or attack for example.
move is defined in Card.prototype.move = function... and attack is UnitCard.prototype.attack
and now I am trying to connect the Card objects to their corresponding HTML elements, so that I will be able to so something like
$('#board').on('click', '.card', function (e) {
this.move(this.location, newLocation);
});
An idea I had is to make all the data and functions of the cards part of the DOM, and insert an object somewhere along the prototype chain of the DOM elements, so that the HTML of that card will have a move function. I know this idea is a bit crazy, but I am trying to avoid constant lookups inside objects (find the clicked card by name in the array of all cards and then if other cards that have influence on the action find them in the dom and then find them in the object etc...)
Any suggestions on how to solve this issue?
UPDATE - Current Code:
var Card = function (type, name, epoch) {
var cardHtml = document.createElement('div');
cardHtml.className += "card";
cardHtml.id = name;
cardHtml.cardType = type;
cardHtml.cardName = name;
cardHtml.cardEpoch = epoch;
this.cardHtml = cardHtml;
}
var Agent = function (cardProps, subtype, description, strike, shield, price) {
//fixed
Card.apply(this, cardProps);
this.subtype = subtype;
this.price = price; //agenda
//changable
this.cardHtml.innerHTML = ss.tmpl['cards-agent'].render({
name: this.name,
});
this.cardHtml.strike = strike;
this.cardHtml.shield = shield;
this.cardHtml.location = []; //board/hand/deck/grveyard
}
Agent.prototype = Object.create(Card.prototype);
Agent.prototype.move = function (currentLocation, newLocarion) {
console.log('move');
}
Store a reference to the instance on the element's data object.
var Card = function (type, name, epoch) {
var cardHtml = document.createElement('div');
cardHtml.className += "card";
cardHtml.id = name;
cardHtml.cardType = type;
cardHtml.cardName = name;
cardHtml.cardEpoch = epoch;
this.cardHtml = cardHtml;
$(cardHtml).data("card",this);
}
Now you can access it within events as needed.
$('#board').on('click', '.card', function (e) {
var card = $(this).data('card');
card.move(card.location, newLocation);
});
This of course assumes you can use jquery, per the jquery you're using in your question.
I can think of two additional options.
You could use bind to create a click handler in which this is actually your object instead of the dom element.
el.onclick = (function(){/* ... */}).bind(yourObj);
In this case, within your function, this would be your object instead of the dom element. As long as your object stores a reference to the dom element itelf, then you're set.
Another option would be to define the click handler within a closure which has a variable containing the object.
function bindHanlder(yourObj, el){
el.onclick = function(){
// "yourObj" can be used here.
};
}
I assume that your board has specific places where your cards can be placed.
You should have a Board object containing an array of Places, something like:
function Card(divId){
this.divId = divId;
//generate Card html elements with jquery
}
function Place(divId){
var currentCard = null;
//attach this javascript object to an html element
this.divId = divId;
//register events of this Place where this Place has this.divId
/*
$(document).on("click", this.divId, function(){
});
*/
this.setCard = function(card){
currentCard = card;
//use jquery to add Card html elements to this Place html element
}
}
function Board(){
var places= new Array();
this.addPlace = function(place){
places.push(place);
}
this.moveCard = function(card, toPlace){
toPlace.setCard(card);
}
}
var card1 = new Card("#divCard1");
var card2 = new Card("#divCard2");
var place1 = new Place("#divPlace1");
var place2 = new Place("#divPlace2");
var board = new Board();
board.addPlace(place1);
board.addPlace(place2);
board.moveCards(card1,place1);
This is really off the top of my head. I don't even know if it runs or not. It's just to give you an idea. Interpret it as pseudo code.
Good luck!
I'm just trying to structure my Javascript better and wondering how to incorporate window.onresize into the returned object, like so:
var baseline = function(){
var tall, newHeight, target, imgl, cur, images = [];
return {
init: function(selector, target){
this.images = document.querySelectorAll(selector);
this.target = target;
this.setbase(this.images);
window.onresize = this.setbase(this.images);
},
setbase: function(imgs){
this.imgl = imgs.length;
if(this.imgl !== 0){
while(this.imgl--){
this.cur = imgs[this.imgl];
this.cur.removeAttribute("style");
this.tall = this.cur.offsetHeight;
this.newHeight = Math.floor(this.tall / this.target) * this.target;
this.cur.style.maxHeight = this.newHeight + 'px';
}
} else {
return false;
}
}
}
}();
Is this the way that people would do it, is this going to work? Thanks
EDIT:
Invoked like so:
window.onload = function(){
baseline.init('img', '24');
};
I would like it so that when the window is resized, baseline.init is called with the same params as the initial init function call...
Here's the main error
init: function(selector, target){
this.images = document.querySelectorAll(selector);
this.target = target;
this.setbase(this.images);
// This line says call setbase now and assign the result of that
// as the onresize handler
window.onresize = this.setbase(this.images);
},
Your this.images does not point to the var images = [] you've created. This is for when you're using protoype style objects. You should just use images in your functions.
Some of your variables look like they're only used in setBase, they should be local
Looking at your object, it's very hard to tell what it's supposed to do, sounds like you're wrapping code in an object just for the sake of wrapping it into an object. What does baseline mean?
Here's a better version of your code, you should read and understand http://www.joezimjs.com/javascript/javascript-closures-and-the-module-pattern/ and http://js-bits.blogspot.com/2010/08/javascript-inheritance-done-right.html so you can decide what pattern you want to use and how they actually work. You are mixing both patterns, even though you didn't intend to. The trick is that with the way you're writing it (module pattern) there's no need to use this in the code, they're actually local variables held be the module
var baseline = function(){
// Don't use "this.tall", just "tall" gets you the variable
// Class variables, are you sure you need them throughout the class
var tall, newHeight, target, imgl, cur, images = [];
// Different name for the parameter so it doesn't get confused with
// the class variables
function init(selector, pTarget) {
images = document.querySelectorAll(selector);
target = pTarget;
setBase();
// Since we're not using this, you
// can just reference the function itself
window.onresize = setBase
}
// Most JS developers name methods using camelCase
function setBase() {
imgl = imgs.length;
if(imgl !== 0){
while(imgl--){
cur = imgs[imgl];
cur.removeAttribute("style");
tall = cur.offsetHeight;
newHeight = Math.floor(tall / target) * target;
cur.style.maxHeight = newHeight + 'px';
}
// should you return true here? what does returning
// something even mean here?
} else {
return false;
}
}
// Return just the public interface
return {
init: init
setBase: setBase
};
}();