1

I created a page on which there's a red square that can be moved by a mouse. I would like to find out how I can reuse Javascript to have more than 1 square. In the following fiddle http://jsfiddle.net/sbel/utM5k/ I show that in HTML on top I include the CSS, the square is a div and the Javascript has the form (function(window) {...})(window);. How can I change the Javascript to be able to simply say here is the ID of a div, apply the moving functionality to it?

1
  • Note also that it's typical to wait for a few answers, assess their usefulness (usually considering votes from the community), and finally accept the "correct" answer after a few days have passed. This strategy typically allows for better answers since many people do not view answered questions assuming they are complete =) Commented Jan 17, 2012 at 23:58

1 Answer 1

1

Rather than wrapping your functionality (variables and functions) in an anonymous closure (which is a good idea to avoid cluttering the global namespace), instead wrap them in a "class" definition so you can create multiple instances of your new type.

For example (not tested):

function MovableItem(id) {
  this.element = document.getElementById(id);
  this.mouseIsDownOnMovable = false;
  this.layerX = 0;
  this.layerY = 0;
  this.movableHeight = this.element.getBoundingClientRect().height;
  this.movableWidth = this.element.getBoundingClientRect().width;
  // And so on for each "member" variable...
}

MovableItem.prototype.markThatMouseIsDownOnMovable = function(event) {
  this.mouseIsDownOnMovable = true;
  this.layerX = event.layerX;
  this.layerY = event.layerY;
}

MovableItem.prototype.markThatMouseIsUp = function() {
  this.mouseIsDownOnMovable = false;
}

// And so on for each "method"...

This refactoring will take some time as you will be learning some new concepts (especially regarding the use of the "this" variable) but when complete you will be able to have any number of your movable objects as such:

var o1 = new MovableItem('slavaMovable');
var o2 = new MovableItem('slavaMovable2');
// ...

This is the general way to achieve object oriented reusability in JavaScript (though the implementation specifics may vary greatly depending on your ideological preferences).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.