Creating new toast via javascript - javascript

I'm trying to create a new toast via javascript using the bootstrap 5 toasts
so basically I searched everywhere and nothing showed up, I do not want to toggle or trigger an existing toast, all I want is to create one and show it
there are no javascript methods to create one, in bootstrap documentation, there is only create an Instance to initialize an existing one, is there a way?
https://getbootstrap.com/docs/5.2/components/toasts/
I appreciate all answers

The easiest way to completely create the toast with Javascript and not use an existing HTML element would be to use document.createElement() to create the HTML divs and then add the needed classes, as described here to it.
If you want to get the following:
<div class="toast show">
<div class="toast-header">
Toast Header
</div>
<div class="toast-body">
Some text inside the toast body
</div>
</div>
You would do this:
const toastContainer = document.createElement('div');
toastContainer.classList.add('toast', 'show');
const toastHeader = document.createElement('div');
toastHeader.classList.add('toast-header');
toastHeader.innerText = 'Toast Header';
const toastBody = document.createElement('div');
toastBody.classList.add('toast-body');
toastBody.innerText = 'Some text inside the toast body';
toastContainer.appendChild(toastHeader);
toastContainer.appendChild(toastBody);
document.body.appendChild(toastContainer);
Here I added the created divs to the body, but of course they can also be added to other divs.

i ended up doing this
const toastContainer =
`<div class="position-fixed top-0 end-0 p-3 z-index-3">
<div id="toast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
<div class="toast-header">
<span class="svg-icon svg-icon-2 svg-icon-primary me-3">...</span>
<strong class="me-auto">Toast Header</strong>
<small>11 mins ago</small>
<button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
</div>
<div class="toast-body">
Some text inside the toast body
</div>
</div>
</div>`;
document.body.insertAdjacentHTML('afterbegin', toastContainer);
test = document.getElementById('toast');
const toast = bootstrap.Toast.getOrCreateInstance(test);
toast.show();
If anyone has a more efficient or effective method, feel free to share it.

Related

How to set a specific keyword/password sent through textarea that trigger JavaScript if statement

