7

I need to display a toastr message within a particular div, class or id. By default it is body. I have figured out that I need to change the target. But I cannot seem to make it work.

Say for example I want to display toastr inside this div:

<showerror> </showerror>

This is the code I am using:

toastr.options = {
    "closeButton": false,
    "debug": false,
    "newestOnTop": false, 
    "progressBar": false, 
    "positionClass": "toast-top-right",
    "preventDuplicates": false, 
    "onclick": null,
    "showDuration": "300", 
    "hideDuration": "1000", 
    "timeOut": "5000", 
    "extendedTimeOut": "1000",
    "showEasing": "swing",
    "hideEasing": "linear",
    "showMethod": "fadeIn",
    "hideMethod": "fadeOut",
};

$('#submitform').submit(function(e){
    e.preventDefault(); 
    console.log($('#ques1').val());
    if($('#ques1').val()==null){
        toastr.error('Please select a question', 'Error!');
   }
});

Could anyone please help.

Bourbia Brahim
  • 14,459
  • 4
  • 39
  • 52
Ankan Kumar Giri
  • 243
  • 1
  • 3
  • 12

2 Answers2

6

It's simple just set the a new class name to "positionClass" inside toastr.options

toastr.options = { 
    ....
    "positionClass": "your-classname-here",
    ....
};

here is a Fiddle

Bourbia Brahim
  • 14,459
  • 4
  • 39
  • 52
  • I'm glad that helps you :) – Bourbia Brahim Feb 13 '17 at 18:48
  • actually that is not the answer to the question (which Im searching on my own) What ever class you provide with the "positionClass" is applied to the toastr. The container in your fiddle isnt used, but its class (width the positioning) is applies to the toastr, that is why it looks like it is displayed in you test container. But it isnt. – st'sahib Apr 12 '22 at 14:42
  • The answer by @st'sahib is actually the right answer, and not this one, please check below. – Adarsh Manickam Jun 29 '22 at 09:57
3

Old question, but if anyone comes across that problem: this is the real solution, while the marked answer only puts a class on toastr, this one makes the tostr really rendered inside a container and displays it in the top center of that container (instead of body)

toastr setup:

toastr.options = { 
    ....
    'positionClass': 'tostr_absolute toastr_top_center',
    'target'='.show_error';
    ....
};

Target can be any CSS selector. positionClass can be anything that helps you to style the toastr - it can be multiple classes, like in this example!

HTML markup:

<div class="show_error"></div>

        

CSS:

.show_error{
    position:relative;
}
.tostr_absolute{
    position: absolute !important;
}
.toastr_top_center {
    top: 0;
    right: 0;
    width: 100%;
}

the error-container needs to be positioned (relative), in order to get the toastr positioned absolute inside of it!

st'sahib
  • 163
  • 8
  • This is actually the right answer as the accepted answer just appends the class and doesn't actually render the toast inside the div we want. – Adarsh Manickam Jun 29 '22 at 09:56