Z.R.T.
Z.R.T.

Reputation: 1603

check whether selected text clicked or not

I have a div element with text inside. I want to know what the user clicked on, selected text or not selected ? The main goal to distinguish between selected text clicking and unselected text clicking

Upvotes: 0

Views: 795

Answers (2)

JSman225
JSman225

Reputation: 96

This will run 2 different functions. When you click on the selected text, it will run one function, making the background red, and when you click on the non-selected text, it will run another function, making the background green. Hope this hepls.

function red(){

//this function will be executed when the selected text is clicked

document.body.style.backgroundColor = "red";
}
function green(){

/*this function will be executed when the non-selected text is clicked*/

document.body.style.backgroundColor = "green";
}
body{
font-size:30px;
}
<body>
<div><span onclick="red()" style="background-color:yellow">this text is selected</span>,<span onclick="green()"> this text is not</span></div>
</body>

Upvotes: 1

caidensanders
caidensanders

Reputation: 81

I would recommend that you throw this useful piece of CSS on the div in order to make the text non-selectable:

div {
    user-select: none;
}

Change the div to the correct class or ID, but that will make the text non-selectable so that you can tell that they have only clicked it. I use this for almost everything that I have that is clickable.

Upvotes: 1

Related Questions