Open skanda-vasishta opened 2 weeks ago
const svg = document.querySelector('#svg1 svg');
// Get the SVG's viewBox
const viewBox = svg.viewBox.baseVal;
// Create a group element to hold our button
const g = document.createElementNS("http://www.w3.org/2000/svg", "g");
// Create a rect element for the button background
const rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
rect.setAttribute("width", "60");
rect.setAttribute("height", "20");
rect.setAttribute("fill", "#007bff");
rect.setAttribute("rx", "5");
// Create a text element for the button label
const text = document.createElementNS("http://www.w3.org/2000/svg", "text");
text.textContent = "Click";
text.setAttribute("fill", "white");
text.setAttribute("font-size", "12");
text.setAttribute("text-anchor", "middle");
text.setAttribute("dominant-baseline", "middle");
text.setAttribute("x", "30");
text.setAttribute("y", "10");
// Add rect and text to the group
g.appendChild(rect);
g.appendChild(text);
// Position the button in the top right corner
g.setAttribute("transform", `translate(${viewBox.width - 70}, 10)`);
// Add click event listener
g.addEventListener('click', () => {
console.log('Button clicked!');
// Add your desired functionality here
});
// Add the group to the SVG
svg.appendChild(g);
// Create a new group for the toggle
const toggleGroup = document.createElementNS("http://www.w3.org/2000/svg", "g");
// Create a rect element for the toggle background
const toggleRect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
toggleRect.setAttribute("width", "60");
toggleRect.setAttribute("height", "20");
toggleRect.setAttribute("fill", "#28a745");
toggleRect.setAttribute("rx", "5");
// Create a text element for the toggle label
const toggleText = document.createElementNS("http://www.w3.org/2000/svg", "text");
toggleText.textContent = "ON";
toggleText.setAttribute("fill", "white");
toggleText.setAttribute("font-size", "12");
toggleText.setAttribute("text-anchor", "middle");
toggleText.setAttribute("dominant-baseline", "middle");
toggleText.setAttribute("x", "30");
toggleText.setAttribute("y", "10");
// Add rect and text to the toggle group
toggleGroup.appendChild(toggleRect);
toggleGroup.appendChild(toggleText);
// Position the toggle below the button
toggleGroup.setAttribute("transform", `translate(${viewBox.width - 70}, 40)`);
// Add click event listener for toggle functionality
let isOn = true;
toggleGroup.addEventListener('click', () => {
isOn = !isOn;
if (isOn) {
toggleText.textContent = "ON";
toggleRect.setAttribute("fill", "#28a745");
} else {
toggleText.textContent = "OFF";
toggleRect.setAttribute("fill", "#dc3545");
}
console.log(`Toggle is now ${isOn ? 'ON' : 'OFF'}`);
});
// Add the toggle group to the SVG
svg.appendChild(toggleGroup);