Javascript "onmousedown" isn't firing

Viewed 75

I'm trying to run a function on an element "onmousedown". Here's the code:

<label class="switch">
     <input type="checkbox" onmousedown="console.log('Run the function'); 
            manageBook(this);"  id="element-id-52"  data-mode= "offx">
     <span class="slider round"></span>
</label>

But when I click the slider, I don't see either the console.log() message or the function running. Any idea what could be causing this?

3 Answers

since mouse down is only on input element only that will listen to event, if you move mouse down to <label class="switch"> then the event from child elements will also bubble up to the element and that cover down event for all 3 elements

Try adding the listener to the label instead of input element.

<label
  class="switch"
  onmousedown="console.log('Run the function'); manageBook(this);
>

Inputs onmousedown is working good, you can move your listener to the parent block to get success

const manageBook=(input)=>{
    console.log('manage book', input);
};

const withSpan=(a)=>{
    console.log('with span', a);
};
<label class="switch" onmousedown="withSpan(this);">
    <input type="checkbox" onmousedown="console.log('Run the function');manageBook(this);" id="element-id-52" data-mode="offx">
    <span class="slider round">aaaa</span>
</label>

Related