1

I am trying to add press to jQuery selector. I have many elements on same document, So I can not use IDs for each. I tried by $(selector)[i] as like explained here.

var selectProduct = $('.mh60 a');
for (var i = 0; i < selectProduct.length; i++) {
  Hammer(selectProduct[i]).on("press", function() {
     $(selectProduct[i]).addClass('active');
  });
}

It's not producing any error and not working. I didn't get what I am missing here.

And when I try to log selectProduct[i] by console.log(selectProduct[i]); it gives undefined result.

UPDATE 1

When I remove for loop and just use selectProduct[0] , selectProduct[1] , ... it's working but with selectProduct[i] , it's not working, So I think problem is on for loop. But I didn't get it.

UPDATE 2

I also tried with jQuery plugin, same problem

UPDATE 3

Again I tried with each(), same problem. It print the console message but addClass() is not working. I guess the problem is with this function which is not returning the current element.

$('.mh60 a').each(function(){
    var mc = new Hammer(this);
    mc.on("press", function() {
      console.log('Double tap!');
      $(this).addClass('active');
    });
 });

2 Answers 2

0

Why do you use a for? Try changing your code like this

var selectProduct = $('.mh60 a');
selectProduct.Hammer().on("press", function() {
  $(this).addClass('active');
});
6
  • hammer.min.js:6Uncaught TypeError: a.addEventListener is not a function Commented Jun 29, 2016 at 14:03
  • instead of using jquery selector, try with pure js one
    – Roxoradev
    Commented Jun 29, 2016 at 14:05
  • I tried same error, you can also check another question linked on this question, may be you get something Commented Jun 29, 2016 at 14:07
  • If you jquery Hammer, have you tried with selectProduct.Hammer().on(...) ?
    – Roxoradev
    Commented Jun 29, 2016 at 14:09
  • you mean like this ? selectProduct.Hammer.on("press", function() {..}); same problem Commented Jun 29, 2016 at 14:21
0

Finally I solved the problem by using each function

$('.mh60 a').each(function(){
    var mc = new Hammer(this);
    var currentEle = $(this);
    mc.on("press", function() {
      currentEle.addClass('active');
    });
 });

Not the answer you're looking for? Browse other questions tagged or ask your own question.