rx65m
rx65m

Reputation: 105

How to toggle a specific JavaScript function with a click?

We need to disable and re-enable with a click, a function which shows us the amount of characters within plenty of < pre >.

The function we use is this:

<script type="text/javascript">
$(window).load(function(){
    $(document).ready(function(){
    $('pre').each(function(i){
        var iCharacters = $(this).text().length;
            $(this).prepend("<b style='color:red'>" + iCharacters + " </b>");
        });
    });
});
</script>

Thanks a lot for your help in advance.

Upvotes: 0

Views: 111

Answers (1)

Joel Lord
Joel Lord

Reputation: 2173

I believe an easy way to do this would be to always display the numbers but they hide or show them on the click of a button using jQuery's toggle method. You can find a working example here: https://jsbin.com/pohagaz/1/edit?html,js,output.

$("pre").each(function(i){
  var iCharacters = $(this).text().length;
  $(this).prepend("<b class='charCount' style='color:red'>" + iCharacters + " </b>");
});

$("#showCounts").click(function() {
  $(".charCount").toggle();
});

Upvotes: 2

Related Questions