Event listener added on click but runs straight away?How do I detect a click outside an element?Trigger a button click with JavaScript on the Enter key in a text boxEvent binding on dynamically created elements?How do I prevent a parent's onclick event from firing when a child anchor is clicked?How to get the data-id attribute?jQuery click events firing multiple timesJavaScript click event listener on classHow to access the correct `this` inside a callback?AngularJS ng-click stopPropagationReact js onClick can't pass value to method

Can I cast reaction spells like Shield or Counterspell when I'm in the middle of casting a spell with a long casting time and don't stop casting it?

How risky is real estate?

How to get cool night-vision without lame drawbacks?

Inverse-quotes-quine

Layout of complex table

Intuitively, why does putting capacitors in series decrease the equivalent capacitance?

What are the penalties for overstaying in USA?

Story-based adventure with functions and relationships

Declining an offer to present a poster instead of a paper

Cascading Repair Costs following Blown Head Gasket on a 2004 Subaru Outback

Are Finite Automata Turing Complete?

How important is payoff?

How can I convince my reader that I will not use a certain trope?

Does Marvel have an equivalent of the Green Lantern?

Gare du Nord to Gare de Lyon transfer time for a family

Going to get married soon, should I do it on Dec 31 or Jan 1?

MH370 blackbox - is it still possible to retrieve data from it?

Why aren't (poly-)cotton tents more popular?

Analog is Obtuse!

How to append a matrix element by element?

Do equal angles necessarily mean a polygon is regular?

Is my Rep in Stack-Exchange Form?

Links to webpages in books

Can ADFS connect to other SSO services?



Event listener added on click but runs straight away?


How do I detect a click outside an element?Trigger a button click with JavaScript on the Enter key in a text boxEvent binding on dynamically created elements?How do I prevent a parent's onclick event from firing when a child anchor is clicked?How to get the data-id attribute?jQuery click events firing multiple timesJavaScript click event listener on classHow to access the correct `this` inside a callback?AngularJS ng-click stopPropagationReact js onClick can't pass value to method






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








7















I add an event on click of my button:



this.$refs.btn.addEventListener('click', this.turnOn);


In the turnOn method I add a listener on the document, to run the turnOff method.



turnOn() 
document.addEventListener('click', this.turnOff);



Then during testing, I click the button and the turnOn method runs, but that initial click also runs the document click listener.



How can I run the turnOn method, add the document listener, but not run the document click listener on the initial button click?










share|improve this question






















  • you are adding 2 addEventListener?

    – brk
    Mar 25 at 11:04











  • 2 event listeners for 2 different elements.

    – panthro
    Mar 25 at 11:06











  • do you mind explaining what you have and what you want to do

    – brk
    Mar 25 at 11:08

















7















I add an event on click of my button:



this.$refs.btn.addEventListener('click', this.turnOn);


In the turnOn method I add a listener on the document, to run the turnOff method.



turnOn() 
document.addEventListener('click', this.turnOff);



Then during testing, I click the button and the turnOn method runs, but that initial click also runs the document click listener.



How can I run the turnOn method, add the document listener, but not run the document click listener on the initial button click?










share|improve this question






















  • you are adding 2 addEventListener?

    – brk
    Mar 25 at 11:04











  • 2 event listeners for 2 different elements.

    – panthro
    Mar 25 at 11:06











  • do you mind explaining what you have and what you want to do

    – brk
    Mar 25 at 11:08













7












7








7








I add an event on click of my button:



this.$refs.btn.addEventListener('click', this.turnOn);


In the turnOn method I add a listener on the document, to run the turnOff method.



turnOn() 
document.addEventListener('click', this.turnOff);



Then during testing, I click the button and the turnOn method runs, but that initial click also runs the document click listener.



How can I run the turnOn method, add the document listener, but not run the document click listener on the initial button click?










share|improve this question














I add an event on click of my button:



this.$refs.btn.addEventListener('click', this.turnOn);


In the turnOn method I add a listener on the document, to run the turnOff method.



turnOn() 
document.addEventListener('click', this.turnOff);



Then during testing, I click the button and the turnOn method runs, but that initial click also runs the document click listener.



How can I run the turnOn method, add the document listener, but not run the document click listener on the initial button click?







javascript






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 25 at 11:02









panthropanthro

7,60934 gold badges116 silver badges218 bronze badges




7,60934 gold badges116 silver badges218 bronze badges












  • you are adding 2 addEventListener?

    – brk
    Mar 25 at 11:04











  • 2 event listeners for 2 different elements.

    – panthro
    Mar 25 at 11:06











  • do you mind explaining what you have and what you want to do

    – brk
    Mar 25 at 11:08

















  • you are adding 2 addEventListener?

    – brk
    Mar 25 at 11:04











  • 2 event listeners for 2 different elements.

    – panthro
    Mar 25 at 11:06











  • do you mind explaining what you have and what you want to do

    – brk
    Mar 25 at 11:08
















you are adding 2 addEventListener?

– brk
Mar 25 at 11:04





you are adding 2 addEventListener?

– brk
Mar 25 at 11:04













2 event listeners for 2 different elements.

– panthro
Mar 25 at 11:06





2 event listeners for 2 different elements.

– panthro
Mar 25 at 11:06













do you mind explaining what you have and what you want to do

– brk
Mar 25 at 11:08





do you mind explaining what you have and what you want to do

