scriptkiddie1 scriptkiddie1 - 1 month ago 8
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


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);