简体   繁体   中英

Fire event on .click() (except when selecting text)

I'm making some kind of chat box, and I want the input within the message box to get focused when the user clicks the whole chat box, except if, let's say, the user is selecting text to copy; in that case it'd make it impossible for the user to copy it 'cause, when he releases the mouse, the selected text would be deselected and, well... That sucks.

Any idea?

PD: The .chats are generated with jQuery, so I have to use events like in the snippet.

Here's an extract of my code (with just the important stuff):

 $("body").on("click", ".chat", function() { $(this).find("input").focus() }); 
 .chat { background-color: #fff; bottom: 0; left: 0; position: fixed; width: 200px; height: 250px; border: 1px solid #ccc; padding: 0.5em } .chat .messages { color: #666; } .chat input { position: absolute; bottom: 0; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div class="chat"> <div class="messages">Terrible markup... Try to copy me. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div> <input/> </div> 

Use a time difference between mousedown and mouseup (~350ms)
to realize if it was a click or a (slower) text selection!

 var t; $(document).on("mousedown mouseup", ".chat", function(ev) { t = ev.type=="mousedown" ? new Date() : new Date() - t; if(t<350) $(this).find("input").focus(); }); 
 .chat { background-color: #fff; bottom: 0; left: 0; position: fixed; width: 200px; height: 250px; border: 1px solid #ccc; padding: 0.5em } .chat .messages { color: #666; } .chat input { position: absolute; bottom: 0; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div class="chat"> <div class="messages">Terrible markup... Try to copy me. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div> <input/> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM