Here's another version I got by instructing ChatGPT, in case you're interested. It's not perfect but it would provide a starting point so you can tell what you need changed. It works when the page has an element in the form of <span class="percentage-calculator"></span> to host the calculator inside.
(function createPercentageCalculator() {
// Function to calculate percentage difference
function calculatePercentageDifference(value1, value2) {
var num1 = parseFloat(value1);
var num2 = parseFloat(value2);
if (isNaN(num1) || isNaN(num2) || num2 === 0) {
return '0.00%';
}
var difference = Math.abs((num1 - num2) / ((num1 + num2) / 2)) * 100;
return difference.toFixed(2) + '%';
}
// Create input fields and output element
var container = document.querySelector('.percentage-calculator');
if (!container) return;
var input1 = document.createElement('input');
input1.type = 'number';
input1.placeholder = 'Enter first number';
var input2 = document.createElement('input');
input2.type = 'number';
input2.placeholder = 'Enter second number';
var output = document.createElement('div');
output.innerText = '0.00%';
// Append elements to the container
container.appendChild(input1);
container.appendChild(input2);
container.appendChild(output);
// Update output when input changes
function updateOutput() {
output.innerText = calculatePercentageDifference(input1.value, input2.value);
}
input1.addEventListener('input', updateOutput);
input2.addEventListener('input', updateOutput);
})();