absentx
absentx

Reputation: 1417

Jquery targeting when multiple items of a class exist

I have the following code:

$(function () {
        var target = $('span.slider') //can I make the variable apply to the target span?

        target.mousedown(function() { 
              sliding = true 
        })
        $(document).mouseup(function() {
             sliding = false 
        })
        $(document).mousemove(function(e) { 
            if(sliding){ 
              target.css('left', e.pageX) //do I isolate here?
            }
        })  
    })

There are four 'span.slider' in my html. How do I modify this jquery so that the functionality only applies to the target span.slider? The code above moves all four spans, and I completely understand why it does. I am having trouble targeting it to just the span the user wishes to move.

Upvotes: 0

Views: 82

Answers (3)

Musa
Musa

Reputation: 97672

Try adding a class to it and then check against the class

    target.mousedown(function() { 
          sliding = true;
          $(this).addClass('sliding'); 
    })
    $(document).mouseup(function() {
         sliding = false; 
          target.removeClass('sliding'); 
    })
    $(document).mousemove(function(e) { 
        if(sliding){ 
          target.filter('.sliding').css('left', e.pageX) //do I isolate here?
        }
    })  

Upvotes: 1

charlietfl
charlietfl

Reputation: 171669

You can bind and unbind the mousemove each time as follows

$(function() {
  var target = $('span.slider');
  target.on('mousedown', function(e) {
    var $el = $(this)
    $(document).mousemove(function(e) {
      $el.css('left', e.pageX) 
    })
  }).on('mouseup', function() {
    $(document).off('mousemove');
  })

})

Upvotes: 1

Sang Suantak
Sang Suantak

Reputation: 5265

Try this:

$(function() {
    var target = $('span.slider'); //can I make the variable apply to the target span?
    var targetToMove;
    target.mousedown(function() {
        sliding = true;
        targetToMove = $(this);
    });
    $(document).mouseup(function() {
        sliding = false;
    });
    $(document).mousemove(function(e) {
        if (sliding) {
            targetToMove.css('left', e.pageX); //do I isolate here?
        }
    });
})​;​

Upvotes: 1

Related Questions