Cyrill Cyrill - 4 months ago 7
Javascript Question

Using $(this) does not work

I am trying to get a script running that adds some events to a class.
I want these events only to be added to one specific DIV among this class. I am using pep.js:

$( ".drag" ).pep({
start: function() {
$(".drag").addClass('color');
$('.drag').next(".text").fadeIn("slow");
$(".text-video").fadeOut("fast");

},
stop: function() {
$('.drag').removeClass('color');
$('.drag').next(".text").fadeOut("slow");
}

});


This works, but it triggers all .drag items at onceā€¦ And I want only the one I am dragging to have added all the events.

I tried to write it with:

$(".drag", this).addClass('color');


or:

$(this).addClass('color');


or:

$(this.element).addClass('color');


But it all didn't work.
Does someone have an idea?

UPDATE:

I made a JSFiddle that hopefully explains my problem.

https://jsfiddle.net/ke6d5r1h/

As you see, the .color class for example is not only added to the DIV that is dragged, but also to the other. This is what I want to change.

Answer

Using console.log(arguments) in the event handlers, I was able to determine that the handlers are passed two arguments: the event object, and an object containing context. The context has a property $el, which is a jQuery object for the event target.

start: function(e,a) {
    a.$el.addClass('color');
    a.$el.next(".text").fadeIn("slow");
    $(".text-video").fadeOut("fast"); 
},

https://jsfiddle.net/85tffqhL/

e.target would also give you a reference to the element.