SearchForKnowledge
SearchForKnowledge

Reputation: 3751

Why is the js callback function giving an error

I have the following JS:

$(document).ready(function (e) {
    $(".pStyle").CapFirstWord();
});
function CapFirstWord() {
    $word = $(this);
    var k = $word.length;
    alert(k);
}

HTML:

<p class="pStyle">Of all of these "new" selectors, ::nth-letter is likely the most useful. For instance, Lettering.js wraps letters in for us so that we can select individual letters. This would be entirely unnecessary with ::nth-letter.</p>

I am trying to create a callback function which can be called from other pages to display the length of a given class/id.

How can I achieve that.

Upvotes: 2

Views: 93

Answers (3)

James Donnelly
James Donnelly

Reputation: 128791

If you want to be able to chain your function after a jQuery selector you can extend the default functionality of jQuery using its $.fn.extend() method:

$.fn.extend({
    CapFirstWord: function() {
        $word = $(this);
        var k = $word.length;
        alert(k);
    }
});

The jQuery.fn.extend() method extends the jQuery prototype ($.fn) object to provide new methods that can be chained to the jQuery() function.

Then you can call $(".pStyle").CapFirstWord();.

Demo

$.fn.extend({
    CapFirstWord: function() {
        $word = $(this);
        var k = $word.length;
        alert(k);
    }
});

$(document).ready(function (e) {
    $(".pStyle").CapFirstWord();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class="pStyle">Of all of these "new" selectors, ::nth-letter is likely the most useful. For instance, Lettering.js wraps letters in for us so that we can select individual letters. This would be entirely unnecessary with ::nth-letter.</p>

Upvotes: 6

Francisco Goldenstein
Francisco Goldenstein

Reputation: 13767

jQuery object doesn't have a function called CapFirstWord, that's why it fails. You should call that function passing the jQuery object as argument. Something like this:

$(document).ready(function (e) {
       CapFirstWord($(".pStyle"));
});
function CapFirstWord(tag) {
    var k = tag.length;
    alert(k);
}

Upvotes: 2

Richard Parnaby-King
Richard Parnaby-King

Reputation: 14862

You are calling the function wrong. You have attempted to chain a regular function to a jquery object.

$(document).ready(function (e) {
    CapFirstWord($(".pStyle"));
});

Here I have added a parameter to the function, the element that is being passed by the above script:

function CapFirstWord($word) {

And finally, to get the length of the string, I am calling .text() on the element:

    var k = $word.text().length;

Final solution:

$(document).ready(function (e) {
    CapFirstWord($(".pStyle"));
});

function CapFirstWord($word) {
    var k = $word.text().length;
    alert(k);
}

Upvotes: 2

Related Questions