megler
megler

Reputation: 216

putting multiple functions under 1 main function

I'm using this line of code quite a bit:

.hide().insertBefore("#placeholder").fadeIn(1000);

Is there a way to make this a function or variable (pretty sure can't use a var, but thought I'd ask) so I can call it as needed? I know I could just copy/paste, but it clutters up the code to see that over and over.

I tried:

function properDisplay() {
    .hide().insertBefore("#placeholder").fadeIn(1000);
}

But that doesn't work.

Upvotes: 3

Views: 101

Answers (4)

Guffa
Guffa

Reputation: 700512

You can make it a plugin:

$.fn.properDisplay = function(){
  return this.hide().insertBefore("#placeholder").fadeIn(1000);
};

Usage:

$('#SomeElement').properDisplay();

Upvotes: 4

Pointy
Pointy

Reputation: 413808

You can also make it into a jQuery plugin:

$.fn.properDisplay = function(whereToInsert, delay) {
  if (delay === undefined) delay = 1000;
  return this.hide().insertBefore(whereToInsert).fadeIn(delay);
});

Then:

$(".something").properDisplay("#placeholder");

In a plugin, this is a reference to a jQuery object, not a DOM element. It's conventional for plugins to return the jQuery object so that the function can be chained as is typical practice.

Upvotes: 0

user5393970
user5393970

Reputation:

function properDisplay(param) {
    $(param).hide().insertBefore("#placeholder").fadeIn(1000);
}

and then just simply call it like this:

properDisplay(this);

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115242

You need to pass the element object as parameter

function properDisplay(ele) {
   $(ele).hide().insertBefore("#placeholder").fadeIn(1000);
}

Upvotes: 3

Related Questions