I've added a button which have aria-label attribute set and an event listener is added to that button.
<button onClick: toggleFavourite(),
aria-label = "favourite button label">
</button>
Now on JavaScript side, I've written code on toggleFavourite() method call where I'll create a <div> and append it to the body and for that div I've set the "aria-live" property to "Assertive". Below is the code for that.
toggleFavourite(): void {
var el = document.createElement("div");
var id = "speak-" + Date.now();
el.setAttribute("id", id);
el.setAttribute("aria-live", "assertive");
el.classList.add("visually-hidden");
document.body.appendChild(el);
var newelem = document.getElementById(id);
setTimeout(() => {
if (newelem != null) {
newelem.innerHTML = "this label should be read first";
}
}, 100);
setTimeout(() => {
if (newelem != null) {
document.body.removeChild(newelem);
}
}, 1000);
}
Tried above solution but it was still reading the button label first and then the message defined in toggleFavourite() method. How to change this order i.e. read the message written in method first and label after?
It's not clear what your timing of interactions is. If you tab to the button, you should hear "favourite button label, button". Period. That's all you should hear.
After tabbing to the button, when you select it, new content is added. That new content might be announced. Live regions that are dynamically added have spotty support with various browser and screen reader combinations. It's generally recommended that live regions exist on the page and then you add content to the live region. See one of my previous answers about live regions.
This is the confusing part of your question. The button label and the newly added text are separate things. Why should they both be announced?