– brk
Mar 25 at 11:08












1 Answer
1






active

oldest

votes


















10














This is due to event bubbling.When you click on <button> an eventListener is attached to body and after that due bubbling its called.
You can prevent that using event.stopPropgation(). Below are two snippets to see the difference.



Non-Working






document.querySelector('button').addEventListener('click',(e)=>
document.addEventListener('click',()=>console.log("body clicked"));
console.log("button clicked")
)

<body>
<button>Test</button>
</body>





Note: The above non-working example also adds multiple click events on each click on Test



Working






document.querySelector('button').addEventListener('click',(e)=>
e.stopPropagation();
document.addEventListener('click',()=>console.log("body clicked"));
console.log("button clicked")
)

<body>
<button>Test</button>
</body>








share|improve this answer

























  • Great answer, with great example. Thanks.

    – panthro
    Mar 25 at 11:11













Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55336347%2fevent-listener-added-on-click-but-runs-straight-away%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









10














This is due to event bubbling.When you click on <button> an eventListener is attached to body and after that due bubbling its called.
You can prevent that using event.stopPropgation(). Below are two snippets to see the difference.



Non-Working






document.querySelector('button').addEventListener('click',(e)=>
document.addEventListener('click',()=>console.log("body clicked"));
console.log("button clicked")
)

<body>
<button>Test</button>
</body>





Note: The above non-working example also adds multiple click events on each click on Test



Working






document.querySelector('button').addEventListener('click',(e)=>
e.stopPropagation();
document.addEventListener('click',()=>console.log("body clicked"));
console.log("button clicked")
)

<body>
<button>Test</button>
</body>








share|improve this answer

























  • Great answer, with great example. Thanks.

    – panthro
    Mar 25 at 11:11















10














This is due to event bubbling.When you click on <button> an eventListener is attached to body and after that due bubbling its called.
You can prevent that using event.stopPropgation(). Below are two snippets to see the difference.



Non-Working






document.querySelector('button').addEventListener('click',(e)=>
document.addEventListener('click',()=>console.log("body clicked"));
console.log("button clicked")
)

<body>
<button>Test</button>
</body>





Note: The above non-working example also adds multiple click events on each click on Test



Working






document.querySelector('button').addEventListener('click',(e)=>
e.stopPropagation();
document.addEventListener('click',()=>console.log("body clicked"));
console.log("button clicked")
)

<body>
<button>Test</button>
</body>








share|improve this answer

























  • Great answer, with great example. Thanks.

    – panthro
    Mar 25 at 11:11













10












10








10







This is due to event bubbling.When you click on <button> an eventListener is attached to body and after that due bubbling its called.
You can prevent that using event.stopPropgation(). Below are two snippets to see the difference.



Non-Working






document.querySelector('button').addEventListener('click',(e)=>
document.addEventListener('click',()=>console.log("body clicked"));
console.log("button clicked")
)

<body>
<button>Test</button>
</body>





Note: The above non-working example also adds multiple click events on each click on Test



Working






document.querySelector('button').addEventListener('click',(e)=>
e.stopPropagation();
document.addEventListener('click',()=>console.log("body clicked"));
console.log("button clicked")
)

<body>
<button>Test</button>
</body>








share|improve this answer















This is due to event bubbling.When you click on <button> an eventListener is attached to body and after that due bubbling its called.
You can prevent that using event.stopPropgation(). Below are two snippets to see the difference.



Non-Working






document.querySelector('button').addEventListener('click',(e)=>
document.addEventListener('click',()=>console.log("body clicked"));
console.log("button clicked")
)

<body>
<button>Test</button>
</body>





Note: The above non-working example also adds multiple click events on each click on Test



Working






document.querySelector('button').addEventListener('click',(e)=>
e.stopPropagation();
document.addEventListener('click',()=>console.log("body clicked"));
console.log("button clicked")
)

<body>
<button>Test</button>
</body>








document.querySelector('button').addEventListener('click',(e)=>
document.addEventListener('click',()=>console.log("body clicked"));
console.log("button clicked")
)

<body>
<button>Test</button>
</body>





document.querySelector('button').addEventListener('click',(e)=>
document.addEventListener('click',()=>console.log("body clicked"));
console.log("button clicked")
)

<body>
<button>Test</button>
</body>





document.querySelector('button').addEventListener('click',(e)=>
e.stopPropagation();
document.addEventListener('click',()=>console.log("body clicked"));
console.log("button clicked")
)

<body>
<button>Test</button>
</body>





document.querySelector('button').addEventListener('click',(e)=>
e.stopPropagation();
document.addEventListener('click',()=>console.log("body clicked"));
console.log("button clicked")
)

<body>
<button>Test</button>
</body>






share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 27 at 17:02

























answered Mar 25 at 11:08









Maheer AliMaheer Ali

21.8k4 gold badges19 silver badges37 bronze badges




21.8k4 gold badges19 silver badges37 bronze badges












  • Great answer, with great example. Thanks.

    – panthro
    Mar 25 at 11:11

















  • Great answer, with great example. Thanks.

    – panthro
    Mar 25 at 11:11
















Great answer, with great example. Thanks.

– panthro
Mar 25 at 11:11





Great answer, with great example. Thanks.

– panthro
Mar 25 at 11:11



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55336347%2fevent-listener-added-on-click-but-runs-straight-away%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해