Created
March 7, 2025 09:48
-
-
Save dgwyer/c1284aa06c38bf47884a22e38ba02d69 to your computer and use it in GitHub Desktop.
FastHTML Context Menu
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from fasthtml.common import * | |
app,rt = fast_app(live=True) | |
@rt("/") | |
def get(): | |
menu_css = Style(""" | |
.context-menu { | |
display: none; | |
position: absolute; | |
background-color: #fff; | |
border: 1px solid #ccc; | |
box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.2); | |
z-index: 1000; | |
} | |
.context-menu ul { | |
list-style: none; | |
margin: 0; | |
padding: 0; | |
} | |
.context-menu li { | |
padding: 8px 12px; | |
cursor: pointer; | |
list-style-type: none; | |
} | |
.context-menu li:hover { | |
background-color: #f0f0f0; | |
} | |
h1 { font-size: 3em; } | |
p { font-size: 1.5em; } | |
""") | |
menu_js = Script(""" | |
document.addEventListener('contextmenu', function(event) { | |
event.preventDefault(); | |
const contextMenu = document.getElementById('custom-context-menu'); | |
// Position the menu at the mouse position | |
contextMenu.style.left = event.pageX + 'px'; | |
contextMenu.style.top = event.pageY + 'px'; | |
// Show the menu | |
contextMenu.style.display = 'block'; | |
}); | |
// Hide the menu when clicking elsewhere | |
document.addEventListener('click', function() { | |
const contextMenu = document.getElementById('custom-context-menu'); | |
contextMenu.style.display = 'none'; | |
}); | |
// Add event listeners to menu options | |
document.getElementById('option1').addEventListener('click', function() { | |
document.querySelector('h1').style.color = 'red'; | |
}); | |
document.getElementById('option2').addEventListener('click', function() { | |
document.querySelector('h1').style.color = 'blue'; | |
}); | |
document.getElementById('option3').addEventListener('click', function() { | |
document.querySelector('h1').style.color = 'green'; | |
}); | |
""") | |
# HTML for the context menu (unchanged) | |
context_menu = Div( | |
Ul( | |
Li("Red", id="option1"), | |
Li("Blue", id="option2"), | |
Li("Green", id="option3") | |
), | |
id="custom-context-menu", cls="context-menu" | |
) | |
# Main content | |
content = Div( | |
P("Right-click anywhere on this page to see the context menu."), | |
context_menu, | |
menu_css, | |
menu_js | |
) | |
return Titled("Context Menu Demo", content) | |
serve() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment