最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Javascript - create and destroy a toast message - Stack Overflow

programmeradmin1浏览0评论

I want to create a toast notification in javascript. When the user has done fine, a message box (the toast) should appear with a green color and the text "successfull" or whatever.

If not, the color is red and the text should be "failure". This div should be sliding from the top of the center of the screen, stay for 3 sec and after that, it should be removed from the DOM.

I got this one here, to create my div

CreateToast(isValid) { // Toast notification
        var toastDiv = document.createElement("div");
        var toastMessage;
        var foreColor;
        var backgroundColor;
        var borderColor;

        if (!isValid) {
            toastMessage = "Failure";
            foreColor = "";
            backgroundColor = "";
            borderColor = "";
        } else {
            toastMessage = "Success";
            foreColor = "";
            backgroundColor = "";
            borderColor = "";
        }

        toastDiv.innerHTML = toastMessage;
        document.body.appendChild(toastDiv);
    }

But what I don't know is, how to setup the rest of it. Where to place it, how it slides down from the top center etc.

I know, I can delete the div by using

toastDiv.remove(); // Delete the element from the DOM

but how to use it when it es to "Destroy it after 3 sec" ?

I want to create a toast notification in javascript. When the user has done fine, a message box (the toast) should appear with a green color and the text "successfull" or whatever.

If not, the color is red and the text should be "failure". This div should be sliding from the top of the center of the screen, stay for 3 sec and after that, it should be removed from the DOM.

I got this one here, to create my div

CreateToast(isValid) { // Toast notification
        var toastDiv = document.createElement("div");
        var toastMessage;
        var foreColor;
        var backgroundColor;
        var borderColor;

        if (!isValid) {
            toastMessage = "Failure";
            foreColor = "";
            backgroundColor = "";
            borderColor = "";
        } else {
            toastMessage = "Success";
            foreColor = "";
            backgroundColor = "";
            borderColor = "";
        }

        toastDiv.innerHTML = toastMessage;
        document.body.appendChild(toastDiv);
    }

But what I don't know is, how to setup the rest of it. Where to place it, how it slides down from the top center etc.

I know, I can delete the div by using

toastDiv.remove(); // Delete the element from the DOM

but how to use it when it es to "Destroy it after 3 sec" ?

Share asked Apr 25, 2017 at 14:18 peterHasemannpeterHasemann 1,5904 gold badges26 silver badges60 bronze badges 2
  • For destroying, at the trigger event... you could use setTimeout(.... function. – Exception_al Commented Apr 25, 2017 at 14:20
  • instead of adding style attributes - which just blows ur script, i would rather set classes and style them with css... e.g. all your toasts go into a wrapper (e.g. with the class .js-toasts) this one you can place anywhere. each toast gets a class (e.g. .js-toasts__item (BEM)) + add a class for success + fail ;) – MarcelD Commented Apr 25, 2017 at 14:34
Add a ment  | 

3 Answers 3

Reset to default 6

Since you tagged jQuery to your question, I assume you want to use some jQuery methods.

So this is the basic example: (I'm sure you will be able to style it as you wish)
To each created div, you have to assign a unique id in order to be able to make it slideDown() and to .remove() it.

So I added a toastCounter to create this id.

var toastCounter=0;

function CreateToast(isValid) { // Toast notification
  
  var toastDiv = document.createElement("div");
  
  // Give it a unique id
  toastDiv.id = "toast_"+toastCounter;
  
  // Make it hidden (necessary to slideDown)
  toastDiv.style.display = "none";
  
  var toastMessage;
  var foreColor;
  var backgroundColor;
  var borderColor;

  if (!isValid) {
    toastMessage = "Failure";
    foreColor = "";
    backgroundColor = "";
    borderColor = "";
  } else {
    toastMessage = "Success";
    foreColor = "";
    backgroundColor = "";
    borderColor = "";
  }

  toastDiv.innerHTML = toastMessage;
  document.body.appendChild(toastDiv);
  
  // Increment toastCounter
  toastCounter++;
}



$("#test1").on("click",function(){
  CreateToast(true);
  var thisToast = toastCounter-1;
  
  // Make it slide down
  $(document).find("#toast_"+thisToast).slideDown(600);
  
  setTimeout(function(){
    $(document).find("#toast_"+thisToast).slideUp(600,function(){   // Slideup callback executes AFTER the slideup effect.
      $(this).remove();
    });
  },3000);  // 3sec.
});

$("#test2").on("click",function(){
  CreateToast(false);
  var thisToast = toastCounter-1;
  
  // Make it slide down
  $(document).find("#toast_"+thisToast).slideDown(600);
  
  setTimeout(function(){
    $(document).find("#toast_"+thisToast).slideUp(600,function(){   // Slideup callback executes AFTER the slideup effect.
      $(this).remove();
    });
  },3000);  // 3sec.
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="test1">TRUE</button>
<button id="test2">FALSE</button>

I think based on your requirements you should take a look at the toastr library. I use it myself for several projects and it has a great API which allows a lot of customization.

See: https://github./CodeSeven/toastr

You can show toast with JsFrame.js like below.

https://riversun.github.io/jsframe/examples/v150/toast_simple.html

<!DOCTYPE html>
<html>
<body>
<script src="https://riversun.github.io/jsframe/jsframe.js"></script>
<script>
    const jsFrame = new JSFrame();
    jsFrame.showToast({
        html: 'This is a simple toast', align: 'top', duration: 2000
    });
</script>
</body>
</html>

Here is the library. https://github./riversun/JSFrame.js

发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>