jquery - How to make a continuous listener in javascript? -


i learning perhaps question rephrased or re-worded.

  1. when click div=> variable= variable+1;
  2. what want when 'variable===3', console.log('i 3).

my script not doing trying do, try.

<script type="text/javascript">      element = document.getelementbyid("id");     variable=0;      function loading(){          element.addeventlistener("click",function(){         variable=variable+1;         console.log(variable);         });      };       function check(){     if(variable===3){console.log('i 3');};      };      loading();     check();       </script> 

should call check() each time object clicked? or should create listener call check() every time 'variable' changing? or solutions?

call check event handler:

function loading(){     element.addeventlistener("click",function(){         variable=variable+1;         check();         console.log(variable);     }); } 

calling check whenver variable changes option variable.

if want check time value of changes, use object property instead, setter:

var obj = (function() {     var value = 0;      return {         value() {             return value;         },         set value(newvalue) {             value = newvalue;             if (value == 3) {                 console.log("i 3");             }         }     } })(); 

then:

function loading(){     element.addeventlistener("click",function(){         obj.value = obj.value + 1; // or ++obj.value;         console.log(obj.value);     }); } 

whenever change value of obj.value, setter function called, , can check there.

note feature added in es5 (2009), it's not present in older javascript engines such 1 in ie8.


some other notes:

  1. your code falling prey the horror of implicit globals: declare variables.

  2. ; don't go @ end of function declarations, or blocks. statements don't end block.

  3. consistent indentation aids readability.

  4. variable = variable + 1; fine, have option of being more concise: ++variable;

so:

var element = document.getelementbyid("id"); var variable = 0;  function loading(){     element.addeventlistener("click",function(){         ++variable;         console.log(variable);         check();     }); }  function check(){     if (variable===3) {         console.log('i 3');     } }  loading(); check(); 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -