1

I have this problem, I need to add onmousedown and onselectstart events to certain html elements. I've tried with this but as they are not attributes this doesn't work.

$(".question, p, b, span, img").each(function(){ 
   $(this).addClass("disableSelection");
   $(this).attr("onmousedown", "return false;");
   $(this).attr('onselectstart', 'return false;');
});

Any ideas?

Example

<p onmousedown="return false;" onselectstart="return false;">Adding events</p>
Polo
  • 159
  • 2
  • 13

3 Answers3

1

You should add event handlers using JS, not the outdated on* event attributes. There's also no need to loop through the elements. Try this:

$(".question, p, b, span, img")
    .addClass('disableSelection');
    .on('mousedown selectstart', function() {
        return false;
    });

Note that by using return false in the event handler you also stop propagation. If that's a problem could just use the preventDefault() method of the event that's passed to the event handlers.

Also, if you want to remove any event handlers already attached to those events you may be better served by using the off() method, for example .off('mousedown selectstart');

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
1

Event in JavaScript is not an attribute of an HTML element.

You can add events like this:

$(".question, p, b, span, img").mousedown(function(){ 
    return false;
});

Reffer to this documentation page: https://api.jquery.com/mousedown/

Also, you should not use .each function in order to iterate over selected elements. jQuery will handle it for you, so in order to add class, as in your example, I suggest you to do it like this:

$(".question, p, b, span, img").addClass("disableSelection");
Tushar
  • 85,780
  • 21
  • 159
  • 179
Alexander Capone
  • 528
  • 3
  • 16
1

To prevent user from selecting text, you can use following CSS.

From How to disable text selection highlighting using CSS?

.noselect {
  -webkit-touch-callout: none; /* iOS Safari */
  -webkit-user-select: none;   /* Chrome/Safari/Opera */
  -khtml-user-select: none;    /* Konqueror */
  -moz-user-select: none;      /* Firefox */
  -ms-user-select: none;       /* IE/Edge */
  user-select: none;           /* non-prefixed version, currently
                                  not supported by any browser */
}
Community
  • 1
  • 1
Tushar
  • 85,780
  • 21
  • 159
  • 179