1

I have the following bit of jQuery code that i want to reuse by calling it from other parts of my jQuery code. How would i do that?

$(document).ready(function() {              
    $('#share_mention').charcount({
        maxLength: 140,
        preventOverage: false
    });

    $('.countable').bind('update', function(evt, length, remaining) {
        var message = 'id=' + $(evt.target).attr('id') + ', length=' + length + ', remaining=' + remaining;                 
    });
});

2 Answers 2

5

There are many ways to skin this cat but here is an approach.

var yourNameSpace = {};

yourNameSpace.YourFunction = function(){
   $('#share_mention').charcount({
   maxLength: 140,
   preventOverage: false
  });

  $('.countable').bind('update', function(evt, length, remaining) {
  var message = 'id=' + $(evt.target).attr('id') + ', length=' + length + ', remaining=' + remaining;                 
  });
}

$(document).ready(function() {   
  yourNameSpace.YourFunction()
});
Sign up to request clarification or add additional context in comments.

2 Comments

A slightly shorter way of writing that last line would be $(document).ready(yourNameSpace.YourFunction);
@JoeEnos Yes, provided that is the only thing you want to do upon DOM Ready is that function.
0

First things first there is no such thing as a jQuery function. It's a javascript function. The event is implicitly passed to the callback function.

function countCats (event) {}

$('.cats').on('click', countCats);

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.