How can the onclick event be activated by pressing the enter key with inline javascript?

[FYI: I am not permitted to alter the existing markup. The div will be clicked, not a button or anchor]

I have a menu that needs to comply with accessibility standards and open its submenu upon being clicked.

This onclick function needs to be triggered when the enter key is pressed as well,

 // parent menu (will repeat)        
    <div onclick="javascript:ToggleMenu('Calendar');" class="menu-item" style="cursor: hand;" tabindex="2">
        <p>Calendar</p>
        </div>

//submenu (will repeat)
            <div id="Calendar" class="menu-subitem" style="display: none;" tabindex="2">


            <a onclick="Audit(this)" tabindex="2" href="Calendar/CalendarAssignment.aspx" id="TM_C1">Calendar Assignment</a>
             <a onclick="Audit(this)" tabindex="2" href="Calendar/ShiftAssignment.aspx" id="TM_C2">Shift Assignment</a>
            </div>

Thanks! I have done my best to explain clearly!

Answer №1

Here is a solution that focuses on accessibility while utilizing a div:

<div id="foo" role="button" tabindex="0">Toggle menu</div>

<script>
    $('#foo').click(function() {
        ToggleMenu('<%# Container.DataItem.FuncID %>');
    }).keydown(function(e) {
        if (e.which === 32 || e.which === 13) {
          this.click();
        }
    });
</script>

Although, it is recommended to simply use a button:

<button id="foo">Toggle menu</button>

<script>
    $('#foo').click(function() {
        ToggleMenu('<%# Container.DataItem.FuncID %>');
    });
</script>

Answer №2

To ensure this action occurs when the enter key is pressed on any part of the webpage:

<div onclick="javascript:ActivateMenu('<%# Container.DataItem.FuncID %>');">
<script>
    document.addEventListener("keypress", function (evt)
    {
        if (evt.keyCode === 13) {
            //enter key was pressed

            //locate the target div
            var div = document.querySelector('div[onclick*="ActivateMenu"]');
            //trigger the event
            div.onclick.apply(div);
        }
    }
    );
</script>

Answer №3

It appears that there is an error in the code you have written

onclick"javascript:xxxx"

is not the correct syntax,

"javascript:xxx"

Instead, you should be using the "a" tag's "href" attribute. Simply remove the "javascript:" from the onclick attribute and you should achieve the desired result.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The error "map is not a function" occurs when trying to update the

I've encountered an issue with my links rendering on a page. I wrote a function that toggles a specific property from false to true based on whether the link is active or not, triggered by a click event. Upon inspecting the updated set of links, I no ...

Exclude the UL hierarchy from removing a class in jQuery

Check out this fiddle to see the code snippet: http://jsfiddle.net/3mpire/yTzGA/1/ I am using jQuery and I need to figure out how to remove the "active" class from all LIs except for the one that is deepest within the hierarchy. <div class="navpole"&g ...

Loading Angular.js scripts into the webpage

My app is built using the MEAN stack. When a user visits the URL: http://localhost:3000/edit/0 Where 0 represents a record id. Initially, it seems like everything should work fine, but I am facing an issue where my scripts are not loading in the edit.js ...

Any tips on how to properly display a div along with script tags in React?

The React application has received a visualization code, and I utilized the unescape function to extract HTML codes from a string. The string contains a div tag with an ID related to the visualization and a script tag containing JavaScript code that genera ...

jQuery GetJson fails to execute success function

I'm trying to use this code for an Ajax request to a JSON file: let formData = $("#myform").serialize(); $.getJSON("/files/data.json?" + formData, function(response){ alert(response); } ); However, there are no errors and the alert is n ...

The callback function used for the database query did not provide any results

So here's a code snippet: module.exports.checkEmailInUse = (email) => { connection.query('SELECT `id` FROM `users` WHERE email = ?', [ email ], function(err, rows, fields) { console. ...

Modify the color of the select element when it is in an open state

If you're new to Material UI, I have a select element that I would like to change the color of. When 'None' is selected, I want the background color of the input field above it to match the 'None' section. Then, when the dropdown m ...

AngularJS showing up as normal text

I can't seem to get angular JS working properly on my website. It keeps displaying as plain text in the browser and doesn't receive any information from the app2.js. I've double-checked all the dependencies and their locations in my code, so ...

The results of the jQuery selector appear differently in the browser console compared to PhantomJS

What could be causing the discrepancy in results when using the same jQuery selector? Visit this website for reference: See below code involving node.js and phantomjs-node(bridge): phantom.create(function(ph){ ph.createPage(function(page){ p ...

Incorporating dynamic elements without sacrificing the original static page

I have a compilation of video titles. Each title links to a page featuring the specific video along with additional details such as player information, description, and discussion. <div id="video-list"> <a href="/Video/title-1">Title 1</a&g ...

Having trouble getting the express router to function properly in your Node.js TypeScript project?

One of the components in this application is registerClass, where all routes are added. The source code is in the dist directory since this node app is using TypeScript. However, when calling the http://localhost:9001/user endpoint, it seems that it is not ...

Error message consistently pops up when using the jQuery search feature

My jQuery function is fetching data from a different domain, and I want to use AJAX to display that data when the user enters a value into the search box. However, no matter if I search by .productName or .itemCode, the app always gives me an error messa ...

Checking for undefined values in fields within an array of objects using scenarios in JavaScript

I am encountering an issue with checking for undefined and empty strings in an object array using Javascript. The code provided is partly functional, but I have hit a roadblock. Within the array object, If the field value is undefined or empty, it should ...

What is the method to retrieve the ID name of an HTML tag based on its value?

Is there a way to determine the ID of an HTML tag based on its content? For example, if I have the following textboxes: I need to identify the id with the value "A2" So the expected result is id=option2 because its value is A2 <input type="text ...

Use a for loop to iterate through elements and retrieve input values using getElementById()

As I work through a for loop in JavaScript, I am utilizing the getElementById() method to fetch multiple input values. To begin, I dynamically created various input boxes and assigned distinct id's using a for loop. Subsequently, I am employing anoth ...

Using a JavaScript callback function as a parameter for the addJavascriptInterface method in Java

Can Java interact with arbitrary functional objects in JavaScript by calling them as callbacks? For example, if we have a function called 'access' that is registered to invoke a Java function: access(function(blabla){ ... }); Are there eff ...

React-spring is causing an increase in the number of hooks rendered compared to the previous render in React

I've encountered a similar issue as discussed on SO, but I'm struggling to resolve the problem detailed below. The scenario This code snippet found at the following link is functional: https://codesandbox.io/s/frosty-water-118xp?file=/src/App. ...

"Utilize Node.js to seamlessly stream real-time Instagram photos based on a designated hashtag

Does anyone know of a node.js library or solution that can automatically fetch Instagram photos in real-time based on specific hashtags? ...

"From time to time, reimport React when saving to ensure all necessary imports are

When working with TypeScript in *.tsx files, particularly when copying code around, I frequently encounter the issue of an additional import line being added. This can be seen below: import React from "react"; // ? On Save "editor ...

Unravel a Base64 encoded string with the power of CryptoJS

I am in the process of developing a basic webpage where the objective is to send an encrypted message to the server, which will then create a file with that content. Subsequently, a link is generated for the recipient to access the encrypted value by provi ...