That's my first ever question, and it's about my very first project, it's an online RPG Forum/PlayByChat game. I know it's kinda of an ambitious project.
So, i'm stuck from months into a problem that i feel i'm close to solve, premise (I'm self-taught).
The idea is to activate an if statement by a keyword/password given by an NPC, if there isn't no keyword in the message that it's supposed to be sent, then nothing should to happen.
That's what i've been able to put together and modify a little bit (it's not the entire code, just the interested parts), it works but it gets activated by any words or even by just one letter/empty messagges, i recently added the attribute "required" to the textarea so the field needs to be fill before to send messagges (even though it works only for the first click, then gives the possibility to send empty messagges which of course triggers the JoinedInTheRoom function) but anyway, that's a minor problem, the main problem remains that i cannot figured out how to make work the if statement inside the event listener under the JoinedInTheRoom function with a pre-chosen keyword/password, let's say "Mellon" (not case-sensitive if possible).
i'll explain myself better.
Let's say i'm gonna write "Mellon fellas" in the TextArea inside the Chat Log, my idea is to simply trigger the JoinedInTheRoom function by the fact that "Mellon", the keyword, has been just sent inside the messagge, i hope that my intent it's clear.
Thanks in advance.
here is the code:
HTML - CHAT LOG + TEXT AREA AND BUTTON
<!-- CHAT LOG -->
<h3>Chat Log</h3>
<div class="ChatLog">
<div class="msg left-msg">
<div class="msg-img" style="background-image: url()"></div>
<div class="msg-bubble">
<div class="msg-info">
<div class="msg-info-name">System</div>
</div>
<div class="msg-text">Write the Keyword to join the room and unlock the NPCs and Quests</div>
</div>
</div>
</div>
<!-- TEXT AREA AND BUTTON -->
<form class="FormInputArea">
<textarea class="InputCamp" id="TextArea" placeholder="Explain your move in max 200 characters..." required></textarea>
<button class="button" type="submit" id="SendButton"> Send </button>
</form>
JAVA SCRIPT - CHAT LOG + TEXT AREA AND BUTTON
// CHAT LOG + TEXT AREA AND BUTTON
const ChatLog = get(".ChatLog");
const FormInputArea = get(".FormInputArea");
const InputCamp = get(".InputCamp");
JAVA SCRIPT - JoinedInTheRoom + NpcsUnlocked
// JoinedInTheRoom + NpcsUnlocked
function JoinedInTheRoom(side) {
const NpcsUnlocked = `
<div class="msg ${side}-msg">
<div class="msg-img" style="background-image: url(${BOT_IMG})"></div>
<div class="msg-bubble">
<div class="msg-info">
<div class="msg-info-name">${BOT_NAME}</div>
<div class="msg-info-time">${formatDate(new Date())}</div>
</div>
<div class="msg-text">You've joined the room, feel free to choose your quest.</div>
</div>
</div>
<div class="msg ${side}-msg">
<div class="msg-img" style="background-image: url(${BOT_IMG})"></div>
<div class="msg-bubble">
<div class="msg-info">
<div class="msg-info-name">${BOT_NAME}</div>
<div class="msg-info-time">${formatDate(new Date())}</div>
</div>
<div class="msg-text">
<p onclick="Npc1('RANDOM TASK DESCRIPTION 1')"> Npc 1. </p>
<p onclick="Npc2('RANDOM TASK DESCRIPTION 2')"> Npc 2. </p>
</div>
</div>
</div>
`;
ChatLog.insertAdjacentHTML("beforeend", NpcsUnlocked);
ChatLog.scrollTop += 500;
}
FormInputArea.addEventListener("submit", event => {
event.preventDefault();
const NpcsUnlocked = InputCamp.value;
if (!NpcsUnlocked) return;
const Delay = NpcsUnlocked.split(" ").length * 600;
setTimeout(() => {
JoinedInTheRoom("left", NpcsUnlocked);
InputCamp.value = " ";
}, Delay);
})
JAVA SCRIPT - PLAYER MESSAGE SCRIPT
// PLAYER MESSAGE SCRIPT
function AppendMessage(name, img, side, text) {
const msgHTML = `
<div class="msg ${side}-msg">
<div class="msg-img" style="background-image: url(${img})"></div>
<div class="msg-bubble">
<div class="msg-info">
<div class="msg-info-name">${name}</div>
<div class="msg-info-time">${formatDate(new Date())}</div>
</div>
<div class="msg-text">${text}</div>
</div>
</div>
`;
ChatLog.insertAdjacentHTML("beforeend", msgHTML);
ChatLog.scrollTop += 500;
}
FormInputArea.addEventListener("submit", event => {
event.preventDefault();
const msgText = InputCamp.value;
if (!msgText) return;
AppendMessage(PERSON_NAME, PERSON_IMG, "right", msgText);
InputCamp.value = "";
});
Searching on internet i found this 11 years old stackoverflow post that i think it might help me, it seems i might use "indexOf" for this job, i'm right ? Maybe you guys can help me make it a little bit more "modern" and apply it to my code ?
Link
You could use the .includes function, like below
if (msgText.includes("mellon")) {
JoinedInTheRoom();
}
It'll search the whole string and return true if "mellon" is found. However it will also return true if someone types a word containing mellon. "smellon" or "smellonies" would return true and run the JoinedInTheRoom function too

How to get only one div to close when clicking close button on seperate divs?

I have to change in order to only get the separate preview window to close, not all that is opened at once. Have any tips?
function displayPreview(title, content) {
const previewContainer = document.createElement('div');
previewContainer.classList.add('preview-container');
previewContainer.insertAdjacentHTML('afterbegin',
`<div class="preview-modal">
<div class="preview-content">
<div class="preview-title">
<h3>${title}</h3>
</div>
<div class="preview-text">
<p>${content}</p>
</div>
<div class="preview-close">
<button class="preview-close-button">Close</button>
</div>
</div>
</div>`
);
document.body.appendChild(previewContainer);
const previewCloseButton = document.querySelector('.preview-close-button');
previewCloseButton.addEventListener('click', () => {
previewContainer.remove();
});
}
You need to confine the selector query for previewCloseButton to the appropriate scope rather than querying the entire document. This may work:
const previewCloseButton = previewContainer.querySelector('.preview-close-button');

Get first div after button is clicked

I have the following bit about shop info:
<h3 class="-center"><shop>Shop name</shop></h3>
<button type="button" id="banff" onclick="showShop(this.id)"><shop-title><b>Bakery Shop</b></shop-title></button>
<p class="move-right"><shop-info>Shop Address · Shop number</shop-info></p>
<div id="shop" class="hidden">
<p><shop-info>Opening soon</shop-info></p>
</div>
What I'm trying to do is that once the button is clicked, it will get the first div after the button and toggle the hidden class without referencing the id, there will be multiple shops so I am trying to create one function which will work for all of them rather than create an individual function for each.
I thought I could do something like:
function showShop(id) {
const elem = document.getElementById(id);
alert(id);
const div = elem.closest('div');
div.classList.toggle('hidden');
}
But it's referencing the first div on the page rather than the first one after the button, where have I gone wrong here? Or do I need to go about this a different way?
Thanks in advance for any advice
What about connecting the button id with the div id?
something like:
<h3 class="-center"><shop>Shop name</shop></h3>
<button type="button" id="button-1" onclick="showShop(this.id)">
<shop-title><b>Bakery Shop</b></shop-title>
</button>
<p class="move-right"><shop-info>Shop Address · Shop number</shop-info></p>
<div id="shop-button-1" class="hidden">
<p><shop-info>Opening soon</shop-info></p>
</div>
and in the javascript code would be possible to simplify to:
function showShop(id) {
const elem = document.getElementById(id);
const div = document.getElementById('shop-' + id);
div.classList.toggle('hidden');
}
You should try and avoid using ids as they are difficult to keep track of. Instead you should navigate relative to the clicked button. Below is a script that can easily take care of multiple shop sections without using any ids:
document.querySelectorAll("button").forEach(btn=>{
for(var div=btn;div=div.nextElementSibling;)
if(div.tagName==="DIV") break;
if(div) btn.onclick=()=>div.classList.toggle("hidden")
})
.hidden {display:none}
<h3 class="-center"><shop>Shop name</shop></h3>
<button><shop-title><b>Bakery Shop</b></shop-title></button>
<p class="move-right"><shop-info>Shop Address · Shop number</shop-info></p>
<div class="hidden">Info on bakery shop:
<p><shop-info>Opening soon</shop-info></p>
</div>
<button><shop-title><b>Iron Monger</b></shop-title></button>
<p class="move-right"><shop-info>Shop Address · Shop number</shop-info></p>
<div class="hidden">Info on iron monger's:
<p><shop-info>already open!</shop-info></p>
</div>
<button><shop-title><b>Fish Monger</b></shop-title></button>
<p class="move-right"><shop-info>Shop Address · Shop number</shop-info></p>
<div class="hidden">Info on fish monger's:
<p><shop-info>will never open!</shop-info></p>
</div>
In my latest update I tweaked the snippet again so that now I do the "relative navigation to the associated <div>" only once: at the time when I define and add the onclick eventlistener.

How do I insert content inside a filter button without duplicating

Is there a way of inserting content inside a filter button without duplicating it?
For example, if you see the content in this case "Hello world" is duplicated inside the filter collapse button.
The idea is to show content without a filter button on large and medium devices and collapsable on small devices, so user can collapse the content if required. This will save the length of the page and give good UX/UI.
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row">
<div class="col-6">
Hello world
</div>
<div class="col-6">
<hr>
<button type="button" class="btn btn-primary" data-toggle="collapse" data-target="#sidebar-collapse">Filter</button>
<div id="sidebar-collapse" class="collapse filter-collapse">
Hello world
</div>
</div>
</div>
This is a contrived example but you could maintain a variable with the text, and use window.matchMedia to check the device dimensions and dynamically add or remove that text. Something like:
function addText(query) {
const text = document.createTextNode("Hello world");
if (query.matches) {
document.body.style.backgroundColor = "yellow";
sidebar.appendChild(text);
desktop.innerText = '';
} else {
document.body.style.backgroundColor = "pink";
desktop.appendChild(text);
sidebar.innerText = '';
}
}
const desktop = document.getElementById('desktop-div');
const sidebar = document.getElementById('sidebar-collapse');
const query = window.matchMedia("(max-width: 350px)");
addText(query);
query.addListener(addText);
Here's the updated JSFiddle.
But I believe it is simpler to just keep duplicate text and hide or show it depending on the device using CSS media queries.

How to replace two class attribute in html content?

In my project, I fetch html content from DB with ajax, and these content will appear in web in div with id of timeTagDiv.
If My name is John, it should appears:
17:05:31 John translatetomaintanceGroup
letMnGrpmakeit
17:05:53 snow acceptSheet
17:06:04 snow translatetoleadGrp
leadercheckit
If my name is snow, it should appears:
17:05:31 John translatetomaintanceGroup
letMnGrpmakeit
17:05:53 snow acceptSheet
17:06:04 snow translatetoleadGrp
leadercheckit
Here is my ajax code:
var stChr="John";
var stTrnStr="translateto";
$.ajax({
......
success:function(data)
{
var $myHtml = $(data.stPrc);
$myHtml.find("label").filter(function(){
return $(this).text()===stChr;
}).parent().attr("class", "rightd");
//$myHtml.find('div:contains('+stChr+' '+stTrnStr+')').next().attr('class','rightd');
$('#timeTagDiv').html($myHtml);
}
});
Here is the content of data.stPrc from DB:
<div class="leftd">
<label>17:05:31</label>
<label>John</label>
<label> translateto</label>
<label>maintanceGroup</label>
</div>
<div class="leftd">
<div class="speech left" >letMnGrpmakeit</div>
</div>
<div class="leftd"><label>17:05:53</label>
<label>snow</label>
<label> acceptSheet</label>
</div>
<div class="leftd">
<label>17:06:04</label>
<label>snow</label>
<label> translateto</label>
<label>leadGrp</label>
</div>
<div class="leftd">
<div class="speech left" >leadercheckit</div>
</div>
When the context of label is John, the attribute class of parent div changed to rightd. Here is the code working successfully:
$myHtml.find("label").filter(function(){
return $(this).text()===stChr;
}).parent().attr("class", "rightd");
And then, the content of letMnGrpmakeit belongs to John should at the right side. So the next two divs class should be set class="rightd" and class="speech right".
In my example, before:
<div class="leftd">
<div class="speech left" >letMnGrpmakeit</div>
</div>
after replace:
<div class="rightd">
<div class="speech right" >letMnGrpmakeit</div>
</div>
I use :
$myHtml.find('div:contains('+stChr+' '+stTrnStr+')').next().attr('class','rightd');
$myHtml.find('div:contains('+stChr+' '+stTrnStr+')').next().next().attr('class','speech right');
But unfortunately, they both worked fail.
I have tried one condition:
$myHtml.find('label:contains('+stTrnStr+')').parent().next().attr('class','rightd');
It works, but it appears like:
17:05:31 John translatetomaintanceGroup
letMnGrpmakeit
17:05:53 snow acceptSheet
17:06:04 snow translatetoleadGrp
leadercheckit
"leadercheckit" should under "17:06:04 snow translatetoleadGrp", because it belongs to snow.
I have no idea about this. The key to change two div class are two conditions.
Who can help me?
I'm not sure I understand everything correctly because of wording and grammar, but I would suggest using addClass('className') and removeClass('className') instead. This way if your element has more than one class, it will only remove the desired class. By using .attr('class', 'className'), you're replacing everything. If you wish to add multiple classes, just use .addClass('class-1 class-2')
Use these:
$myHtml.find('label:contains('+stChr+')').next('label:contains('+stTrnStr+')').parent().next().attr('class','rightd');
$myHtml.find('label:contains('+stChr+')').next('label:contains('+stTrnStr+')').parent().next().children("div").eq(0).attr('class','speech right');

Categories