简体   繁体   中英

Fire event if margin-left == 200px;

I'm trying to create a listener kind of thing in jQuery. What I want to do is check all the time, if an divs margin-left == 200px and then fire an event. But I have no idea how to do that. Maybe it's better, that the div calls the event function, when it's margin-left == 200px, but I'm not even sure, if that's possible.

Any help will be very appreciated.

The following function will check every 1 second whether an element with the class elementClass has a margin-left set as 200px . If so, an alert will be triggered (as an example).

$(document).ready(function(){
   setInterval(function(){
      if ($(".elementClass").css("marginLeft")=='200px'){
         //do something here
         alert("margin is 200px");
      }
   }, 1000);
});

However, this code will then trigger the event every second that the margin-left is 200px . The following will only trigger the event the first time the element has been detected with the 200px margin-left:

 var eventtrig = 0;
 $(document).ready(function(){
   setInterval(function(){
      if ($(".elementClass").css("marginLeft")=='200px' && eventtrig=0) {
         //do something here
         alert("margin is 200px");
         eventtrig=1;
      }
      else {
         eventtrig=0;
      }
   }, 1000);
});

You can check "all the time" by doing a setinterval( ) of say 1 second and then, in the handler for the clock event, check the div's left margin and perhaps alert( ) when/if it ever gets to 200.

EDIT: as a point of information: the process of checking every once in a while -- ie, every second -- is called "polling."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM