To create an HTML page with a button that adds a new div with the button's text and a QR code inside, you need to write HTML, CSS, and JavaScript. For the QR code, we can use a JavaScript library like qrcode.js that you can include in your project. Below is an example of how you can achieve this:
First, make sure you have the qrcode.js script included in your project. You can download the library from https://davidshimjs.github.io/qrcodejs/ or link directly to the library hosted on a CDN:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>QR Code Generator</title>
<script src="https://cdn.jsdelivr.net/gh/davidshimjs/qrcodejs/qrcode.min.js"></script>
<style>
.new-div {
width: 300px;
height: 150px;
border: 1px solid #000;
margin-top: 10px;
position: relative;
padding: 10px;
box-sizing: border-box;
}
.qr-code {
position: absolute;
bottom: 10px;
right: 10px;
}
.div-content {
font-size: 16px;
margin-bottom: 10px;
}
</style>
</head>
<body>
<button id="generateDiv">Generate Div with QR Code</button>
<script>
document.getElementById('generateDiv').addEventListener('click', function() {
// Create new div
var newDiv = document.createElement('div');
newDiv.className = 'new-div';
// Set content of new div
var divContent = document.createElement('div');
divContent.className = 'div-content';
divContent.innerText = 'Button Text';
newDiv.appendChild(divContent);
// Create container for QR code
var qrCodeContainer = document.createElement('div');
qrCodeContainer.className = 'qr-code';
newDiv.appendChild(qrCodeContainer);
// Append the new div to body
document.body.appendChild(newDiv);
// Generate QR code
new QRCode(qrCodeContainer, {
text: 'Button Text',
width: 128,
height: 128,
colorDark : "#000000",
colorLight : "#ffffff",
correctLevel : QRCode.CorrectLevel.H
});
});
</script>
</body>
</html>
How this code works:
- It includes the
qrcode.js library to generate QR codes.
- It defines a button with the ID of
generateDiv.
- It includes some basic styles to ensure the new div and QR code look as desired.
- It adds an event listener to the button that creates a new div with the button text and a new QR code each time it's clicked.
- It uses the
QRCode constructor to generate the QR code within the newly created div.
- The new div, along with its content and the QR code, is appended to the page.
Make sure to replace 'Button Text' with the actual text you want to display in the div and QR code if needed. You can modify the width and height options passed to the QRCode constructor to fit the QR code within the 150px height constraint of the new-div.