0

I have created an element using javascript and trying to bind focus/blur event, but it is not firing. How can I acheive the same?

var parentContainer = document.getElementById('parent');
var container = document.createElement('div');
container.innerHTML = '<p>Hello</p>';
container.style.userSelect = "none";
container.style.MozUserSelect = "none";

parentContainer.appendChild(container);

$(container).focus(function () {
  $(this).css('border', '1px solid')
}).blur(function () {
  $(this).css('border', '')
});

//container.addEventListener('focus',function () {
//  $(this).css('border', '1px solid')
//})
//container.addEventListener('blur',function () {
//  $(this).css('border', '')
//})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='parent'>
  
</div>
Vijesh
  • 572
  • 2
  • 7
  • 20
Escoute
  • 366
  • 2
  • 15
  • You can't have `focus` and `blur` on elements which don't accept a focal point. Do you mean `mouseover` and `mouseout`? Also, you should use `.on("eventname", function` instead of `.eventname(function` – freefaller Jun 07 '19 at 15:03
  • @freefaller I want to change the border of element on focus, and blur need to remove it. mouseover and mouseout won't work out here I guess. – Escoute Jun 07 '19 at 15:09
  • But you **can't** put focus on an element that doesn't accept a focal point. You can focus on things like ``, ` – freefaller Jun 07 '19 at 15:11
  • @freefaller technically you can if you add a `tabindex` attribute, but it's not good practice for UX, and is a bit hacky. – Rory McCrossan Jun 07 '19 at 15:13
  • @Rory - I did not know that... thanks for the information, and I stand corrected (but I totally agree, it's not nice) – freefaller Jun 07 '19 at 15:14
  • Adding `tabIndex = -1` works in this case. – Escoute Jun 07 '19 at 15:18

1 Answers1

0

In order to apply focus on div, you need to add tabindex to the div. I would suggest you use mouseover or hover to apply or do anything specific because the focus property should be used for input fields

<div id='parent' tabindex="100">

</div>
Umashankar
  • 515
  • 4
  • 16