Issue
For a research project, I am building a web tool to track users' interactions with specific elements that I need for later analysis.
Often, I have interactable containers that contain graphics or text elements, sometimes both. For instance:
<div class="interaction-field trackable" id="specific-interaction-id"> <!-- This id is what I want to track -->
<img id="img-id" src="path/to/img.png"/> <!-- But i am triggering either this... -->
<p> Some Text </p> <!--...or this -->
</div>
I style the container by its interaction-field
class and have a javascript function that logs all interactions based on the trackable
class. Now, I got two issues.
- For the tracking, I want to store the container's id for simplicity, as in such cases the
<img>
and<p>
belong together. However, mostclick
events, for example, are only recognised on child elements. - Because of this, the parents'
targetable
class is not triggering, denying any logging. Since I want the parents' id as a compound trackable element, I would like to avoid giving the children thetargetable
class to avoid ambiguity and redundancy.
I do get the general layering problem and it is logical that I rather hit the children than their parents. But is there an elegant way to always pass the parents' classes and id's to make the logging easier? Or is there an even simpler solution that I am not seeing?
Thanks in advance!
Solution
You can delegate the click handler to the document. Then grab the clicked element and use closest to find the parent element's ID if it has the trackable class.
document.addEventListener("click",(e)=>{
let trackedEl = e.target.closest(".trackable");
if(trackedEl){
console.log(trackedEl.id)
}
});
<div class="interaction-field trackable" id="specific-interaction-id"> <!-- This id is what I want to track -->
<img id="img-id" src="path/to/img.png"/> <!-- But i am triggering either this... -->
<p> Some Text </p> <!--...or this -->
</div>
Answered By - imvain2
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.