Hey guys i have an code which changes from one state to another when you click on a button(it starts a video and blends). Now i try to say my eventhandler if someone clicks very fast he shouldnt use it as input. Something like = Eventhandler please notice just oneclick in one sec. Hope this is understanble here my code :
<script>
var clickState = 0;
var btn = document.querySelector('#playbutton');
btn.addEventListener('click', function(){
if (clickState == 0) {
document.querySelector('#toggler').emit('fade_1');
var videoEl_1 = document.querySelector('#video');
videoEl_1.play();
document.querySelector( "#skyid" ).emit('fade_1');
clickState = 1;
} else {
document.querySelector('#toggler').emit('fade_2');
var videoEl_1 = document.querySelector('#video');
videoEl_1.pause();
document.querySelector( "#skyid" ).emit('fade_2');
clickState = 0;
}
});
</script>
You could disable the button when it is clicked and then set a timeout to reenable it after a second.
Like this
$( document ).ready(function() {
$("#myButton").click(function(){
// disable the button
$("#myButton").prop("disabled", true);
//do the things you want the button to do:
console.log("doing stuff");
// reenable the button after 1 second
setTimeout(function(){
$("#myButton").prop("disabled", false);
}, 1000);
});
});
Example here:
https://jsfiddle.net/20n1gb89/8/
I've used some jQuery here, but setTimeout is native JavaScript
edit:
It seems you are defining a click handler inside a click handler for the same button. See my comments. Remove the btn.addEventListener and just keep the if else statement. See if that works.
$(document).ready(function () {
// here you define a click handler for playbutton
$("#playbutton").click(function () {
// disable the button
$("#playbutton").prop("disabled", true);
//do the things you want the button to do:
var clickState = 0;
var btn = document.querySelector('#playbutton');
// here you define a click handler for the same button
// inside the first click handler. You shouldn't do that.
btn.addEventListener('click', function () {
if (clickState == 0) {
document.querySelector('#toggler').emit('fade_1');
var videoEl_1 = document.querySelector('#video');
videoEl_1.play();
document.querySelector("#skyid").emit('fade_1');
clickState = 1;
} else {
document.querySelector('#toggler').emit('fade_2');
var videoEl_1 = document.querySelector('#video');
videoEl_1.pause();
document.querySelector("#skyid").emit('fade_2');
clickState = 0;
}
console.log("doing stuff");
// reenable the button after 1 second
setTimeout(function () {
$("#playbutton").prop("disabled", false);
}, 2000);
});
});
});
edit 2:
That is. Try this:
$(document).ready(function () {
$("#playbutton").click(function () {
// disable the button
$("#playbutton").prop("disabled", true);
//do the things you want the button to do:
var clickState = 0;
// this doesn't really make sense. clickState will always be 0
// as it is defined as 0 each time you click the button. You
// will need to define clickState outside the click handler
// for this to work.
if (clickState == 0) {
document.querySelector('#toggler').emit('fade_1');
var videoEl_1 = document.querySelector('#video');
videoEl_1.play();
document.querySelector("#skyid").emit('fade_1');
clickState = 1;
} else {
document.querySelector('#toggler').emit('fade_2');
var videoEl_1 = document.querySelector('#video');
videoEl_1.pause();
document.querySelector("#skyid").emit('fade_2');
clickState = 0;
}
console.log("doing stuff");
// reenable the button after 1 second
setTimeout(function () {
$("#playbutton").prop("disabled", false);
}, 2000);
});
});
});
You can add an eventlistener on click and creating a timer with it
for example, here after the user clicks the button, we launch a 1000ms timer, if the button is clicked within this time-interval, we will display an alert.
var btn = document.querySelector('#playbutton');
btn.addEventListener('click', function(){
setTimeout(function(){
if (btn.clicked == true){
alert("Cmon dude, chill a little");
}
}, 1000);
});
Related
I was able to get the space bar to activate the simple button I made, but I am having problems with having it be looped with setInterval(). Is it because of the eventFire mechanism I utilized? Any help or constructive criticism is welcomed as I am trying to learn. Thanks for your time.
Edit: I was able to find a solution as I apparently was using the setInterval function incorrectly. However I still have an issue with stopping the setInterval loop with clearInterval(timer) E hotkey. Here is the updated code.
"use strict";
// used for Tracking Mouse Position which I will implement later
let mousex;
let mousey;
// Simple Button that logs the amount of times pressed and triggers an animation
function button() {
const button = document.querySelector(".button");
function buttonClassRemove() {
button.classList.remove("active");
}
function delay(time, inputFunction) {
let milliseconds = time;
setTimeout(function () {
inputFunction();
}, milliseconds);
}
let i = 0;
button.addEventListener("click", function () {
i = i + 1;
console.log(`Button pressed ${i} times`);
button.classList.add("active");
delay(100, buttonClassRemove);
});
}
// Simulates event
function eventFire(el, etype) {
if (el.fireEvent) {
el.fireEvent("on" + etype);
} else {
var evObj = document.createEvent("Events");
evObj.initEvent(etype, true, false);
el.dispatchEvent(evObj);
}
}
function autoClicker() {
document.addEventListener("mousemove", () => {
// Tracking Mouse Position
mousex = event.clientX; // Gets Mouse X
mousey = event.clientY; // Gets Mouse Y
// console.log([mousex, mousey]); // Prints data
});
document.body.onkeydown = function (e) {
// Simulates click mouse event
// and then loop that functionality with the setInterval function
let timer = setInterval(function () {
eventFire(document.getElementById("button1"), "click");
}, 100);
if (e.keyCode == 32) {
timer;
console.log("Space pressed");
} else if (e.keyCode == 69) {
// Cancels autoclicker setInterval function
clearInterval(timer);
console.log("E pressed");
}
};
}
autoClicker();
button();
Your issue is that timer is a local variable. You should define it with var at the start of your program alongside mousex and mousey. As it currently stands, every time you run onkeydown it creates a new instance of the interval, checks whether to cancel it, and then throws away the reference. If you make it a global variable, then you can keep the reference so that you can cancel it at any time.
With this, you should also consider when you are running the interval. If you keep it as-is, your old interval will be overwritten with the new one before you can check to cancel. What you should do instead is something like this:
var timer = null;
document.body.onkeydown = function(e) {
if (/* start timer */ && timer == null) {
timer = setInterval(/* ... */);
} else if (/* end timer */) {
clearInterval(timer);
timer = null;
}
}
I'm trying to create a popup when a user is idle for (x) seconds and the idle timer only starts after a button is clicked but the timer is reset if there is mouse movement or another click. I also want this popup to only occur 1 timer per session.
So far I have the function working when the button is clicked and the popup shows up after 3 seconds. I would like the timer to be able to be reset when the mouse moves or is clicked.
Here's my javascript
function idlePop() {
var timer = 3000;
function resetTimer() {
}
$(document).ready(function() {
if (!sessionStorage.getItem('popupPreviouslyShown') || false) {
setTimeout(function() {
$('#donate-overlay').css('display', 'block');
sessionStorage.setItem('popupPreviouslyShown', true);
}, timer);
}
});
}
And the html button if you wanted to see it
<button onclick="idlePop();">Start</button>
I'm getting choked up on the function to reset the timer on mouse move (onmousemove) and on mouse click. Any help would be extremely appreciated.
i propose a solution , we'll see with what you say:
i suggest you to replace
<button onclick="idlePop();">Start</button>
by
<button id="start">Start</button>
user clicks on start button and after an idle of 3sec the popup appears
UPDATED V1.0
$(document).ready(function() {
var stage = 0;
var timer = 3000;
var timout = -1;
var isDetectionActivated = false;
$("#start").on('click', function(e) {
$("#start").prop("disabled", true);
//e.stopPropagation();
console.log("start");
idlePop();
})
function activateDetection() {
isDetectionActivated = true;
$(document).on("mousemove click", function(e) {
console.log("timeout aborted")
// you couldt test the type of event with e.type
clearTimeout(timout);
//console.log("you have moved or clicked", e.type);
//re-launch process
idlePop();
});
}
function desactivateDetection() {
$(document).off("mousemove click");
isDetectionActivated = false;
}
function idlePop() {
console.log("idlePop");
//for debuging
/*
timout = launchTimeout(timer);
return;
*/
if (!sessionStorage.getItem('popupPreviouslyShown') || false) {
timout = launchTimeout(timer);
}
}
function launchPopup() {
console.log("popup");
$('#donate-overlay').css('display', 'block');
sessionStorage.setItem('popupPreviouslyShown', true);
}
function launchTimeout() {
if (!isDetectionActivated) {
activateDetection();
}
console.log("timeout activated");
return setTimeout(function() {
console.log("timeout finished");
$("#start").prop("disabled", false);
clearTimeout(timout);
desactivateDetection();
launchPopup();
}, timer);
}
});
I wrote the function for check if button was clicked twice and if it was to measure the time between two clicks. It has to prevent multiple clicks in short time.
Button click:
$("#Save").click(function () {
dateTime1 = new Date().getTime();
BtnId = this.id;
showSaveDialog();
});
And measuring function:
ButtonWasTriggeredTwice: function () {
var result = false;
var currentTime = new Date().getTime();
var time = currentTime - dateTime1;
if (PreviousBtn === null) {
result= false;
} else {
if (PreviousBtn === BtnId) {
if ( time < 1500) {
result = true;
}
else result = false;
}
else {
result= false;
}
}
PreviousBtn = BtnId;
BtnId = null;
return result;
}
BtnId and PreviosusBtn are global scope variables.
The strange thing is this function works great when I set breakpoints in debugger. If I switch off debugger function blocks every next click on button, no matter what time interval is between clicks
You can use this solution with unbind and timeout, like this:
HTML
<input type="button" id="Save" value="save me" />
JS:
function saveEventButton(){
$("#Save").click(function () {
alert('saved!');
$("#Save").unbind('click');
setTimeout(function(){
saveEventButton();
}, 5000); // 5sec
});
}
saveEventButton();
This is the JSFiddle
UPDATE This solution is a mix from mine and Revish Patel solution
function disableTimeout(_this){
$(_this).prop('disabled','disabled');
setTimeout(function(){
$(_this).prop('disabled','');
}, 5000); // 5sec
}
$("#Save").click(function () {
alert('saved!');
disableTimeout(this);
});
This is the JSfiddle
You can also disable button when you first click is performed.
$(document).ready(function () {
$("#Save").click(function(){
$('#Save').prop('disabled','disabled');
// Perform your button click operation
});
});
$(function(){
window.location.href = $('.links').attr('href');
});
The Class Name is "links" and there are many links under it,how do i add a delay to each link click and not have the script click the same link again and again?
Thanks
$(function () {
// Grab all links into a wrapped set.
var $links = $('.link');
// Start with the first link at index 0 in the wrapped set.
var linkNum = 0;
// Specify our delay time.
var delay = 1; // seconds
// Setup a click handler on all our links.
$links.click(function (e) {
var $this = $(this);
console.log($this.text() + ' clicked.');
$this.css({ color: '#f00' });
// After our delay, click the next link.
setTimeout(function () {
++linkNum;
if (linkNum < $links.length) {
$links.eq(linkNum).click();
} else {
linkNum = 0;
console.log("All links clicked.");
}
}, delay * 1000);
});
$('button').click(function () {
$links.eq(0).click();
});
});
http://codepen.io/Chevex/pen/WvzXbQ?editors=101
I am trying to modify the script below to click a button that looks like this on a site:
<button id="checkPrice-02070" onclick="checkPrice(02070,null); return false;" class="orangeDark">
<span>check price</span>
</button>
I am using the code below. So far, the page seems to keep reloading; nothing else happens.
Any advice to someone new?
(function () {
window.addEventListener("load", function (e) {
clickConfirmButton()
}, false);
})();
function clickConfirmButton() {
var buttons = document.getElementsByTagName('button');
var clicked = false;
for (var index = 0; (index < buttons.length); index++) {
if (buttons[index].value == "check price") {
buttons[index].click();
clicked = true;
break;
}
}
if (!clicked) {
setTimeout("window.location.reload()", 300 * 1000);
}
}
A <button>s value is not the visible text. You'd want to search textContent.
However:
If that sample HTML is correct, you'd be better off searching for ids that start with checkPrice. See the code below.
Are you sure you want to reload if the button is not found? If it is added by AJAX this is not the best approach. See this answer.
Don't use setTimeout with a string (to evaluate) argument like that. See the code below.
You do not need to wrap the code in an anonymous function.
Anyway, this should work, given the sample HTML:
window.addEventListener ("load", clickConfirmButton, false);
function clickConfirmButton (zEvent) {
var button = document.querySelector ("button[id^='checkPrice']");
if (button) {
button.click ();
}
else {
setTimeout (function () { location.reload(); }, 300 * 1000);
}
}
To check the button text anyway, use:
function clickConfirmButton (zEvent) {
var buttons = document.querySelectorAll ("button[id^='checkPrice']");
var clicked = false;
for (var index = 0, numBtn = buttons.length; index < numBtn; ++index) {
if (/check price/i.test (buttons[index].textContent) ) {
buttons[index].click();
clicked = true;
break;
}
}
if (!clicked) {
setTimeout (function () { location.reload(); }, 300 * 1000);
}
}