0

I have a function that accepts the element as a parameter, this element will used to perform operations inside function.

function center(element) {
   // code to align this given element to center position
   element.css("position","fixed");
   element.css("top", Math.max(0, ((window.innerHeight - element[0].offsetHeight) / 2))+ "px");
   element.css("left", Math.max(0, ((window.innerWidth - element[0].offsetWidth) / 2))+ "px");
   return element;
}

// calling above function
center(element);

Here element is passed as parameter. But I don't want to do that. Is it possible to create a function which will be called on element? Example

element.center();

You can also consider jQuery functions like: $(element).next(); etc.

Note I don't want to use jQuery. I need pure javascript coding.

By using jQuery it can be possible by creating below

center function

jQuery.fn.center = function () {
   this.css("position","absolute");
   this.css("top", Math.max(0, (($(window).height() - this.height()) / 2)   + $(window).scrollTop())+ "px");
   this.css("left", Math.max(0, (($(window).width() - this.width()) / 2) + $(window).scrollLeft())+ "px");
   return this;
};

2 Answers 2

5

You can add a function to the prototype of the Node object:

Node.prototype.center = function() {
    // code to align this given element to center position
    this.css("position","fixed");
    this.css("top", Math.max(0, ((window.innerHeight - element[0].offsetHeight) / 2))+ "px");
    this.css("left", Math.max(0, ((window.innerWidth - element[0].offsetWidth) / 2))+ "px");
    return this;
}

This will allow you to call .center() on any node.

Note: When defining prototype functions, this is the object (in this case a Node) on which the function is called.

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

Comments

0

By adding a prototype named center to your element object, you will be able to call the center method on element.

References

Prototypes in Javascript: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype

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.