I would like to enable and disable a function with a button, is it possible in jQuery?
I need to track all clicks on a div, but only when the user want to record them.
1 - User click on button "start recording" 2 - every click on a div records the coordinates in a array 3 - when the user click on button "stop recording" the array is saved in a file and the function is disable.
For the example I did a function which just prints an alert with the coordinate.
$('.room').click(function(e) {
var width = $(this).css("width");
var widthLength = width.length;
var height = $(this).css("height");
var heightLength = height.length;
height = height.substring(0,heightLength-2);
width = width.substring(0,widthLength-2);
var posX = $(this).offset().left, posY = $(this).offset().top;
posX = (e.pageX - posX);
posY = (e.pageY - posY);
posY = Math.round((100/height) * posY);
posX = Math.round((100/width) * posX);
alert(posX + " - " + posY);
});
and this is the div:
.room{
position:relative;
background-color:#444444;
margin:5% 5% 10% 5%;
z-index:1;
}
To do this you could just hold your array of points, and a boolean of whether you're recording. Push a new value into the array for each click - only when recording - and when you click stop do whatever you want with the array.
For example:
var points = [];
var isRecording = false;
$('#start').click(function(){
points = [];
isRecording = true;
});
$('#stop').click(function(){
isRecording = false;
console.log(points);
});
$('.room').click(function(e) {
if(isRecording){
var width = $(this).css("width");
var widthLength = width.length;
var height = $(this).css("height");
var heightLength = height.length;
height = height.substring(0,heightLength-2);
width = width.substring(0,widthLength-2);
var posX = $(this).offset().left, posY = $(this).offset().top;
posX = (e.pageX - posX);
posY = (e.pageY - posY);
posY = Math.round((100/height) * posY);
posX = Math.round((100/width) * posX);
points.push({x:posX,y:posY});
}
});
.room{
width:200px;
height:200px;
border: 1px solid black
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="start">Start Recording</button>
<button id="stop">Stop Recording</button>
<div class="room">
</div>