scriptkiddie1 scriptkiddie1 - 1 year ago 146
Javascript Question

How pass this value to setinterval on onload function

I want to send this to a function called using setInterval on image's onload event but it throws the following error:

Uncaught TypeError: Cannot read property 'attr' of undefined(…)

<img src="image.jpg" id="24" onload="var sel =this;setInterval(function(sel){calllogin(sel)},20000);"
function calllogin(sel){
var id = sel.attr("id");
console.log('calling calllogin function',id);

Please tell me how to pass this.
Thanks in advance

Answer Source

You have to remove setInterval(function(sel), sel from the function parameter.

onload="var sel =this; setInterval(function(){ calllogin(sel) },20000);"

Or just pass the sel as a third parameter to setInterval

setInterval(function(sel){calllogin(sel)},20000, sel);

and the sel inside callBack will not be a jquery object. It will be a simple element object. You have to convert it before consuming a Jquery's function.

function calllogin(sel) {
  var id = $(sel).attr("id");
  console.log('calling calllogin function',id);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download