Dany
Dany

Reputation: 755

jquery plugin css opacity

I am trying to create a simple jquery plugin for a CRT type effect. I did check the documentation -> https://learn.jquery.com/plugins/basic-plugin-creation/ but i think i don't understand.

When i execute the code without turning it into a plugin it works fine.

setInterval(function(){
  $('#wallpaper').css("filter", "opacity("+ String(Math.random() * (0.96 - 1.0) + 0.96 ) +")");
}, (Math.random() * (500 - 1000) + 100) );

When i turn it into a plugin it does nothing.

$.fn.crt = function(){
  setInterval(function(){
    $(this).css("filter", "opacity("+ String(Math.random() * (0.96 - 1.0) + 0.96 ) +")");
  }, (Math.random() * (500 - 1000) + 100) );
}
console.log($('#wallpaper').crt());

When i change $(this).css()... to this.css()... it gives me the following error : TypeError: this.css is not a function

Can anyone tell me how to get this code working in a plugin or what i am doing wrong?

Upvotes: 0

Views: 75

Answers (1)

epascarello
epascarello

Reputation: 207531

this inside the timeout is not what you think it is. It will be the window object. You need to either bind() the anonymous function to this or use the classical closure technique of defining a variable outside.

$.fn.crt = function(){
  var that = $(this);
  setInterval(function(){
    that.css("filter", "opacity("+ String(Math.random() * (0.96 - 1.0) + 0.96 ) +")");
  }, (Math.random() * (500 - 1000) + 100) );
}

Upvotes: 1

Related Questions