Designer
Designer

Reputation: 895

Using js instead of jquery to focus on input field when click on a specific div

I have this code in jquery:

$('.selection').click(function() {
    $('#autocomplete').focus();
});

How can i run exactly the same code using pure javascript instead of jquery ?

Upvotes: 0

Views: 540

Answers (3)

SashoSTZ
SashoSTZ

Reputation: 302

function getFocus() {         
    document.getElementById("myTextField").focus();
}

This indicated in the official documentation: https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/focus

Upvotes: 0

Rado
Rado

Reputation: 749

You can search for vanilla js for focus and click events on the net. You can also use the snippet below.

const selection = document.querySelector('.selection');
const autocomplete = document.querySelector('#autocomplete')

selection.addEventListener('click', function(){
 autocomplete.focus();
})
.selection {
  width: 200px;
  height: 200px;
  background: green;
}

#autocomplete {
  width: 150px;
  height: 30px;
  background: yellow;
}
<div class="selection"></div>

<input id="autocomplete" />

Upvotes: 2

smunteanu
smunteanu

Reputation: 542

You can do this, and it will work exactly the same:

document.querySelector('.selection').addEventListener('click', function() {
  document.querySelector('#autocomplete').focus();
});

Upvotes: 3

Related Questions