简体   繁体   中英

Reset a run once function

I am working with facebook pixel code to determine when a user has read the entire article. I have an infinite blog so the URL changes as the user scrolls down the page. I current have a function to run once when the user gets to the end of the page but I need to modify it so if the URL changes the function is reset and can run again. here is my current code.

// determine the position of element
jQuery.fn.isInViewport = function() {
  var elementTop = jQuery(this).offset().top;
  var elementBottom = elementTop + jQuery(this).outerHeight();
  var viewportTop = jQuery(window).scrollTop();
  var viewportBottom = viewportTop + jQuery(window).height();
  return elementBottom > viewportTop && elementTop < viewportBottom;
};

// grab the current URL
var originalURL = window.location.href;

// check to see if element is in viewport
jQuery(window).on('resize scroll', function() {

  var currentURL = '';

  jQuery('.end-of-content-icon').each(function() {

    if (jQuery(this).isInViewport()) {

      currentURL = window.location.href;

      if(originalURL !== currentURL) {

        canOnlyFireOnce();

        originalURL = currentURL;

      }
    }
  });
});

// function to only fire once (courtesy of David Walsh)
function once(fn, context) { 
  var result;

  return function() { 
    if(fn) {
      result = fn.apply(context || this, arguments);
      fn = null;
    }

    return result;
  };
}

// Usage
var canOnlyFireOnce = once(function() {

  fbq('track', 'Lead');

});

Solved it with a different function. I pass the permalink through and add it to an array. If the permalink does not already exist in the array the variable 'triggerOnce' is set reset to true and the function runs.

var triggerOnce = true;
var permalinkArray = [];
function callFaceBookPixel(permalink){

  if(permalinkArray.indexOf(permalink) === -1) {
    permalinkArray.push(permalink);
    triggerOnce = true;
  }

  if(triggerOnce){
    triggerOnce = false;
    fbq('track', 'Lead');
  }
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM