Here is my HTML:
<div id="doc1" class="document-container-title">
<h3>Doc 1</h3>
</div>
<div id="doc2" class="document-container-title">
<h3>Doc 2</h3>
</div>
<div id="doc3" class="document-container-title">
<h3>Doc 3</h3>
</div>
As you can see, each div has a class of 'document-container-title'. I want to add some JavaScript to detect if any one of these divs were hovered over, and then I want to find out which specific div was hovered over. Specifically, I want to be able to detect whether a div with the class of document-container-title was hovered over. If so, then I want to get the id of the exact div that was hovered over.
I am only one month into JavaScript so a helpful explanation wouldn't hurt.
Thanks.
P.S. I don't mind using jQuery.
One solution is this one:
const elements = document.getElementsByClassName('document-container-title')
for (let element of elements) {
element.addEventListener('mouseenter', (e) => {
console.log(e.target.id);
});
}
First, you will iterate over your DOM to get all elements with the specified class. The defined constant elements is now an array of html elements that have the document-container-title class. After that, you will have a simple for loop to iterate over all gathered elements. Finally, you will add an event listener for the current element in the for loop that will trigger the mouseenter event. Then, you can easily get the target with their corresponding id.
you can use jQuery mouseover or mouseenter event based on your requirement like this:
Based on this:
The mouseover event triggers when the mouse pointer enters the div element, and its child elements.
However
The mouseenter event is only triggered when the mouse pointer enters the div element.
$(".document-container-title").mouseover(function (e) {
console.log(e.currentTarget.textContent);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="doc1" class="document-container-title">
<h3>Doc 1</h3>
</div>
<div id="doc2" class="document-container-title">
<h3>Doc 2</h3>
</div>
<div id="doc3" class="document-container-title">
<h3>Doc 3</h3>
</div>