0

Some had this problem but I did not see any answer that fits mine.

Here is the html :

<div id="page">
  ......
  <ul>
    <li role="presentation">
      <a id="selection"...... ></a>
    </li>
    <li role="presentation>
      <a id="xxxx"></a>
    </li>
    <li role="presentation">
      <a id="yyyyy"></a>
    </li>
  </ul>
 .......
</div>

here is the javascript using Mootools (no choice) :

window.addEvent('domready', function() {
   var myDivPage = document.id('page');
   var as = myDivPage.getElements('li[role=presentation] a');

   //as is an array of 3 elements

   Array.each(as, function(element, index) {
      if(element.id !== 'selection') {
            element.addEvent("click", function(event) {
                event.preventDefault();
                event.stopPropagation();
                alert("did you save?");
            });
       } 
   });

 });

The event is indeed attached but when I click my link the alrt is displayed twice, as though the event occured twice. As you can see I stopped the propagation, so how could this happen ?

Thank you

mlwacosmos
  • 4,391
  • 16
  • 66
  • 114
  • What's about adding `stopImmediatePropagation` instead of `stopPropagation` – Madhu Magar Nov 15 '19 at 15:24
  • I don't have Mootools, so testing your example is out of the question for me. Have you tried putting a console.log(...) line inside the start of each new scope to see how many times each gets called? You might be inserting your event handler more than once. One possible solution would be to clear existing onclick handlers, but you need either a named click handler or clone the element to be able to do that with plain vanilla javascript. https://stackoverflow.com/a/9251864/9035707 -- The better option would be to figure out why it's getting added twice. – FlippingBinary Nov 15 '19 at 15:32

2 Answers2

0

The below if condition is inside a loop.

if(element.id !== 'selection')

The check is made for each element.id which is not equal to selection. So how many times, if condition is true? 2 One for id="xxxx" and other for id="yyyyy"

For click event to be triggered only once use

if(element.id === 'selection')
Vinit Desai
  • 520
  • 1
  • 4
  • 20
0

The code as displayed seems fine. Verify that your event handler isn't actually added twice (place an alert just before your Array.each loop)

$$('#page li[role=presentation] a:not(#selection)').addEvent("click",
   function(event) { event.stop(); alert("Did you save?"); })

would be a more mootools-y way of doing this though.

unilynx
  • 456
  • 3
  • 10