How do i add a Play/Pause button for this slideshow? - javascript

Hi im trying to make a slideshow that run automatically and with this code it's working but i need to add a Play/Pause button to that code. Someone care to help ?
I would need the html/css also
var indexDiaporama=1;
afficherDiapo(indexDiaporama);
function ajoutDiapo(n){
afficherDiapo(indexDiaporama+=n);
}
function diapoActuelle(n){
afficherDiapo(indexDiaporama=n);
}
function afficherDiapo(n){
var i;
var slides=document.getElementByClassName("diapo");
var dots=document.getElementByClassName("dot");
if(n>slides.length){indexDiaporama=1;}
if(n<1){indexDiaporama=slides.length;}
for(i=0; i<slides.length; i++){
slides[i].style.display="none";
}
for(i=0; i<dots.length; i++){
dots[i].className=dots[i].className.replace("active", "");
}
slides[indexDiaporama-1].style.display="block";
dots[indexDiaporama-1].className+="active";
}
var timer = setInterval(function(){
indexDiaporama++;
afficherDiapo(indexDiaporama);
},3000);

Start by setting a variable, we will call it pause, to false and then run a conditional inside your setTimeout() that checks if it is false => if(!paused){ //run code }.
Handle the paused variable due to what state your button is in when it is pressed ==> e.target
You create a function that passes in your event target of a pause/play button when it is clicked. In that function you check the value of your pause/play button, you can use a dataset to toggle 0 or 1 / on or off / true or false on click and change the value of your pause variable due to what that dataset is set to on click.
In my example I use 0 and 1 in the data-id attribute => dataset.id in JS, with a conditional that checks that value => if (e.target.dataset.id === '0'){ //set paused to true }else{ // set paused to false }. Within the conditional I also set the textContent of the button and the dataset.id value as well.
Then each time you press the pause button the setInteral freezes as it is looking for paused to not be set to false => if (!paused){ // run code for setInterval }.
Below is a simply JS setInterval that increments a number by one every millisecond. We can pause and play it using the function and event listener as described above.
const display = document.getElementById('display')
const btn = document.querySelector('.btn')
let paused = false;
let i = 1;
function checkBool(e) {
if (e.target.dataset.id === '0') {
e.target.dataset.id = '1'
btn.textContent = 'Play'
paused = true;
}else{
e.target.dataset.id = '0'
btn.textContent = 'Pause'
paused = false;
}
}
btn.addEventListener('click', checkBool)
const timer = setInterval(function() {
if (!paused) { //<-- paused is not false
//<-- run the code your interval handles
display.textContent = i;
i++;
}
}, 100);
<div id="display"></div>
<button class="btn" data-id="0">Pause</button>

Related

read div and check for a click condition

let timer = document.querySelector("#timer");
var counter = 3;
function myFn() {
counter--
if (counter === -1) {
counter = 3
}
timer.innerText = counter
}
btn.onclick = function() {
text.innerHTML += 'clicked' + '<br>'
}
var myTimer = setInterval(myFn, 1000);
<div id="timer"></div>
<button id="btn">Button</button>
<div id="text"></div>
I'm trying with this small code to read the div#timer every second and check for a click condition in console.log() F12. It gives me different error in every way I try to do it.
let timer = document.querySelector("#timer");
let btn = document.querySelector("#btn");
setInterval(() => {
console.log(timer.textContent)
if (timer.textContent === '0') {
btn.click()
}
}, 1000);
Consider the following jQuery example.
$(function() {
var timer = 0;
var counter = 3;
var timeObj = $("#timer");
var btnObj = $("#btn");
var txtObj = $("#text");
var interval;
function myFn() {
if (--counter >= 0) {
txtObj.append("Clicked<br />");
} else {
clearInterval(interval);
}
}
interval = setInterval(function() {
timeObj.html(++timer);
}, 1000);
btnObj.click(myFn);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="timer">0</div>
<button id="btn">Button</button>
<div id="text"></div>
You will want to use setInterval() and not setTimeout().
The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.
This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval().
See more: https://developer.mozilla.org/en-US/docs/Web/API/setInterval
Using the -- and ++ before the variable will also apply the change before it is used.
The decrement operator (--) decrements (subtracts one from) its operand and returns the value before or after the decrement, depending on where the operator is placed.
Adjusting the logic here can also ensure that the button click does allow the user to keep performing actions.

Set a background timer in javascript

I'm trying to prevent users in Dynamics 365 / CRM from quickly clicking on the same button, thus initiating a synchronous, window-blocking event.
We were able to fix this in IE, but Chrome seems to "remember" the button clicks - and then initiate the same event, again and again, synchronously (as is expected).
I had thought about creating a background timer, that will be initiated on the first button click, which will turn a variable as 'True' until the timer finishes, then turning the variable as 'False'.
During those X seconds in which the variable is set to true, subsequent button clicks will fire the event, but not proceed any further than a few lines where the function will check if the variable is set to true or false.
This is my (not working) code so far:
function startTimer(duration) {
isTimerOn = true;
var timer = duration, seconds;
setInterval (function () {
seconds = parseInt(timer % 60, 10);
seconds = seconds < 10 ? 0 + seconds : seconds;
if (--timer < 0) {
timer = duration;
}
}, 500);
isTimerOn = false;
};
var isTimerOn = false;
function createWordSummary() {
if (isTimerOn) {
return;
}
try {
startTimer(3);
// Logic here
Would love some help, thanks in advance!
You can try something like this:
let disabled = false;
function startTimer(s) {
disabled = true;
setTimeout(function() {
disabled = false;
}, s * 1000);
}
function createWordSummary() {
if ( disabled ) return;
startTimer(3);
console.log('check');
}
<button onclick="createWordSummary()">Check</button>
Hope it helps!

Map data example with slider in d3

I tried to implement a basic slider function to this example
var slider = d3.slider()
.axis(false).min(minDate).max(maxDate).step(secondsInDay)
.on("slide", function(evt, value) {
temp = moment(value,"x").utc().format("MM");
console.log(temp);
//tempVal = moment(temp).unix()*1000;
dataChoro = countries.properties.filter(function(d){
return d.properties[attributeArray[temp]]
});
});
d3.select('#slider3').call(slider);
But I can't read countries. What do I have to change to make it running? I try to use the play function of this example but instead of the button playing I'd like to use the slider to trigger the events
function animateMap() {
var timer; // create timer object
d3.select('#play')
.on('click', function() { // when user clicks the play button
if(playing == false) { // if the map is currently playing
timer = setInterval(function(){ // set a JS interval
if(currentAttribute < attributeArray.length-1) {
currentAttribute +=1; // increment the current attribute counter
} else {
currentAttribute = 0; // or reset it to zero
}
sequenceMap(); // update the representation of the map
d3.select('#clock').html(attributeArray[currentAttribute]); // update the clock
}, 2000);
d3.select(this).html('stop'); // change the button label to stop
playing = true; // change the status of the animation
} else { // else if is currently playing
clearInterval(timer); // stop the animation by clearing the interval
d3.select(this).html('play'); // change the button label to play
playing = false; // change the status again
}
});
}
Gist Any tips?
When you want to use the same code of your clock you can try this
var slider = d3.slider()
.axis(false).min(minDate).max(maxDate).step(secondsInDay)
.on("slide", function(evt, value) {
temp = moment(value,"x").utc().format("MM");
if(currentAttribute < attributeArray.length-1) {
console.log(currentAttribute);
currentAttribute = temp-1; // increment the current attribute counter
} else {
currentAttribute = 0; // or reset it to zero
}
sequenceMap(); // update the representation of the map
d3.select('#clock').html(attributeArray[currentAttribute]); // update the clock
});
d3.select('#slider3').call(slider);

Increase value by 1 till mouse is release using angular mouse events

I have a td span which displays some numeric value and i have 2 icons (up/down arrow) shown above and below the span. Clicking on the up arrow increases the value by 1 till 99 and clicking on down arrow decreases the value by 1 till 0. Everything is working fine with ng-click.
The problem is if i want to increase the value say from 10 to 20, i have to click the up arrow 10 times. I want to do this by keep pressing the mouse on the up arrow. It should keep increasing/decreasing till i release the mouse on the up/down arrow respectively.
I tried using ng-mousedown but it increases by 1. Is there a way i can call the js function till the mouse button is released.
Any pointers will be helpful.
Code I tried so far:
var mouseDown = true;
var interval;
$scope.keepPressing = function(){
mouseDown = true;
if (mouseDown){
doSome();
}
};
function doSome(){
console.log(mouseDown);
if (mouseDown){
console.log(1);
interval = setInterval(doSome, 1000);
}
}
$scope.isMouseDown = function (){
clearInterval(interval);
mouseDown = false;
};
HTML:
The problem with this is even though the value 1 is not printed when i release the mouse, value false (mousedown value) is getting logged infinitely. This is a just the test flow to check if it works for me before i apply it to my actual function.
The output from console:
true
1
true
1
true
1
true
1
true
1
true
1
true
1
true
1
63 false
After i release the mouse, the false value is printed 63 times within seconds. I have to refresh the page to stop it.
Here is directive, that enables setting your own time-interval and step:
.directive('changingValue', function(){
return {
scope : {
changingValue :"=",
changingValueStep : "#",
changingValueInterval : "#"
},
link : function(scope, element, attrs) {
var step = attrs.changingValueStep;
if(!step)step = 1;
else step = parseInt(step);
var interval = attrs.changingValueInterval;
if(!interval)interval = 500;
else interval = parseInt(interval);
console.log("step", step, "interval", interval);
var pressed = false;
function changeValue() {
if (pressed) {
setTimeout(
function() {
console.log(scope.changingValue);
scope.changingValue += step;
scope.$apply();
changeValue();
}, interval
)
}
}
element.on("mousedown", function() {
pressed = true;
changeValue();
});
element.on("mouseup", function() {
pressed = false;
});
}
}
Basically it can be used like that:
<div changing-value="counter" changing-value-step="-1" changing-value-interval="200">-</div>
And here is working --->PLNKR<---.
Here is what i did and working for me.
var interval;
scope.mousePress = function(){
doSome();
}
};
var doSome = function {
increaseValue(); // separate function where all the increment logic resides.
interval = $timeout(doSome, 1000);
}
scope.mouseRelease = function (){
$timeout.cancel(interval);
};
In the HTML, call the mousePress & mouseRelease functions from ng-mousedown & ng-mouseup respectively.

Detecting when the mouse is not moving

I am able to find the cursor position. But I need to find out if the mouse is stable. If the mouse wasn't moved for more than 1 minute, then we have to alert the user.
How its possible, are there any special events for this? (Only for IE in javascript)
Set a timeout when the mouse is moved one minute into the future, and if the mouse is moved, clear the timeout:
var timeout;
document.onmousemove = function(){
clearTimeout(timeout);
timeout = setTimeout(function(){alert("move your mouse");}, 60000);
}
Here's a one-and-done function that can check any element for movement:
function mouse (element, delay, callback) {
// Counter Object
element.ms = {};
// Counter Value
element.ms.x = 0;
// Counter Function
element.ms.y = function () {
// Callback Trigger
if ((++element.ms.x) == delay) element.ms.callback(element, element.ms);
};
// Counter Callback
element.ms.callback = callback;
// Function Toggle
element.ms.toggle = function (state) {
// Stop Loop
if ([0, "off"][state]) clearInterval(element.ms.z);
// Create Loop
if ([1, "on"][state]) element.ms.z = setInterval(element.ms.y, 1);
};
// Function Disable
element.ms.remove = function () {
// Delete Counter Object
element.ms = null; return delete element.ms;
};
// Function Trigger
element.onmousemove = function () {
// Reset Counter Value
element.ms.x = -1;
};
// Return
return element.ms;
};
Usage:
mouse(element, delay, callback)
Examples:
Make a video player hide the mouse after 5 seconds when idle and fullscreen
let x = mouse(video, 5000, function (a) {
if (document.webkitIsFullScreen) video.style.cursor = "none";
});
x.toggle(1); addEventListener("mousemove", function () {
video.style.cursor = "auto";
});
Chat Room AFK (45 Seconds) (assuming you have a chat box and a send message function):
let x = mouse(chatBox, (45e3), function (a) {
chatBox.send({ text: chatBox.username + " is AFK.", italic: true });
});
x.toggle(1); x.addEventListener("mousemove", function () {
chatBox.send({ text: chatBox.username + " is no longer AFK", italic: true });
});
Is there not a way to set a timer to start incrementing after every mouse movement event?
If it gets to a minute then pop up the message box, but every time the mouse moves the timer gets reset.
Use a timer that resets its value on mousemove event.
If timer reaches 1 minute --> Do something.
More info on timer here http://www.w3schools.com/js/js_timing.asp
And more info on catchin mouse events here http://www.quirksmode.org/js/events_mouse.html
Yes, you have a onmousemove event in Javascript, so to achieve what you need you just have to do code something like this:
startTimer();
element.onmousemove = stopTimer(); //this stops and resets the timer
You can use it on the document body tag for instance.
UPDATE: #Marius has achieved a better example than this one.
You can use the onmousemove event. Inside it, clearTimeout(), and setTimeout(your_warning, 1 minute).
You could use this script/snippet to detect the mouse pointer position and "remember" it. Then use a timer "setTimeout(...)" to check the position let's say every second and remember that time.
If more than one minute passed and the position hasn't changed, you could alert the user.

Categories