When you press the spacebar on an anchor html element, the click event does not fire. How to do it?

<a tabindex="7" style="cursor: pointer;" class="button" id="saveTocAddNew" onClick="saveTdsAddNew();"/><span>Save & Add Another</span></a>

I have the above anchor element on my page. This style looks like a button and therefore will be considered as a button. The problem is as follows. The user does not want to use the mouse to click on it or to reach it, but he will use the tab to highlight this anchor element, and then will use the space bar or return key to click on it. If the user presses the space bar or return key, I should be able to call the JavaScript function. I tried the onkeypress event and it does not help. Any idea?

+5
source share
2 answers

First: a problem with your HTML. You use short syntax for A- this means that the text is not actually part of the content A. Many browsers do not like the short syntax for tags Aanyway - not your fault, but our work is more tolerant than browsers.

Here's the adjusted version:

<a tabindex="7" style="cursor: pointer;" class="button" id="saveTocAddNew" onClick="saveTdsAddNew();"><span>Save & Add Another</span></a>

Depending on the browser and DOCTYPE, it is important whether the event name is lowercase or not. Just looking for something.

, onclick Enter - . pagedown. , A , Enter, , . :

function addNewKeys(event) {
    if(!event) var event = window.event; // cross-browser shenanigans
    if(event.keyCode === 32) { // this is the spacebar
        saveTdsAddNew(event);
    }
    return true; // treat all other keys normally;
}

( onkeypress A.)

, event saveTdsAddNew. , , event , . event , /, ..

+6

, , .

, , , , , , , .

on-click HTML.

0

All Articles