javascript - Why is the order of alert reversed? -


this question has answer here:

why following code show "three" "two"and "one" (in order)? function or table? expecting output one, two, 3 , not other way around.

<html>     <head>         <title>webdev exams</title>          </head>     <body>           <div id='one'>             <table>                 <tr id='two'>                     <td id='three'>ce1111</td>                 </tr>             </table>         </div>     </body>     <script type="text/javascript">         function registerevent(id) {             document.getelementbyid(id).addeventlistener('click', function()             {                 alert(id);             });         }         registerevent('one');         registerevent('two');         registerevent('three');     </script>    </html> 

dom level 3 events , javascript event order specification allows register event listener either in capturing or in bubbling phase.

but default, bubbling phase used.
means more depth element associated listener first notified , closest ancestor element of notified element associated same listener notified, , on...
whereas actual behavior.

to use bubbling phase behavior has reverse behavior, have specify second argument (usecapture) of eventtarget.addeventlistener() true. official documentation :

usecapture optional

a boolean indicating events of type dispatched registered listener before being dispatched eventtarget beneath in dom tree. events bubbling upward through tree not trigger listener designated use capture. event bubbling , capturing 2 ways of propagating events occur in element nested within element, when both elements have registered handle event. event propagation mode determines order in elements receive event

you update method in way :

function registerevent(id) {     document.getelementbyid(id).addeventlistener('click', function()     {         alert(id);     },true); } 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -