Вопрос

I'm using jQuery Tag-It! in my project. I want to make my object's border visible when the onfocus event fires, but I can't make it work.

My code:

<ul id="TagsDesc" name="nameOfSelect" runat="server" ></ul>

<script type="text/javascript">
   $(document).ready(function () {
      $('#<%=TagsDesc.ClientID %>').focus(function () {
         $(this).css("border", "1px solid");
      });

      $('#<%=TagsDesc.ClientID %>').tagit({ 
        'maxTags': 10,'minLength': 1,
        'maxLength': 12,
        'tagsChanged': showTags
      });

      function showTags() {
         var tags = $('#<%=TagsDesc.ClientID %>').tagit("tags");
         var tagsContainer = $('#<%=tagsContainer.ClientID %>');
         var res = '';
         for (var i in tags)
            res += ',' + tags[i].value;
         tagsContainer.val(res);
      }
   });
</script>

Any idea please?

Это было полезно?

Решение

The focus event is actually applicable to focusable elements only. (<input>, <select>, etc.)

ul or li are not focusable by default.

The focus event is sent to an element when it gains focus. This event is implicitly applicable to a limited set of elements, such as form elements (<input>, <select>, etc.) and links (<a href>). In recent browser versions, the event can be extended to include all element types by explicitly setting the element's tabindex property. An element can gain focus via keyboard commands, such as the Tab key, or by mouse clicks on the element.

One work around is to use tabidex on the element you want to make focusable, not sure if its completely cross browser. Adding a tabindex makes most elements focusable as it forces to be focused by keboard.

For setting css values you can use :focus pseudo seleector rather than using jquery.

.focusableelement:focus{
  border: 1px solid red;
  }

Specific answer for tagit:

apply focus event on input with class ui-widget-content ui-autocomplete-input and change border of the parent element with classes tagit ui-widget ui-widget-content ui-corner-all

Другие советы

You have to attach event handlers on the input field created by tag-it. It's a bit of a DOM traversing hassle, but this worked for me using jQuery 1.11 and tag-it 2.0:

  $("#selector")
    .tagit({
       // whatever you need
    })
    // bind events on tag-it's input field 
    .siblings("ul.tagit")
    .first()
    .find("input:first")
    .on("focus", function() {
      $(this).closest("ul.tagit").addClass("focus");
    })
    .on("blur", function() {
      $(this).closest("ul.tagit").removeClass("focus");
    });

Now add appropriate CSS rules in your stylesheet:

ul.tagit.focus {
  border: 1px solid;
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top