I have to make a chat widget movable. This chat widget is injected by an external script (SFDC Embedded Service, to be specific). Hence, I do not have access to the click handlers of the chat widget.
I am currently using event handlers of the embedded service to attach 'mousedown', 'mouseup' and 'mousemove' event listeners to the chat widget to make it movable.
While the widget is movable by dragging, upon mouseup, the mouseclick event is also triggered and the chat gets activated.
Can I avoid triggering the mouseclick event given the external nature of the widget?
I am also using react if that matters.
The chat widget is also attached directly onto the document body by the salesforce script, so a container is out of the question.
HTML:
<body>
<script async src='salesforce.com/esw.min.js' /> // external script that adds chat widget
</body>
rough representation of esw.min.js:
const chatWidget = <chat-widget />
chatWidget.addEventListener('click', openChat)
document.querySelector('body').append(chatWidget) // adds chat widget into body
my code:
const widgetObserver = new MutationObserver((mutations, observer) => {
const helpButton = document.querySelector('chat-widget');
if (helpButton) {
!helpButton.draggable && enableDragging(helpButton);
observer.disconnect();
}
});
function enableDragging(element) {
var displacedX = 0,
displacedY = 0,
currentX = 0,
currentY = 0;
// otherwise, move the DIV from anywhere inside the DIV:
element.onmousedown = dragMouseDown;
element.style.right = currentX + 'px';
element.style.bottom = currentY + 'px';
element.draggable = true;
function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
// get the mouse cursor position at startup:
currentX = e.clientX;
currentY = e.clientY;
document.onmouseup = closeDragElement;
// call a function whenever the cursor moves:
document.onmousemove = elementDrag;
}
function elementDrag(e) {
e.preventDefault();
// calculate the new cursor position:
displacedX = currentX - e.clientX;
displacedY = currentY - e.clientY;
currentX = e.clientX;
currentY = e.clientY;
// set the element's new position:
element.style.top = element.offsetTop - displacedY + 'px';
element.style.left = element.offsetLeft - displacedX + 'px';
}
function closeDragElement() {
// stop moving when mouse button is released:
document.onmouseup = null;
document.onmousemove = null;
}
}