"In JSFiddle, when you set the wrapping to "onLoad" or "onDomready", the functions you define are only defined inside that block, and cannot be accessed by outside event handlers."
Easiest fix is to change:
function something(...)
To:
window.something = function(...)
---Niet The Dark Absol
For your example, you want to define the onclick
method of a button. That's really easy with JavaScript, we just need to give the button an id
in the HTML, so that we can find it in our JavaScript code.
Change this:
<button class = "hidden-print" onclick = "printProducts()">Print Products</button>
To this:
<button id="myButton" class="hidden-print">Print Products</button>
Note that we no longer need the onclick="printProducts()"
part anymore.
Now we need to set the printProducts
function to run when the button is clicked. This can be done like so:
document.getElementById('myButton').onclick = printProducts;
Start edit
This code needs to be placed in the onload
function though, to properly run.
Do that like so:
window.onload = function() {
document.getElementById('myButton').onclick = printProducts;
}
End edit
And the printProducts
function remains the same.
Working JSFiddle
document.getElementById('myButton').onclick = printProducts;
function printProducts(){
window.print();
}
<button id="myButton" class="hidden-print">Print Products</button>