I am using codemirror in a webapp I am creating and I have several editors on the page. There are undo and redo buttons as well and they do work. However I can only set one editor to undo unless I use an if statement to determine which one is focussed and then apply the undo or redo function to its corresponding textbox. I have tried a few variations in both jQuery and JavaScript but to no avail. This is one of the code blocks I am attempting to get to work. The actual variable that holds the codemirror setup is called "codeeditor1", "#editor1" is the id of the textbox.
if ($("#editor1").is(':focus')) {
undo.addEventListener('click', function() {
codeeditor1.undo();
}, false);
redo.addEventListener('click', function() {
codeeditor1.redo();
}, false);
}
I also tried this according to the documentation of the method "cm.hasFocus()" = boolean.
if (codeeditor1.hasFocus() == true) {
undo.addEventListener('click', function() {
codeeditor1.undo();
}, false);
redo.addEventListener('click', function() {
codeeditor1.redo();
}, false);
}
I have now also tried this for the sake of logical code placement but still no luck with it. Perhaps it is a bug in the method of codemirror?
undo.addEventListener('click', function() {
if (codeeditor1.hasFocus() == true) {
codeeditor1.undo();
}
}, false);
redo.addEventListener('click', function() {
if (codeeditor1.hasFocus() == true) {
codeeditor1.redo();
}
}, false);
Okay! So, I figured it out.
The problem is (I wasn't thinking properly) that when the user presses the button of course the focus gets removed, and then it tries to test it meaning the result of "hasFocus" is of course false. So to get around this, I created a variable. The variable updates when ever one of the editors is in focus to either 1, 2 or 3. Then I check on click of the button what the value of the variable is and then re-apply the focus to the corresponding editor before running either undo or redo on the now in-focus editor.
var detectfocus = "0";
codeeditor1.on('focus', function() {
detectfocus = "1";
});
codeeditor2.on('focus', function() {
detectfocus = "2";
});
codeeditor3.on('focus', function() {
detectfocus = "3";
});
undo.addEventListener('click', function() {
if (detectfocus === "1") {
codeeditor1.focus();
codeeditor1.undo();
} else if (detectfocus === "2") {
codeeditor2.focus();
codeeditor2.undo();
} else if (detectfocus === "3") {
codeeditor3.focus();
codeeditor3.undo();
}
}, false);
redo.addEventListener('click', function() {
if (detectfocus === "1") {
codeeditor1.focus();
codeeditor1.redo();
} else if (detectfocus === "2") {
codeeditor2.focus();
codeeditor2.redo();
} else if (detectfocus === "3") {
codeeditor3.focus();
codeeditor3.redo();
}
}, false);