JavaScript onshow Event: Context Menu Displayed

The onshow event in JavaScript is triggered when a context menu is about to be displayed. This event is very useful for customizing the behavior of context menus or performing actions before the menu is visible to the user. Understanding and using the onshow event can greatly enhance the interactivity and customizability of your web applications. This article will provide a detailed explanation of the onshow event, its syntax, practical examples, and common use cases.

What is the onshow Event?

The onshow event is an event handler that occurs just before a context menu is displayed. Context menus, usually accessed via a right-click or similar action, provide users with a list of options related to a particular element or area of a web page. The onshow event provides a moment to execute JavaScript code before the context menu appears, which can allow you to dynamically modify its options, gather relevant data, or even prevent the menu from being shown altogether.

Purpose of the onshow Event

The main purpose of the onshow event is to allow developers to:

  • Customize Context Menu Options: Modify the context menu items dynamically based on the clicked element or its context.
  • Perform Actions Before Display: Execute specific actions, such as logging, gathering data, or setting variables, just before the menu is shown.
  • Prevent Context Menus: Conditionally prevent the context menu from displaying under certain circumstances.
  • Enhance Interactivity: Make context menus more interactive by adapting them to the current state of the application.

Syntax of the onshow Event

The onshow event can be used in two main ways:

  1. HTML Attribute: Directly in the HTML tag using the onshow attribute.
    html

    ยจK19K

  2. JavaScript Property: By assigning a function to the onshow property of a DOM element in JavaScript.
    javascript
    element.onshow = function() { yourFunction(); };

Important Notes

  • The onshow event only works on <menu> elements and is triggered only when the menu is shown through the show() method in JavaScript or via a context menu.
  • Ensure that the element or the menu to which the event is attached, is the one where you are triggering the context menu.
  • Using the event object in the handler can provide information about the event, such as the target element where the context menu was triggered.

Practical Examples

Let’s explore practical examples to illustrate how the onshow event works.

Example 1: Basic Usage with HTML Attribute

In this example, we will display an alert message when a context menu is about to be displayed using the onshow attribute directly in the HTML.

<menu id="myContextMenu1" type="context">
    <menuitem>Item 1</menuitem>
    <menuitem>Item 2</menuitem>
</menu>

<div id="contextArea1" style="width:200px; height:100px; border: 1px solid black;" contextmenu="myContextMenu1" oncontextmenu="event.preventDefault(); document.getElementById('myContextMenu1').show(event.clientX,event.clientY);">
    Right-click here
</div>

<script>
    const contextMenuDiv1 = document.getElementById('contextArea1');

    const contextmenu1 = document.getElementById('myContextMenu1');

        contextmenu1.onshow = function() {
            alert('Context menu is about to show.');
        }
</script>

When you right-click on the div element, before the context menu shows up, you will see the alert message.

Example 2: Using JavaScript Property

This example demonstrates how to use the onshow event by assigning a function to the onshow property of a DOM element in JavaScript.

<menu id="myContextMenu2" type="context">
    <menuitem>Item 1</menuitem>
    <menuitem>Item 2</menuitem>
</menu>

<div id="contextArea2" style="width:200px; height:100px; border: 1px solid black;" contextmenu="myContextMenu2" oncontextmenu="event.preventDefault(); document.getElementById('myContextMenu2').show(event.clientX,event.clientY);">
    Right-click here
</div>
<script>
    const contextMenuDiv2 = document.getElementById('contextArea2');
    const contextmenu2 = document.getElementById('myContextMenu2');


    contextmenu2.onshow = function(event) {
      console.log('Context menu is about to show.');
       console.log("Event Target: ", event.target);
    };
</script>

When you right-click on the div element, the message ‘Context menu is about to show.’ and the target element of the event will be logged to the console before the context menu appears.

Example 3: Modifying Context Menu Items

This example shows how to modify context menu items dynamically based on the element that was clicked.

<menu id="myContextMenu3" type="context">
    <menuitem id="item1">Item 1</menuitem>
    <menuitem id="item2">Item 2</menuitem>
</menu>

<div id="contextArea3a" style="width:200px; height:100px; border: 1px solid black;" contextmenu="myContextMenu3" oncontextmenu="event.preventDefault(); document.getElementById('myContextMenu3').show(event.clientX,event.clientY);">
    Right-click here (Area A)
</div>
<br>
<div id="contextArea3b" style="width:200px; height:100px; border: 1px solid black;" contextmenu="myContextMenu3" oncontextmenu="event.preventDefault(); document.getElementById('myContextMenu3').show(event.clientX,event.clientY);">
    Right-click here (Area B)
</div>
<script>
    const contextMenuDiv3a = document.getElementById('contextArea3a');
    const contextMenuDiv3b = document.getElementById('contextArea3b');
    const contextmenu3 = document.getElementById('myContextMenu3');

    contextmenu3.onshow = function(event) {
      const item1 = document.getElementById('item1');
      const item2 = document.getElementById('item2');

        if (event.target.id === 'contextArea3a') {
           item1.label = "Custom Item for A";
           item2.label = "Another Item for A";
        }else if (event.target.id === 'contextArea3b') {
            item1.label = "Custom Item for B";
            item2.label = "Another Item for B";
        }
    };
</script>

Right-clicking on “Area A” and “Area B” will show different labels on the context menu. The context menu gets modified dynamically based on which area the user right clicked.

Example 4: Preventing the Context Menu

In some cases, you may want to prevent the context menu from appearing based on certain conditions. This example shows how to use event.preventDefault() to stop the context menu from showing.

<menu id="myContextMenu4" type="context">
    <menuitem>Item 1</menuitem>
    <menuitem>Item 2</menuitem>
</menu>

<div id="contextArea4" style="width:200px; height:100px; border: 1px solid black;" contextmenu="myContextMenu4" oncontextmenu="event.preventDefault(); document.getElementById('myContextMenu4').show(event.clientX,event.clientY);">
    Right-click here
</div>
<script>
    const contextMenuDiv4 = document.getElementById('contextArea4');
    const contextmenu4 = document.getElementById('myContextMenu4');
    let preventMenu = true;

    contextmenu4.onshow = function(event) {
        if (preventMenu) {
          event.preventDefault();
        }else{
            console.log("Menu is being showed");
        }

    };

  contextMenuDiv4.addEventListener("click", function() {
    preventMenu = false;
    console.log("preventMenu:", preventMenu);
  });
</script>

Initially, the context menu won’t be shown when right-clicked on the div because of the preventMenu boolean being true. When you click once on the div then the value of preventMenu will be set to false and after that, when right clicked, you will see the context menu.

Real-World Use Cases

The onshow event is useful in various real-world scenarios:

  • Customizable Toolbars: Modify context menus based on user roles or permissions.
  • Enhanced Text Editors: Adjust menu options depending on the selected text or cursor position.
  • Interactive Visualizations: Offer different menu options for different elements in a chart or graph.
  • Context-Aware Applications: Dynamically change menu options based on the current application state.
  • Image Editing Tools: Display appropriate menu options for editing images.

Browser Support

The onshow event is supported by modern browsers.

Browser Support
Chrome Yes
Edge Yes
Firefox Yes
Safari Yes
Opera Yes

Conclusion

The onshow event is a powerful feature that allows you to control and customize context menus effectively in JavaScript. By using the onshow event, you can create more interactive and user-friendly web applications. Understanding and applying the techniques discussed in this article will help you leverage this event to its fullest potential.