I'm working on a project where I can't use jQuery and I'm having an issue with the click event.
I have a link with an icon and some text and I want to create an event that when I click the link it gets added a "selected" class. The issue is that when I click a child node the class is added to it and not the link.
Here's an example:
window.onload = function() { var actions = document.querySelectorAll(".action"); actionClickHandler = function(e) { e.target.classList.add("selected"); }; actions.forEach(function(action) { action.addEventListener("click", actionClickHandler); }); }
.action { display:inline-block; padding:10px 15px; background-color:#eee; border:1px solid #ddd; border-radius:8; color:#666; text-decoration:none; } .action:hover { box-shadow:0px 2px 5px rgba(0,0,0,0.3); border-color:#ccc; } .selected { background-color:#fff; }
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/> <a href="#" class="action"> <i class="icon fa fa-comment"></i> Comment </a> <a href="#" class="action"> <i class="icon fa fa-heart"></i> Like </a>
What I want is that when I click anywhere on the link element (".action") the .action gets the class "selected" and not the child.
How can I achieve this?
Use event.currentTarget
instead of event.target
.
event.currentTarget returns the DOM element that the event linstener was attached to, as opposed to event.target which returns the inner-most element, the one that captured the event.
window.onload = function() { var actions = document.querySelectorAll(".action"); actionClickHandler = function(e) { e.currentTarget.classList.add("selected"); }; actions.forEach(function(action) { action.addEventListener("click", actionClickHandler); }); }
.action { display:inline-block; padding:10px 15px; background-color:#eee; border:1px solid #ddd; border-radius:8; color:#666; text-decoration:none; } .action:hover { box-shadow:0px 2px 5px rgba(0,0,0,0.3); border-color:#ccc; } .selected { background-color:#fff; }
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/> <a href="#" class="action"> <i class="icon fa fa-comment"></i> Comment </a> <a href="#" class="action"> <i class="icon fa fa-heart"></i> Like </a>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.