How to add javascript snippet into my app?

Hi all.

I just wanted to reply that I had the same issue and I solved it by creating an event listener to listen for clicks, then run a function to show/hide a div if a header was clicked:

function toggle(id) {
    var state = document.getElementById(id).style.display;
    if (state == 'block') {
        document.getElementById(id).style.display = 'none';
    } else {
        document.getElementById(id).style.display = 'block';
    }
}

window.addEventListener("click", () => {
    let thedesctitle = document.getElementById('purpose-title');
    thedesctitle.setAttribute("onclick","toggle('purpose-div');");
});

I hope this helps you all with adding JS functions to Dash/Plotly apps!

Edit: I changed the ā€˜setAttributeā€™ line.

Been trying to do this myself and came up with a JS way to get it working

/**
 *
 * @param {string} id
 * @param {*} event
 * @param {(this: HTMLElement, ev: any) => any} callback
 * @param {boolean | AddEventListenerOptions} options
 */
function attachEventToDash(id, event, callback, options) {
	debugger;
	var observer = new MutationObserver(function (_mutations, obs) {
		var ele = document.getElementById(id);
		if (ele) {
			debugger;
			ele.addEventListener(event, callback, options)
			obs.disconnect();
		}
	});
	window.addEventListener('DOMContentLoaded', function () {
		observer.observe(document, {
			childList: true,
			subtree: true
		});
	})
}

Now you just attach event using element ID and adding your js into assets folder.

1 Like