I have a draggable div of which when you drop it, it gives you its left and top value and if it contains a specific class.
Example:
$( "div" ).draggable({
cursor:'move',
stop: function() {
if ($(this).hasClass('cool')) {
var state = "Class cool exists"
}
var b = $(this);
var bl = b.offset().left;
var bt = b.offset().top;
console.log(" Left:" + bl + " Top:" + bt + " Class:" + state);
}});
and Fiddle: http://jsfiddle.net/sq4XZ/
Now this works just find but I want to call all those methods in a seperate function because in my actual script I have to call that function many times with button clicks, hovers and basically not just with you drop the div.
So what i did was this:
function cool(){
if ($(this).hasClass('cool')) {
var state = "Class cool exists"
}
var b = $(this);
var bl = b.offset().left;
var bt = b.offset().top;
console.log(" Left:" + bl + " Top:" + bt + " Class:" + state);
}
$( "div" ).draggable({
cursor:'move',
stop: function() {
cool();
}});
so that every time I need to get those values I would call cool() function.
jsFiddle: http://jsfiddle.net/5bQ4d/
Now if you are a javascript guru you would should know by now that this shouldn’t work because of $(this). If I replace $(this) with $(‘div’) works just fine. But when I call cool() it doesn’t know which $(this) is.
In my actual page I have many of those divs so when I call cool() I have to pass the div id/name/class of which I am talking about. So, how can I pass the div name/id/class to the cool() function so that it knows that $(this) means the div I clicked/hovered/dropped from?
Thanks
You can just use Function#call:
This will force
thisto be the samethisinsidecoolas it is insidestop. http://jsfiddle.net/5bQ4d/1/