Home > Software engineering >  How can I return two parameters when onfocus?
How can I return two parameters when onfocus?

Time:02-16

I have a function that returns the currently focused item's ID and a random string. I use a different function to parse through that string.

I need to also return the aria-label, which is where I'm having trouble. None of my current attempts have worked.

var global_focused_id = -1;

function GetLastFocusedId() {
  return global_focused_id;
}

function reply_focus(focused_id) {
  global_focused_id = focused_id   ' || '   Math.random();
  console.log(global_focused_id);
}
<button  id="some-id" aria-label="some-label" onfocus="reply_focus(this.id)">Button Text</button>

What returns now is: "some-id || 0.1234567890"

What I'd like returned is: "some-id || some-label || 0.1234567890"

CodePudding user response:

Pass the entire event (or just the element) and get it from that.

https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute

var global_focused_id = -1;

function reply_focus(el) {
  global_focused_id = el.id   ' || '
      el.getAttribute('aria-label')   ' || '   Math.random();

  console.log(global_focused_id);
}
<button  id="some-id" aria-label="some-label" 
  onfocus="reply_focus(this)">Button Text</button>

CodePudding user response:

You have easy access to the element the event handler is bound to -- the Event Object is passed by default:

     function eventHandler(event) {... // aka e, evt, etc.

The Event property Event.target will always reference the tag (element) the user interacted with (ex. user clicked a button now e.target points to it). There is also e.currentTarget which points to the tag that the event handler is bound to, in the example below the button is both e.target, e.currentTarget, and this.

Note, all values of the button are stored in an object which might be more useful but it isn't necessary. Also Inline Event Handlers are Garbage. Also read about Events and Event Delegation inline_event_handlers_—_dont_use_these)

let cfg = {};

function getBtnID(event) {
  const focalPt = event.target;
  
  cfg.id = focalPt.id;
  cfg.key = Math.random();
  cfg.label = this.getAttribute('aria-label');
  
  console.log(cfg);
};
  
document.getElementById('exit-0').addEventListener('focus', getBtnID);

// OR document.getElementById('btn').onfocus = getBtnID;

  
<button id="exit-0"  aria-label="close">❌</button>

  • Related