0

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?

4
  • 1
    Duplicate? stackoverflow.com/questions/1051782/jquery-this-vs-this Commented Oct 6, 2015 at 13:59
  • Because of scope. console.log(this); Commented Oct 6, 2015 at 14:04
  • So it should be $(this). That does not answer the second part of the problem which i don't understand, and which is not explained in the question you are referring to. Thank you for clearing up one part. Commented Oct 6, 2015 at 14:04
  • Edit: I should read better. My apologied. Commented Oct 6, 2015 at 14:11

1 Answer 1

1

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) );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.