1

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.

Johannes Klauß
  • 10,676
  • 16
  • 68
  • 122
  • 2
    Possible duplicate of http://stackoverflow.com/questions/1397251/event-detect-when-css-property-changed-using-jquery – etuardu Oct 24 '11 at 12:39

2 Answers2

4

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);
});
Curtis
  • 101,612
  • 66
  • 270
  • 352
  • This will do, best solution so far. But I am not sure if you should swap to `margin-left` instead. – OptimusCrime Oct 26 '11 at 11:33
  • @OptimusCrime - For `.css("marginLeft")`? I think I've done this the correct way. See the examples at jquery http://api.jquery.com/css/ – Curtis Oct 26 '11 at 11:35
  • both of them will work. Just think it's easier to use the correct css-attribute, so jQuery don't have to parse it first. – OptimusCrime Oct 26 '11 at 11:37
  • @OptimusCrime - Cheers I wasn't aware of that. Any idea why you can use `marginLeft` instead then? What's the point? – Curtis Oct 26 '11 at 12:00
  • I think it's because of the coding conventions of jQuery. They're heavily java influenced. – Johannes Klauß Oct 28 '11 at 09:36
  • @JohannesKlauß - I've actually sinced looked into why. Heres the answer: http://stackoverflow.com/questions/7902324/jquery-css-marginleft-vs-margin-left – Curtis Oct 28 '11 at 09:39
0

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 -- i.e., every second -- is called "polling."

Pete Wilson
  • 8,610
  • 6
  • 39
  • 51