Roger Chan
Roger Chan

Reputation: 1393

How can I get the element or element itself from Event e

How can I get the current LIElement's id which fire event e in activeNav(), because I want to find the active element from navMap.

import 'dart:html';

Map navMap = new Map<String, LIElement>();

void main() {
  navMap["#li-home"] =  query("#li-home");
  navMap["#li-about"] =  query("#li-about");
  navMap["#li-setting"] =  query("#li-setting");
  navMap["#li-home"].onClick.listen(activeNav);
  navMap["#li-about"].onClick.listen(activeNav);
  navMap["#li-setting"].onClick.listen(activeNav);
}

void activeNav(Event e){
  // Get element #li-home from map and add class "active"
  // remove the class "active" from remain LIElements in navMap

Upvotes: 1

Views: 1434

Answers (1)

Shailen Tuli
Shailen Tuli

Reputation: 14161

You don't need to store all the li elements in a map. Just attach the event handler to the ul that contains the lis, figure out which li was clicked, and add or remove the 'active' class:

import 'dart:html';

void main() {
  query('ul').onClick.listen((event) {
    if (event.target.id == 'li-home') {
      event.target.classes.add('active');
    } else {
      event.target.classes.remove('active');
    }
  });
}

Upvotes: 3

Related Questions