Argirco Popov Argirco Popov - 1 year ago 78
Javascript Question

Break jQuery method chain with plguin function

What I want to achieve is to build a plugin that do some validation logic on an element, but I want to go on with the next chain methods, but If its not okay, to stop and abort the next chains.

For example, I have this

;(function($, window, document, undefined) {
var pluginName = 'check';

$.fn[pluginName] = function(options) {
return this.each(function() {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName, new Plugin(this, options));

function Plugin(element, options) {
// Do the logic here
})(jQuery, window, document);

So in order to continue the chain after your callback you must return this, as I did in the plugin above.

jQuery( document ).ready( function($) {

button.check().on( 'click', function(){
// do something

But what If I want to execute click function only if the check function logic condition was met.

Answer Source

You can create a plain object having property descriptor writable set to false, assign object to $._data(this[0]).events within plugin to not permit writing "events" property at element $._data() object.

(function($) {
  $.fn.check = function() {
    const el = this;
    // if element `.tagName` is `"DIV"` do not set events
    if (el[0].tagName === "DIV") {
      let e = Object.defineProperty(Object.prototype, "events", {
        value: null,
        writable: false
      $._data(el[0]).events = e;
    return el
$(function() {
  $("div").check().on("click", function(e) {
    .on("mouseover", function(e) {
  console.log($._data($("div")[0], "events"))
<script src="">

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download