简体   繁体   中英

How to trigger onclick by pressing enter using inline javascript?

[FYI: i am not allowed to change how it was marked up. div will be clicked.. not a button or anchor]

i have a menu(that should pass on accessibility standards) that will open its submenu when clicked.

this is the onclick function, and i need to do the same function when pressing enter key,

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

//submenu (this 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 tried my best to be clear whew!

Here's the accessible solution while keeping 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>

But honestly you should just use a button :

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

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

This will do it when they hit the enter key anywhere on the page

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

            //now get the divevent
            var div = document.querySelector('div[onclick*="ToggleMenu"]');
            //trigger the event
            div.onclick.apply(div);
        }
    }
    );
</script>

I can see you have an error in your code

onclick"javascript:xxxx"

is not correct,

"javascript:xxx"

should using on "a" tag "href" attribute, just remove the "javascript:" in your onclick attribute and you may get what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM