Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Chaining custom functions

I am wondering how to chain my custom functions and maintain context of 'this'.

Example:

$.fn.foo = function() {
  var html = '<div class="foo"></div>';
  if ($(this).hasClass(somthing) {
    $(this).prepend(html);
  }
}

$.fn.bar = function() {
  var html = '<h3>bar</h3>';
  $(this).find('.foo').prepend(html);
}

$('body').foo().bar();

When i try to use this code i get a TypeError: Cannot read property 'bar' of undefined

like image 640
Frederick M. Rogers Avatar asked Jun 23 '16 13:06

Frederick M. Rogers


1 Answers

You need to return current element context, i.e. this from you custom method.

$.fn.foo = function() {
  var html = '<div class="foo"></div>';
  if ($(this).hasClass('somthing')) {
    $(this).prepend(html);
  }
  return this; //The magic statement
}

$.fn.bar = function() {
  var html = '<h3>bar</h3>';
  $(this).find('.foo').prepend(html);
  return this; //The magic statement
}

$('body').addClass('somthing').foo().bar();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
like image 95
Satpal Avatar answered Oct 13 '22 23:10

Satpal