Function Declaration in jQuery

May 8, 2017
Frontend JavaScript

Three ways to declare functions in jQuery include the simple function, get/set, and extending the jQuery object. I cover all three in this short post.

The Simple Function

This is the simplest way to declare a function (method) in JavaScript and jQuery. This is a great way to test and is good for a throwaway method, but it isn’t good practice to code like this because it doesn’t encourage code recycling.

function sayHello(name) {
  alert("Hello, " + name);
}

Get/Set

This is a great way to get/set/delete model values. It’s very common and is not too far off from the simple method declaration.

//declaring
var sayHello = function(name) {
    return "Hello, " + name;
}
//using
console.log(sayHello("Jon")); // "Hello, Jon"

Create Your Own

Extending the jQuery object is a great way to abstract pieces of code that will be reused. It encourages developers to use method chaining, so this keeps your code clean, too!

jQuery.fn.extend({
  backwards: function() {
    var text = $(this).text();
    var backwardsText = '';
    var bits = text.split('');
    var x = text.length - 1;
    while (x >= 0) {
      backwardsText += bits[x];
      --x;
    }
    return backwardsText;
  }
})
$(document).ready(function() {
  console.log($("#testText").backwards());
  //given $("#testText") looks like <p id='testText'>racecar tacocat</p>
  //the result is => tacocat racecar
})

Here’s a CodePen that uses the above method (plus another one) to determine if an element’s text forms a palindrome:

See the Pen Extending the jQuery Object by Nate Northway (@the_Northway) on CodePen.

No Comments...yet

Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post

CodeIgniter Class Level Variables

From April 23, 2017

I’m always looking for ways to improve how we at Gittr write software. We’ve got a pretty good flow and class level variables helped move our app forward

Read This Article
Next Post

Regex Cheatsheet

From May 23, 2017

I’ve been writing some regex lately and compiled this handy little cheat sheet. Hopefully it helps you quickly write regex. I know I’ll be using it!

Read This Article