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.
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.
Share Improve this question asked Oct 24, 2011 at 12:28 Johannes KlaußJohannes Klauß 11.1k18 gold badges71 silver badges127 bronze badges 1- 2 Possible duplicate of stackoverflow./questions/1397251/… – etuardu Commented Oct 24, 2011 at 12:39
2 Answers
Reset to default 4The 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 -- i.e., every second -- is called "polling."