If I click on a selection in the autocompleter of WordPress in codeMirror, the whole field is closed. To prevent this I want to add preventDefault to the click event.
var cm = wp.codeEditor.initialize( options.field, editorSettings );
var editor = cm.codemirror;
jQuery('body').hover(function(e){
if(jQuery('ul.CodeMirror-hints')){
jQuery('ul.CodeMirror-hints').mousedown(function(eH){
eH.preventDefault();
});
}
});
var editorSettings = {
mode: 'css',
lineNumbers: true,
indentUnit: 2,
tabSize: 2,
autoRefresh:true,
autocorrect: true,
autocapitalize: true,
matchBrackets: true,
autoCloseBrackets: true,
lineWrapping: true,
lint: true,
gutters: [ 'CodeMirror-lint-markers' ]
}
Since ul.CodeMirror-hints is now stored in the body element and is only inserted when codeMirror hints makes a suggestion, I have to make an event on body.
body => <ul class="CodeMirror-hints"...</ul>
Is there a better solution to add preventFefault() to the event click on ul.CodeMirror-hints?
If I click on a selection in the autocompleter of WordPress in codeMirror, the whole field is closed. To prevent this I want to add preventDefault to the click event.
var cm = wp.codeEditor.initialize( options.field, editorSettings );
var editor = cm.codemirror;
jQuery('body').hover(function(e){
if(jQuery('ul.CodeMirror-hints')){
jQuery('ul.CodeMirror-hints').mousedown(function(eH){
eH.preventDefault();
});
}
});
var editorSettings = {
mode: 'css',
lineNumbers: true,
indentUnit: 2,
tabSize: 2,
autoRefresh:true,
autocorrect: true,
autocapitalize: true,
matchBrackets: true,
autoCloseBrackets: true,
lineWrapping: true,
lint: true,
gutters: [ 'CodeMirror-lint-markers' ]
}
Since ul.CodeMirror-hints is now stored in the body element and is only inserted when codeMirror hints makes a suggestion, I have to make an event on body.
body => <ul class="CodeMirror-hints"...</ul>
Is there a better solution to add preventFefault() to the event click on ul.CodeMirror-hints?
Share Improve this question asked Feb 27, 2019 at 8:55 SeverinSeverin 551 gold badge1 silver badge8 bronze badges2 Answers
Reset to default 0Event delegation is your friend! This way the element doesn't have to exist when the code runs to have the function bound to it.
jQuery('body').on('click', 'ul.CodeMirror-hints li', function(e) {
e.preventDefault();
});
replace click
with mousedown
if you need to
This solution is not beautiful but it does what it should.
jQuery('body').hover(function(e){
if( jQuery('ul.CodeMirror-hints li').length > 0){
jQuery('ul.CodeMirror-hints li').mousedown(function(eH){
eH.preventDefault();
});
jQuery('ul.CodeMirror-hints li').click(function(ecH){
ecH.preventDefault();
});
}