How can I call onblur from ul li?


By default, I highlight each li when clicked and want to β€œunselect” the clicked li when clicked elsewhere or pasted (using the background-color property).

Such behavior will essentially emulate <select> in its "underlining behavior ... I am not using select , although since I want to embed HTML inside the listed elements - you cannot do this with <option> .

I am trying to use onblur which does not work ...



Here is the HTML:
 <ul id = "list"> <li>asdf</li> <li>qwerty</li> <ul> 


... here is the CSS:

  #list { list-style-type: none; } 


... and here is jQuery / javascript:

  function getEventTarget(e) { e = e || window.event; return e.target || e.srcElement; } function highlightSelection(selection) { alert("It worked!"); $(selection).css("background-color","#FFFF00"); } // this function is not being triggered: function removeHighlight(selection) { $(selection).css("background-color","none"); } var ul = document.getElementById("list"); ul.onclick = function(event) { var target = getEventTarget(event); highlightSelection(target); }; // this event is not working: ul.onblur = function(event) { var target = getEventTarget(event); removeHighlight(target); }; 
+4
source share
2 answers

Since you are already using jQuery ...

 <ul id = "list"> <li tabindex="1">asdf</li> <li tabindex="2">qwerty</li> <ul> var ul = $("#list"); ul.on('click focus','li',function(){ $(this) .css("background-color","#FFFF00") .siblings().css('background',''); }).on('blur','li',function(){ $(this).css('background',''); }); 

http://jsfiddle.net/mc4tN/2/

I was not sure what effect you needed when you move away from the list item ... It seems you just want to leave it selected. You can add focus ability to your list items by giving them the tabindex attribute.

+1
source

li do not blur because they do not focus. Try using mouseout or mouseleave .

0
source

Source: https://habr.com/ru/post/1491512/


All Articles