Select parent div by clicking on child element

Asked

Viewed 77 times

1

Hello, I’m having trouble selecting a parent element when your child is clicked/selected.

I have a main div that takes care of the alignment of an image that is inside it, this image when clicked, can be redeemed, but when I click on it, the parent div is not selected, so I cannot set the div to the correct alignment.

<div style="text-align: left;">
  <img src="imagem" class="ui-imagem-redimensionar" draggable="false" tabindex="0" style="width: 447px; height: 494px; margin: 0px 0px 5px; resize: none; position: relative; zoom: 1; display: block; top: 0px; left: 0px; pointer-events: auto;">
</div>

I tried to create an event with jQuery for when the image received the focus set the focus on her Parent, but I was unsuccessful.

$(document).on('focusin', '.ui-imagem-redimensionar', function () {
  $(this.parentElement).focus();
});

I also tried using CSS pointer-events: none; and z-index: -1; in my image, only then my image is no longer selectable and I can’t redeem.

Someone has some idea, I hope I’ve been clear on my problem

1 answer

0

There are two points here:

  • the event "focusin" is entering with Focus in one element, so it will not be able to change to another without canceling the current event inside the same Handler, for that it is necessary to cancel the event;
  • to the DIV receive phocus, let’s add the attribute "tabindex".

Here an example:

$(document).on('focus', '.ui-imagem-redimensionar', function (event) {
  // esse comando vai cancelar o evento que dá focus à imagem, e permitir dar focus no div
  event.stopPropagation();

  var $div = $(this).parent("div");
  $div.focus();
});
/* para demonstrar que o div recebeu focus */

div:focus {
    border: solid 10px red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="text-align: left;" tabindex="0">
  <img src="imagem" class="ui-imagem-redimensionar" draggable="false" tabindex="0" style="width: 447px; height: 494px; margin: 0px 0px 5px; resize: none; position: relative; zoom: 1; display: block; top: 0px; left: 0px; pointer-events: auto;">
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.