Search code examples
javascriptjquerymousedown

How do I change my js click button to hold down


Here is my button code

$("#btn_Shiftup,#menufavs_btn_Shiftup").click(function () {             
    user_favourites_add('.group_button_2','#menufavs_btn_Shiftup','Shiftup()');    
});

Solution

  • You can use jQuery mousedown() Method.

    The mousedown event occurs when the left mouse button is pressed down over the selected element. The mousedown() method triggers the mousedown event, or attaches a function to run when a mousedown event occurs.

    Tip: This method is often used together with the mouseup() method.

    $("#btn_Shiftup,#menufavs_btn_Shiftup").mousedown(function(){
        // Do your things here 
    });
    

    Example and detailed information you can find here

    var timer = null;
    var subject = $("#subject")[0];
    
    var shifter =  function() {
      var newShifterPosition =  subject.style.top ? subject.style.top.split("px")[0] : "100";
      newShifterPosition =  parseInt(newShifterPosition) - 2;
      newShifterPosition = newShifterPosition < 10 ? 100 : newShifterPosition;
      subject.style.top = newShifterPosition + "px";
    }
    
    
    var shiftUp = function() {
       timer = setInterval(function(){
          shifter();    
       }, 200); 
    }
    
    var stopShifting = function() {
      timer && clearInterval(timer);
      timer = null;
      $(document).off('mouseup')
    }
    
    
    $(".btn_shiftup").mousedown(function(){
        shiftUp();
        // Stop execution of code when ever a mouse up event happens
        $(document).mouseup(function(){
            stopShifting();
        });
    
    });
    .container {
      position: absolute;
      top: 0px;
      bottom: 0px;
      left: 0px;
      right: 0px;
      background: #ffeeff;
    }
    
    #subject {
      position: relative;
      display: block;
      width: 25px;
      height: 25px;
      background: #ff000f;
      top: 100px;
      left: 100px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    
    
    
    <div class="container"> 
      <button class="btn_shiftup">Shift Up</button>
      <span id="subject"></span>
    </div>