I want to change an element when the cursor is only directly above some text. For instance :
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Trigger the event when on this text but not the blank space after.
I don't want to trigger this change when the cursor is in the div or paragraph and above blank space, like the space at the end of the end of this paragraph. The problem is that elements formated in rectangles and that includes this blank space.
I don't know if this is possible and I don't really know when to start.
CodePudding user response:
As stated in the following link:
Note: An inline element does not start on a new line and only takes up as much width as necessary.
Encapsulate the text within an inline element (like a span
) that don't extend all the way across the page like a block level element would and use a mouseover
event handler on the span
.
document.querySelector("span").addEventListener("mouseover", function(){
console.log("You are over the text of the span");
});
<div>
<span>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Trigger the event when on this text but not the blank space after.
</span>
</div>
And, if you need a solution that only employs JavaScript, we can change the display
property for a div
so that it flows as an inline element:
const div = document.querySelector("div");
div.style.display = "inline"; // Make the div act like a span
div.addEventListener("mouseover", function(){
console.log("You are over the text of the div that is acting as an inline element");
});
<div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Trigger the event when on this text but not the blank space after.
</div>
CodePudding user response:
make sure the element wrapping the text is set to display: inline;
and then listen for the mouseover
event like so:
let element = document.querySelector('.selector');
element.addEventListener('mouseover', () => {
// your code here.
});