Error message. My version.

    Recently, I wanted to make sure that my project would display errors exactly where they were committed. Those. if you entered the e-mail incorrectly, then the error should be displayed just next to the “input” for entering the e-mail. So what's the problem? To write directly under this "input" and all. Not! And if there is not enough space? This is precisely the situation that has arisen in me, in some places there is simply nowhere to "blame" the error because of the lack of space for it.

    In this regard, we understand that we need to use a semblance of JavaScript's “alert”. I know, “alert” is not kosher. Therefore, a pop-up-floating “div” is needed, moreover, tied to the place where the error was committed.

    After searching a bit among the plugins for "jQuery" I did not find anything worthwhile. Either I searched poorly, or there really is nothing suitable. Therefore, please take a look at my option:



    The function itself:
    function showError(e, message) {
      if (message.length < 1) {
        return false;
      }
      eOffset = $(e).offset();
      eBox  = $('#error_Box').clone();
      eBoxId = $(e).attr('id') + '_Error';
      $(eBox).attr({ id: eBoxId });
      $(eBox).css({ top: eOffset.top + 13, left: eOffset.left + 25, display: '' }).text(message).prependTo('body');
      $(eBox).bind('click', function() {
        $(this).remove();
      });
    }

    * This source code was highlighted with Source Code Highlighter.


    Pop-up "div":


    * This source code was highlighted with Source Code Highlighter.


    The function is passed an “e” - the object (DOM element) to which the error will be attached, and “message” - an error message that will be displayed to the user.

    In turn, the function determines the location (coordinates) of the object, clones the already existing "div" and attaches it (visually) to the scene.

    Here is the result of this function:
    image

    When you click on an error, the "div" is destroyed.

    PS My knowledge of JavaScript is enough only to indulge. Therefore, any constructive criticism is welcome.

    Also popular now: