Q:

How do I stopPropagation when changing an event inside an event?

So I have got the following javascript code:
function showSearch() {
    var ev = new Event("onkeydown");
    ev.keyCode = 13;
    document.getElementById("search").onclick = search(ev);
}

The function showSearch() is called in the onclick-event of the Element #search. So when assigning the new event, the new one triggers immediately.
I want to prevent that using stopPropagation().
How do I do that? How else could I solve this?

A:

onclick accepts a function as a parameter - you're providing it undefined (the result of showSearch() ; your current showSearch(), being a function call, executes immediately. Assign onclick a function instead of a function call:

document.getElementById("search").onclick = showSearch;
const search = () => console.log('searching');
function showSearch() {
    var ev = new Event("onkeydown");
    ev.keyCode = 13;
    document.getElementById("search").onclick = () => search(ev);
}
<div id="search">text</div>

But using on-handlers is pretty bad practice. It would be better to add an event listener instead:

const searchDiv = document.getElementById("search");
searchDiv.addEventListener('click', showSearch);
const search = () => console.log('searching');
function showSearch() {
    var ev = new Event("onkeydown");
    ev.keyCode = 13;
    searchDiv.removeEventListener('click', showSearch);
    searchDiv.addEventListener('click', () => search(ev));
}
<div id="search">text</div>

