skip to Main Content

Sorry if I’m missing something (i’m a beginner in JS). I am looking to use the PrintThis.js JQuery plugin to add a print button to any div with the “printdiv” class. I am using Jquery to number off the buttons and div classes and append the needed JQuery code to the script tag at the bottom of the page.

Here is a codepen I made with the code I am using. https://codepen.io/hinte019/pen/yEybmG?editors=1010

Here is it also in code form

<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="printthis/printThis.js"></script>
    </head>
    <body>
        <div class="printdiv"><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rem voluptatibus, magni, alias eaque dolor quisquam placeat, similique atque ratione fugiat impedit nam numquam accusantium. Deserunt reiciendis nulla omnis necessitatibus, quo.</p></div>
        <div class="printdiv"><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sit labore commodi, magnam corrupti dignissimos hic soluta. Distinctio quod saepe, tempora inventore ipsum, eligendi, dignissimos, eos recusandae perspiciatis odit consequuntur! Optio.</p></div>
        <div class="printdiv"><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptate distinctio fugiat earum, quibusdam soluta ipsa voluptas porro nostrum cupiditate vel modi nesciunt sint rem, vitae id exercitationem debitis, saepe eius?</p></div>
        <script>
        $(function () {
            // print divs
            var i = 1;
            $("body script").append('$(document).ready(function () {');
            $('.printdiv').each(function(){
                $(this).removeClass('printdiv').addClass('printdiv'+i);
                $('.printdiv'+i).prepend('<button type="button'+i + '" class="btn btn-primary printbutton' +i + '">Print</button>');
                var printcode = 'rn        $('.printbutton'+i + '').click(function () {rn            $('.printdiv'+i + '').printThis();rn        });';
                $("body script").append(printcode);
                i++;
            });
            $("body script").append('rn});');
        });
        </script>
    </body>
</html>

This results in printing

$(document).ready(function () {
    $('.printbutton1').click(function () {
        $('.printdiv1').printThis();
    });
    $('.printbutton2').click(function () {
        $('.printdiv2').printThis();
    });
    $('.printbutton3').click(function () {
        $('.printdiv3').printThis();
    });
});

The resulting code should be right, but the print buttons do not work 🙁

2

Answers


  1. The problem is that the script in the body, in which you append your code, has already been parsed/processed by the js engine so you cannot alter its contents.

    You should create an in-memory script and after you fill it then append it to the DOM.

    $(function() {
      // print divs
      var i = 1;
      var script = $('<script>');
      script.append("$(document).ready(function () {");
      $(".printdiv").each(function() {
        $(this)
          .removeClass("printdiv")
          .addClass("printdiv" + i);
        $(".printdiv" + i).prepend(
          '<button type="button' +
            i +
            '" class="btn btn-primary printbutton' +
            i +
            '">Print</button>'
        );
        var printcode =
          "rn        $('.printbutton" +
          i +
          "').on('click', function () {rn            $('.printdiv" +
          i +
          "').printThis();rn        });";
        script.append(printcode);
        i++;
      });
      script.append("rn});");
      script.appendTo('body');
    });
    
    Login or Signup to reply.
  2. An easier way to accomplish what you want:

    Change to html (including print button in the source code):

    <div class="printdiv">
        <p>Lorem ipsum dolor sit amet</p>
        <button class="btn btn-primary printbutton">Print</button>
    </div>
    <div class="printdiv">
        <p>consectetur adipisicing elit</p>
        <button class="btn btn-primary printbutton">Print</button>
    </div>
    <div class="printdiv">
        <p>vitae id exercitationem debitis</p>
        <button class="btn btn-primary printbutton">Print</button>
    </div>
    

    jQuery:

    $('.printButton').on('click', function(){
        var $parent = $(this).parent('.printdiv');
        $parent.printThis();
    });
    

    This jQuery says on click of a button, find that button‘s parent div matching the class printDiv and passes that as the selector for printThis.

    Additionally, I would suggest moving all javascript/jQuery out of the page an into it’s own file.

    So you would have:

    <script src="path/to/jQuery"></script>
    <script src="path/to/printThis"></script>
    <script src="path/to/your/custom/javascript"></script>
    

    Important note:

    • Appending <script> dynamically is typically not necessary, and is a very roundabout klunky way of affecting the DOM.
    • Use $.on('click',... instead of $.click. For $.click a separate handler gets created for every single element that matches the selector and only works for elements already in the DOM (hence your problem in your initial code). $.on works for dynamically added elements
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search