Kris
Kris

Reputation: 575

How to remove selection on images

I want to remove the selection-highlight on all images on my page. I found some useful additions like :

CSS

img {
     -webkit-user-select:none;
     -khtml-user-select:none;
     -moz-user-select:none;
     -o-user-select:none;
      user-select:none;
      pointer-events:none
}

But when I press down my mouse button and select multiple things or press Ctrl+A for "select all" my images get highlighted with a blue shade. I tried to change it via :

CSS

img::selection      {background:transparent;color:inherit;}
img::-moz-selection {background:transparent;color:inherit;}

But that don't have any effect.

Does someone have a useful solution or is there none yet ?

P.S. : I don't care about selecting my images - I just want to get rid of that blue shape.

Upvotes: 0

Views: 4406

Answers (2)

KaMZaTa
KaMZaTa

Reputation: 741

This disabled highlighting on a DOM element:

function disableSelection(target){
    if (typeof target.onselectstart!="undefined") // if IE
        target.onselectstart=function(){return false}
    else if (typeof target.style.MozUserSelect!="undefined") // if Firefox
        target.style.MozUserSelect="none";
    else // others
         target.onmousedown=function(){return false;}

    target.style.cursor = "default";
}

Use it like this:

disableSelection(document.getElementById("my_image"));

Upvotes: 0

Danield
Danield

Reputation: 125591

Here goes a wacky solution I came up with...

1) After some testing I found that this only occurs on mozilla. Other browsers don't show the blue selection on images when the code

img::selection {
    background: transparent;
}

is set.

2) Even mozilla - only has a problem with image elements. But other elements with a background-image obey the ::selection rule.

So technically we could work around this assuming we add an empty span in our markup after each img element which we set to display:none;

Then we can add some CSS which will only run in firefox which sets the images to display:none and places a background-image on the adjacent span.

Like this:

FIDDLE

**

img::selection {
    background: transparent;
}
img + span {
    display: none;
}

@-moz-document url-prefix() {
    img {
        display: none;
    }
    
    img + span {
        background: url(http://placehold.it/200x200) no-repeat;
        width: 200px;
        height: 200px;
        display: block;
    }
}
<div>Hello there </div>

<img src="http://placehold.it/200x200" /><span></span>

<div>Hello there </div>
1: http://jsfiddle.net/GMuzV/30/

Upvotes: 1

Related Questions