javascripthtml

OnClick works only once


HTML:

<svg id="settings-icon" xmlns="http://www.w3.org/2000/svg" height="90px" viewBox="0 -960 960 960" width="40px" fill="#FFF"><path d="(thepath)" onclick='settings()'></svg>

JS:

function settings() {alert("hello")}

The alert only happens the first time when clicked. Afterwards I would need to reload then the alert will show again. Or not the alert wouldn't show after the first time.

Help greatly appreciated.

EDIT: it works but only sometimes. when i click theres bout a 50% chance it alerts


Solution

  • I think here issue with the DOM. Try to edit the code like this

    <svg id="settings-icon" xmlns="http://www.w3.org/2000/svg" height="90px" viewBox="0 -960 960 960" width="40px" fill="#FFF"><path d="(thepath)"></path></svg>

    JS,

    document.getElementById('settings-icon').addEventListener('click', settings);
    
    function settings() {
        alert("hello");
    }