Reputation: 764
The following code allows user to select text by clicking on it. If user want's to select multiple text lines. User just have to press Ctrl and Click. User can change the color of selected text to green by clicking on 'Green Color' Button. Atleast one text stays selected.
All the text gets deselected when user presses Esc key on keyboard. The function of Esc I wan't to achieve when user clicks anywhere, except on text and 'Green Color' button.
To achieve it, I was trying to capture click event on 'this' using the commented code and then recognize whether it has class 'selectable', if not then remove class obj_select from all the elements having class 'selectable', but it seems this is not capturing text element. But even when I am clicking on Text, the jquery is not recognising the element with class 'selectable' rather selects entire document.
Please guide to achieve deselection on clicking outside of text and 'Green Color' button.
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<style type="text/css">
.obj_select{
outline: dashed;
outline-width: 2px;
}
</style>
<script src="https://code.jquery.com/jquery-2.2.0.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/svg.js/3.0.12/svg.js"></script>
</head>
<body>
<div style='left:"100px";'>
<svg id="limits" width=350 height=350>
<text id="demo_text_1" class="selectable" x="10" y="20" transform="translate(10,0)" fill="red">This is Demo Text 1</text>
<text id="demo_text_2" class="selectable" x="10" y="40" fill="red">This is Demo Text 2</text>
<text id="demo_text_3" class="selectable" x="10" y="60" fill="red">This is Demo Text 3</text>
</svg>
<button id="green" class="formatter">Green Color</button>
</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
/*
$(this).on('click',function(event) {
alert($(this).attr("class"));
if(!$(this).hasClass('selectable') && !$(this).hasClass('formatter'))
{
$(".selectable").removeClass('obj_select');
}
});
*/
$(".selectable").on("click",function(evt){
console.log($(this));
if (!evt.ctrlKey)
{
$(".selectable").not(this).removeClass('obj_select');
}
$(this).addClass("obj_select");
});
$(document).keyup(function(e) {
if (e.key === "Escape") {
$(".selectable").removeClass('obj_select');
}
});
$("#green").on("click",function(){
$(".obj_select").css({
fill: 'green'
});
});
});
</script>
</body>
</html>
Upvotes: 0
Views: 74
Reputation: 961
I am not sure but if you want to achieve deselection on clicking outside of the selectable items I think that this is what you are looking for:
$(document).click(function(e) {
if(!$(e.target).is(".selectable")) {
$(".selectable").removeClass('obj_select');
}
});
Basically you need to check what is your clicking target and if its not the .selectable you can remove the class
Upvotes: 2