Why does the Click event fire on page load?

  • 0
    There is html code like this:
    <div class="click_number_header" onclick="ga('send', 'event', 'click_number_header', 'click', 'Click number header');">
        057-098-28
        <span class="num_hide">-52</span>
        <span class="sh_nmr">показать</span>
    </div>

    And JS:
    jQuery(document).ready(function($){
      $.fn.textToggle = function(cls, str) {
        return this.each(function(i) {
          $(this).click(function() {
            var c = 0, el = $(cls).eq(i), arr = [str,el.text()];
            return function() {
              el.text(arr[c++ % arr.length]);
            }
          }());
        })
      };
      $(function(){
        $('.sh_nmr').textToggle(".sh_nmr","").click();
        $('.sh_nmr').textToggle(".num_hide","ХХХ").click();
      });
    });

    The essence of the code is to hide part of the number when the page loads, in order to track the number of clicks on the phone number in Google analytics. The code hides the number perfectly, but for some reason the onclick event in the block is also triggered on page load.
    <div class="click_number_header" onclick="ga('send', 'event', 'click_number_header', 'click', 'Click number header');">

    What could be wrong?
    JavaScript Ezra Collier, May 30, 2019

  • 2 Answers
  • 0
    You click on the spans from below, here the event pops up to your onclick.



    $('.sh_nmr').textToggle(".sh_nmr","").click();
    $('.sh_nmr').textToggle(".num_hide","ХХХ").click();




    You can add the click event manually after clicks on the span.

    $('.click_number_header').on("click" , () => ga('send', 'event', 'click_number_header', 'click', 'Click number header'));
    Scarlett Butler

  • 0
    I don't quite understand the logic, but:

    1) why do "auto-clicks" when loading a page? Why not just call the function you want?

    2) if you really need to "autoclick", use stopPropagation so that "yellow submarine" does not pop up))
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!