Execute window on load only if class exists

I’m in need of executing $(window).on('load', function() only if a certain class exists in a DOM element (div).

My current code is as follows:

jQuery(document).ready(function($) {
    if (window.innerWidth > 767) {
  var $sticky = $('#sticky');
  var $stickyrStopper = $('.footer');
  if (!!$sticky.offset()) { // make sure ".sticky" element exists
    var generalSidebarHeight = $sticky.innerHeight();
    var stickyTop = $sticky.offset().top;
    var stickOffset = 0;
    var stickyStopperPosition = $stickyrStopper.offset().top;
    var stopPoint = stickyStopperPosition - generalSidebarHeight - stickOffset;
    var diff = stopPoint + stickOffset;
    $(window).scroll(function(){ // scroll event
      var windowTop = $(window).scrollTop(); // returns number
      //////////////
      if (stopPoint < windowTop) {
          $sticky.css({ position: 'absolute', top: diff });
      } else if (stickyTop < windowTop+stickOffset) {
          $sticky.css({ position: 'fixed', top: stickOffset });
      } else {
          $sticky.css({position: 'absolute', top: 'initial'});
      }/////////////
    });
  }
    
  }
});

And this is my idea, if the class exists:

jQuery(document).ready(function($) {
    if (window.innerWidth > 767) {
                if ($(".classexists")[0]){

Where the element would be:

<div class="classexists">123</div>

Execute window on load function before the main function:

 $(window).on('load', function() {

if class does not exist, do not actually execute a $(window).on('load', function() {, just execute the rest of the code normally.

This code is supposed to create a sticky sidebar.

Answer

If i’m understanding your problem correctly, try this:

    function example() {
    var $sticky = jQuery('#sticky');
    var $stickyrStopper = jQuery('.footer');
    if (!!$sticky.offset()) { // make sure ".sticky" element exists
        var generalSidebarHeight = $sticky.innerHeight();
        var stickyTop = $sticky.offset().top;
        var stickOffset = 0;
        var stickyStopperPosition = $stickyrStopper.offset().top;
        var stopPoint = stickyStopperPosition - generalSidebarHeight - stickOffset;
        var diff = stopPoint + stickOffset;
        jQuery(window).scroll(function () { // scroll event
            var windowTop = jQuery(window).scrollTop(); // returns number
            //////////////
            if (stopPoint < windowTop) {
                $sticky.css({ position: 'absolute', top: diff });
            } else if (stickyTop < windowTop + stickOffset) {
                $sticky.css({ position: 'fixed', top: stickOffset });
            } else {
                $sticky.css({ position: 'absolute', top: 'initial' });
            }/////////////
        });
    }
}
if (window.innerWidth > 767) {
    if (jQuery('.classexists').length > 0) {
        jQuery(window).on('load', function () {
            example();
        });
    } else {
        example();
    }
}