Results 1 to 4 of 4

Thread: Object method on button?

  1. #1
    Join Date
    Dec 2011

    Object method on button?

    I know it's easy to call a function to activate when you click an HTML button. Is it possible to have the same thing happen with an Objects method? Such as onclick="object.method();" And if so, what is the proper way to call it? Seems nothing I try works.

  2. #2
    Join Date
    Mar 2007
    The named instance of the object must exist at the time that it is installed. Can you give a full code example?
    Where used, return should be executed unconditionally and always as the last statement in the function.

    That's my signature, it's not part of the damn post!

  3. #3
    Join Date
    Oct 2012
    I know it's trouble-free to describe a meaning to make active when you clack an HTML key.

    **Links removed by Site Administrator so it doesn't look like you're spamming us. Please don't post them again.**

  4. #4
    Join Date
    Feb 2003
    Michigan, USA
    You need to bind the "this" variable to a different context, and assign the function object reference to the onclick.

    Function.prototype.bind is included in the newer versions of the ECMAScript specification, so you'll need this snippet below to support older browsers:
    if (!Function.prototype.bind) {
    	Function.prototype.bind = function(context) {
    		var self = this;
    		var fn = function() {
    			return self.apply(context, arguments);
    		fn.cleanup = function() {
    			self = fn = context = null;
    		return fn;
    And to use it:
    var myObject = {
      doSomething: function(event) {
        var button = event.target || event.srcElement;
        // do something with button
        // "this" points to myObject
        alert(this === myObject); // alerts "true"
    var element = document.getElementById("some_id");
    element.onclick = myObject.doSomething.bind(myObject);
    Perhaps a more traditional object oriented approach:
    function Foo(element) {
    	this.element = element;
    	this.element.onclick = this.handleClick.bind(this);
    Foo.prototype = {
    	element: null,
    	handleClick: function(event) {
    		var element = event.target || event.srcElement;
    	showButton: function(button) {
    		alert(button.nodeName + "#" + button.id);
    var foo = new Foo(document.getElementById("some_id"));

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center