Pregunta

Triggering a click synthetically does not cause focus to switch to the element, however the click triggered by hardware does.

I'm trying to simulate a synthetic click on an element (say div with tabindex), which has a callback bound on focus. I do not want to call focus on the element explicitly, as the element can gain focus by click or keyboard tab.

My JSFiddle

Code:

$('button.trigger').click(function(){
    $('div#target').trigger('click');
});

$('button.trigger1').click(function(){
    var event = new MouseEvent('click');
    var target = document.getElementById('target'); 
    target.dispatchEvent(event);
});

$('div#target').click(function(){
    $(this).addClass('selected');
});

HTML:

<div id="target" tabindex="-1"></div>
<button class="trigger">Click to trigger click</button>
<button class="trigger1">Click to dispatch click</button>

CSS:

div{
    height:100px;
    width:100px;
    border:10px solid black;
}

#target:focus{
    background-color:#aaa;
}
.selected{
    border-color:red;
}
¿Fue útil?

Solución

There's no such thing as a hardware click.

Focus happens on mouse down.

If the mouse is released over the same element, then you also get a click event.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top