Applying styles to JS variable returning error

I have the following in a jsfiddle:

function isOnScreen(elem) {
	// if the element doesn't exist, abort
	if( elem.length == 0 ) {
		return;
	}
	var $window = jQuery(window)
	var viewport_top = $window.scrollTop()
	var viewport_height = $window.height()
	var viewport_bottom = viewport_top + viewport_height
	var $elem = jQuery(elem)
	var top = $elem.offset().top
	var height = $elem.height()
	var bottom = top + height

	return (top >= viewport_top && top < viewport_bottom) ||
	(bottom > viewport_top && bottom <= viewport_bottom) ||
	(height > viewport_height && top <= viewport_top && bottom >= viewport_bottom)
}

;(function(){

  var throttle = function(type, name, obj){
    var obj = obj || window;
    var running = false;
    var func = function(){
      if (running){ return; }
      running = true;
      requestAnimationFrame(function(){
        obj.dispatchEvent(new CustomEvent(name));
        running = false;
      });
    };
    obj.addEventListener(type, func);
  };
  
  throttle("scroll", "optimizedScroll");
})();

window.addEventListener("optimizedScroll", function(e){
		if( isOnScreen( jQuery( item ) ) ) { 
		item.style.transform = "rotate(-" + window.pageYOffset + "deg)";
 		}	
	});
  
  const item = $('#item0')

However on scroll it returns the error Cannot set property 'transform' of undefined" As you can see item is getting the element id’d item0 so why isn’t item.style.transform = "rotate(-" + window.pageYOffset + "deg)"; working specifically?

Cheers.

The jQuery selector returns a jQuery object, it does not return the raw element.

If you want to use native properties/methods you can get to the element using the array index.

const test = $('#test')
test[0].style.background = 'red'

However, if you are going to use jQuery you might as well use its build-in methods, like css for example.

test.css({ background: "red" });

Also, your selector is after the use. It needs to be before.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.