The first version didn't consider system messages that are already there on page load (directly transfered with the HTML markup e.g. on the first GET of the corresponding page).
So the new version checks on page load if there are already messages present and if so appends the corresponding CSS class that the messages are displayed in a modal (here is also the place were the display: none comes in to play).
Moreover the event handling was updated so that we don't need to recreate the keyup event over and over again (for ESC) after each modal open and close.
This event is added once and kept persistent. The previous code flow was basically not necessary and overcomplicated so an additional condition was added to make things easier and more general.
Finally the whole modal open and modal close functionality was separated into two functions so that we can call them easily without code duplication. E.g. we need to call the openModal() code now twice, first on page load to ensure that already rendered message are displayed in a modal and second for dynamic messages that are generated by other JS code.
Additionally the CSS selectors and their strings were outsourced to variables so that the script can be adapted at one point for other similar scenarios in the future, that makes things a little more comfortable, maintainable and modifiable.