javascript/jquery: focus() not working

Andre picture Andre · Apr 24, 2014 · Viewed 7.5k times · Source

I want to focus a special id (in roundcube) by a keyboard shortcut. The html is

   ... 
   <div id="mainscreen">
    <div id="messagetoolbar" class="toolbar">
    <div id="mailview-left" style="width: 220px;">
    <div id="mailview-right" style="left: 232px;">
    ...

I tried the following:

 // Strg + Tab, um in Nachrichtenbereich zu kommen
 ...
 else if (event.keyCode == 9 && event.ctrlKey) {
 alert("taste erkannt");
 //document.getElementById("messagetoolbar").focus();
 //$("#messagetoolbar").focus();
 setTimeout(function() { $('#messagetoolbar').focus(); alert("zeit"); }, 3000);
 }
 ...

The first alert and the second alert is shown but no focus on id messagetoolbar. Does anybody have an idea?

Thank you very much.

Edit: I think I should describe it better: I want to mark the first line/email in the email-inbox in roundcube. The inbox is a table with a tr-tag...when I try your solution the first line is dotted, too, but with enter I can't open the mail and with other keys I can't MARK the first line/mail... I think I have to "simulate a left-klick" to get the first line marked...?
Now I tried to use jquery's .trigger. The html of the inbox-Table is

 <table id="messagelist" class="records-table messagelist sortheader fixedheader">
  <thead>
  <tbody>
     <tr id="rcmrow27428" class="message">
         <td class="threads"></td>
         <td class="date">16.04.2014 13:41</td>
         <td class="fromto">
 ...

I tried to use...

 $('#messagelist tr').eq(1).addClass('message selected focused').removeClass('unfocused').trigger("click");

...but it doesn't work: It adds an removes the classes but doesn't really focus the line :-( With "buttons" it works.

EDIT AGAIN: I think the file list.js of roundcube is important for that question. There I found the following:

/**
 * Set focus to the list
 */
focus: function(e)
{
  var n, id;
  this.focused = true;

  for (n in this.selection) {
    id = this.selection[n];
    if (this.rows[id] && this.rows[id].obj) {
      $(this.rows[id].obj).addClass('selected').removeClass('unfocused');
    }
  }

  // Un-focus already focused elements (#1487123, #1487316, #1488600, #1488620)
  // It looks that window.focus() does the job for all browsers, but not Firefox (#1489058)
  $('iframe,:focus:not(body)').blur();
  window.focus();

  if (e || (e = window.event))
    rcube_event.cancel(e);
},

Does anybody know how to modify or use referring to my question? Thank you!

Answer

Harshit Jain picture Harshit Jain · Apr 24, 2014

Add tabindex=0 attribute to the div you want to foucs and you will be able to set focus on the div using .focus()