Stefan Octavian Stefan Octavian - 1 month ago 6
jQuery Question

Trying to make a JQuery plugin not working

I am trying something new for me.I am always making html pages with the same functions so I want to simplify my work using a JQuery plugin made by me.But this is the First time I am trying this and I have read many web pages on how to do this and I don't know what doesn't work.This is
Emu.js file:

$.fn.loop = function(time,callback) {
setInterval(this,time);
if(callback !== 'undefined' && typeof(callback) == "function") {
callback
}
};


And this is Emu.html file:

<!DOCTYPE html>
<html>
<head>
<script src="JQuery.js" ></script>
<script src="Emu.js" ></script>
</head>
<body onload="do_it()">
<p></p>
<script type="text/javascript">
function hello() {
$("p").append("Hello!"+"<br>")
}

function do_it() {
$(hello).loop(2000)
}
</script>
</body>
</html>

Answer
  • jQuery plugins/ Methods (just like .show()) expect a jQuery Element Object as reference: $("p").loop()
  • Put the setInterval stuff within your if
  • Use $.proxy to refer to the right jQuery this Element Object (otherwise this will point to window Object inside setInterval)
  • Inside the hello() feel free to use jQuery's $(this) cause this refers to the JS reference on the HTMLParagraphElement "p"

$.fn.loop=function(time,callback) {
  if(callback !== 'undefined' && typeof callback === "function") {
    setInterval($.proxy(callback, this), time);
  }
};


jQuery(function($) { // Use DOM ready instead of <body onload="do_it()">

  function hello(){
    $(this).append("Hello!<br>");
  }

  $("p").loop(2000,hello);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p></p>

Some errors you've could avoid your self are i.e. the use of WindowTimers.setInterval where the first parameter is supposed to be a callback function setIntarval(fn, time). this is not a function in your case.