0

How we can use all texts inside bodyelement as selector just like any other selectors (ie.: id, class, input, etc.)? I want to do something when any text in the body is hovered or clicked.

Example:

$("body > text").on('mouseover', function(){
 alert("Any text in the body is hovered!");
});

I tried this:

$("body").text().on('mouseover', function(){
 alert("Any text in the body is hovered!");
});

but it is returning this error:

TypeError: $(...).text(...).on is not a function
Ari
  • 4,643
  • 5
  • 36
  • 52

2 Answers2

0

Your first case didn't attach the event as there is no element with tagname text. and second one failed as jquery .text() return string and on method is used for jquery objects of dom elements which causes the error for you.

You need to simply attach the event to body element.:

$("body").on('mouseover', function(){
 alert("Any text in the body is hovered!");
});

you can also use all selector to attach event to all the inner elements:

$("body *").on('mouseover', function(){
 alert("Any text in the body is hovered!");
});
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
  • Isn't it will also select image and any other stuffs than text? – Ari Feb 19 '15 at 08:51
  • that is the reason i would suggest you to attch event to body and then use stopPropogation for elements on which you do not want event to occur. see this post http://stackoverflow.com/questions/10389459/is-there-a-way-to-detect-if-im-hovering-over-text – Milind Anantwar Feb 19 '15 at 10:43
0

you can put your body text in <span> or <p> tags and can easily attached mouseover event in jquery i.e:

HTML:

<body>
<p>this is text</p>
</body>

JQuery:

$("body p").on('mouseover', function(){
 alert("Any text in the body is hovered!");
});
  • What if the only wrapper for the text is `body` tag and there other stuffs like image, while I only want to select text? – Ari Feb 19 '15 at 08:59