Apply certain JS to specified class/IDs only

108 Views Asked by At

I have a game written in JS, and have some code to prevent the user from dragging on and highlighting the in-game contents:

onSelectStart="return false;"
onMouseDown="return false;"
style="-moz-user-select: none; -khtml-user-select: none; user-select: none;"

I usually apply this to the specific elements in my game individually within HTML, but it doesn't look good when you have all this code for each element you want "un-selectable".

Using my tiny knowledge of JavaScript, I wrote something like this:

$(".nonselect").Nonselectable();
function Nonselectable() {
    onSelectStart="return false;"
    onMouseDown="return false;"
    style="-moz-user-select: none; -khtml-user-select: none; user-select: none;"
}

Then add .nonselect to those elements I want un-selectable.

But it is not working. Why does it not work, and how can I do this?

1

There are 1 best solutions below

1
On

use the each() function

$(".nonselect").each(function(){
    $(this).selectstart(function(event){event.preventDefault();});
    $(this).mousedown(function(event){event.preventDefault();});
    $(this).css("-moz-user-select", "none");
    $(this).css("-khtml-user-select: none; user-select", "none;"
});