I'm trying to find out how to 'select' an image. That is if you were to double click on any text on this page, that word will be highlighted/selected.
Is it possible to do the same with an image.
https://jsfiddle.net/eL6my246/
<img src="http://www.free.fr/freebox/im/logo_free.png" style="max-width:200px;" />
<p>
Here is some content. Double click a word to 'select' it. Now try
with the image and notice it doesn't get selected.
</p>
If you click in the result pane of the JSFiddle (the page where the HTML is rendered) and on your keyboard do Ctrl+A (select all) you can see the image is selected (it goes in blue). How can I select the image by single (or double) clicking the image?
Here is a small example on programmatically doing selection via javascript. It is interesting to see the documentation for window.getSelection() and also the Range class API
var btnToggleSelection = document.getElementById('toggleSelection');
btnToggleSelection.imgSelected = false;
btnToggleSelection.addEventListener('click', function(e) {
if (this.imgSelected) {
/* deselect image */
clearSelection();
this.innerHTML = "Select";
} else {
/* select image */
var s = window.getSelection();
var r = document.createRange();
r.selectNode(document.images[0]);
s.addRange(r);
this.innerHTML = "Deselect";
}
this.imgSelected = !this.imgSelected;
});
function clearSelection() {
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE
document.selection.empty();
}
}
<img src="http://www.free.fr/freebox/im/logo_free.png" style="max-width:200px;" />
<button id="toggleSelection">Select</button>
Check the code and make it fit your needs. Let me know if you need more help. Good luck !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With