SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Addict
    Join Date
    Dec 2010
    Posts
    221
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    One element, multiple events

    In jQuery you can easily do it like this:

    Code:
    $("#foo").focus(function () {
        // Do this.
    }).blur(function () {
        // Do that.
    });
    Can we do something similar in JavaScript so we don't have to repeat #foo in two separate functions?

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,696
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by Rain Lover View Post
    Can we do something similar in JavaScript so we don't have to repeat #foo in two separate functions?
    Yes, if the function is designed that way.

    For example:

    Code javascript:
    function Helper() {
        var helper = this;
     
        return function (selector) {
            console.log(selector);
            return helper;
        };
    };
    var helper = new Helper();
     
    Helper.prototype.blur = function () {
        console.log('blur');
        return this;
    }
    Helper.prototype.focus = function () {
        console.log('focus');
        return this;
    }
     
    helper('#foo').focus().blur();
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  3. #3
    SitePoint Addict
    Join Date
    Dec 2010
    Posts
    221
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by paul_wilkins View Post
    Yes, if the function is designed that way.

    For example:

    Code javascript:
    function Helper() {
        var helper = this;
     
        return function (selector) {
            console.log(selector);
            return helper;
        };
    };
    var helper = new Helper();
     
    Helper.prototype.blur = function () {
        console.log('blur');
        return this;
    }
    Helper.prototype.focus = function () {
        console.log('focus');
        return this;
    }
     
    helper('#foo').focus().blur();
    Thanks for the sample code, but it seems that using two separate functions for #foo is easier than a helper.


Bookmarks

Posting Permissions

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