简体   繁体   中英

Trying to rewrite a deprecated jquery function fn.click()

I'm working on updating jQuery for a really old wordpress site. I have the function below that I'm trying to rewrite:

 $(".smscroll").click(function(event){ event.preventDefault(); // CALCULATE DESTINATION PLACE var dest = 0; if ($(this.hash).offset().top > ($(document).height() - $(window).height())) { dest = $(document).height() - $(window).height(); } else { dest = $(this.hash).offset().top; } // GO TO DESTINATION $('html,body').animate({scrollTop:dest}, 1000, 'swing'); });

I realize that .click is deprecated. So, I'm trying to replace it with the following:

 $(document).on("click", ".smscroll", function(event){ event.preventDefault(); // CALCULATE DESTINATION PLACE var dest = 0; if ($(this.hash).offset().top > ($(document).height() - $(window).height())) { dest = $(document).height() - $(window).height(); } else { dest = $(this.hash).offset().top; } // GO TO DESTINATION $('html,body').animate({scrollTop:dest}, 1000, 'swing'); });

What else do i need to clean up to get rid of the deprecation?

It appears that your code no longer contains deprecated functionality, although $(document).on('click', scope, callback) is redundant. Use $(scope).on('click', callback) like so:

 $(".smscroll").on("click", function(event) { event.preventDefault(); var dest = 0; if ($(this.hash).offset().top > ($(document).height() - $(window).height())) { dest = $(document).height() - $(window).height(); } else { dest = $(this.hash).offset().top; } $('html,body').animate({ scrollTop: dest }, 1000, 'swing'); });

Assuming of course that the event listener is applied after all the .smscroll elements that need to ever be selected have been loaded. Of course, don't use this if your aim is to delegate the click event to the .smscroll class.

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