if ($(e.target).hasClass("leaf")) {
// do x
} else {
// do x but in a different way
}
This part makes it harder to maintain. If you change one you must change the other.
$(this).attr("tabIndex", -1);
You do not need jQuery for this. Try this.setAttribute("tabIndex", -1) or even this.tabIndex = -1.
Also, I see some problems with this code:
- Why are you checking the event's target in
$().on("click")? Would the event's target not be this? Maybe you should change it to $(".leaf.my-class, .tree.my-class")?
- What if a user clicks on an element besides
.leaf or .tree? The code suggests that you expect one or the other. Should $(".my-class") be changed to $(".leaf, .tree")?
- What if you add leaves? You will need to update
leaves and trees if new leaves/trees are created.
Here is my proposed solution...
var $leaves = $(".leaf"), $trees = $(".tree"), tabIndexLeaves = -1, tabIndexTrees = 1;
$(".my-class").on("click", function (e) {
var isLeaf = $(e.target).hasClass("leaf");
if ((isLeaf && tabIndexLeaves !== 1) || (!isLeaf && tabIndexLeaves === -1)) {
// Invert the tabIndex
tabIndexLeaves = -tabIndexLeaves;
tabIndexTrees = -tabIndexTrees;
// Update all the leaves' and trees' tabIndexes
$leaves.attr("tabIndex", "" + tabIndexLeaves);
$trees.attr("tabIndex", "" + tabIndexTrees);
}
});