'Javascript print function not working inside a modal

I want to print data from a pop-up modal on my website, so in the footer of the modal, I added a print button. (The extra divs at the end are from code above):

<div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
        <button type="button" id="btnSave" onclick="save()" class="btn btn-success">Save</button>
        <button id="btnPrint" type="button" class="btn btn-default">Print</button>
            
      </div>
    </div>
  </div>
</div>
<!-- End Bootstrap modal -->

<script src="<?php echo base_url('assets/image-picker/image-picker.js'); ?>"></script>
<link href="<?php echo base_url('assets/image-picker/image-picker.css'); ?>" rel="stylesheet" type="text/css">
<script type="text/javascript">

document.getElementById("btnPrint").onclick = function () {
    printElement(document.getElementById("printThis"));
}

function printElement(elem) {
    var domClone = elem.cloneNode(true);
    
    var $printSection = document.getElementById("printSection");
    
    if (!$printSection) {
        var $printSection = document.createElement("div");
        $printSection.id = "printSection";
        document.body.appendChild($printSection);
    }
    
    $printSection.innerHTML = "";
    $printSection.appendChild(domClone);
    window.print();
}

I have this in the beginning of my masters.css file:

@media screen {
  #printSection {
      display: none;
  }
}

@media print {
  body * {
    visibility:hidden;
  }
  #printSection, #printSection * {
    visibility:visible;
  }
  #printSection {
    position:absolute;
    left:0;
    top:0;
  }
}

</script>

Why isn't the print button working; when the print button is clicked, nothing happens. Should I add the javascript code in a different file like I did with the css?



Solution 1:[1]

try to put your script inside: document.addEventListener('DOMContentLoaded',function(){/*your code to run*/}) for vanila javascript or inside jquery ready function: $(document).ready(function(){/*your code to run*/ }).

this way you ensure that the script is executed after the content of your page is loaded.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ali Tenni