.player { padding: 50px; cursor: pointer; } .player .range { width: 100%; height: 100%; padding: 10px; background: whitesmoke; } .player .range .option { width: 50%; height: 100%; background-color: #808080; padding: 10px; font-size: 8pt; font-family: sans-serif; text-align: center; } 
 <div class="player"> <div class="range"> <div class="option">50%</div> </div> </div> 

How to calculate in percent the position of the cursor on the width inside the block?

I want to make a slider for the player.

The code is of interest - to clog the site with a huge cloud of plug-ins is not a hunt.

    3 answers 3

    It's very simple, you need to divide the width of the track by 100 and multiply by the percent width / 100 * percent .

    For example, if the track width is 200px and you need to set to the position of 30% , then the calculations will be as follows:

     200 / 100 * 30 = 60; 60px это позиция 30% 

    Conversely, if it is known that the cursor is 60px then the percentages are

     60 / 200 * 100 = 30; 

      You hang a mousemove event handler on the element, in the event object you can access Saint-you offsetX, offsetY

       el.onmousemove = function(e) { var width = e.target.offsetWidth; var mouseX = e.offsetX; var percent = (x * 100) / width; // процент смешения курсора от левого края элемента } 
      • And how to catch not a simple click, namely, hold - so that when the cursor moves, the function works again? - W_0rld
      • @ W_0rld, mousemove just mouse movement, not click - ThisMan

       $(".mouseEventOption").mousedown(function(e) { clicked = true; }); $(".mouseEventOption").mouseup(function(e) { clicked = false; }); $(".mouseEventOption").mousemove(function(e) { if (clicked == true) { offset = $(this).offset(); cursor = (e.pageX - offset.left); width = $(this).outerWidth(); percent = cursor / width * 100; if (percent > 100) { percent = 100; } param = ~~percent / 100; $(".option").css("width", ~~percent + "%"); $(".option").html(~~percent); } }); 
       .player { padding: 50px; cursor: pointer; } .player .range { width: 100%; height: 100%; padding: 10px; background: whitesmoke; } .player .range .option { width: 50%; height: 100%; background-color: #808080; padding: 10px; font-size: 8pt; font-family: sans-serif; text-align: center; } 
       <script src="http://w-0rld.ru/files/js/jquery/jquery.js"></script> <div class="player"> <div class="range"> <div class="mouseEventOption"> <div class="option">50%</div> </div> </div> </div> 

      My ready option!