I'm trying to put in a small easter egg on a site I'm building where if a user clicks a link x amount of times it will trigger a popup, I'd guess this would be some kind of JS or JQuery but I have no idea where to start or if it's even possible. I guess what I really want is something like the easter egg built into the Android 'About Phone' page, which opens a new page after about 7 clicks within 5 seconds. Is there any way to do this in a browser?
Maybe an OnClick command which adds 1 to a counter and does an action when the counter reaches a specified number, but resets the counter to 0 every 10 seconds? (I don't want to make it too easy to find!)
Thanks
Try this one with jQuery:
Html:
<a id='lnkEgg' data-clicks='0'>Click for surprise</a>
Script:
$(function(){
$("#lnkEgg").on("click",function(){
var c=$(this).data("click");
if(c==7){
//if it equals to whatever number you are chasing
//open the popup
}else{
$(this).data("clicks",c++);
}
});
});
Use a setTimeout (which you clear each time) and preventDefault on the click event if it doesn't meet your requirements.
(function (node) { // IIFE to keep our namespace clean :)
var timer,
count = 0;
function timeup() {
count = 0;
}
function handler(e) {
clearTimeout(timer);
timer = setTimeout(timeup, 5e3); // 5 seconds
++count;
if (count < 7) // number of clicks
e.preventDefault();
}
node.addEventLister('click', handler);
}(document.getElementById('myLink'))); // passing the <a> into the IIFE
This code must be run after the target element exists
#TheVillageIdiot's technique is the way to go. Here I'll just show some approach using the same technique:
$(function(){
var egg = $('#lnkEgg');
egg.on('click', function() {
//increment and check if magic clicks has been reached
if( ++$(this).data().clicks == 7 ) {
console.log( "You've now clicked the required number of times");
//do some more operations
$(this).data('complete', true);
console.log( $(this).data() );
};
});
//Reset counter every 10 seconds
setInterval(function() {
egg.data().clicks = 0;
}, 10000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a id="lnkEgg" data-clicks="0">Click for surprise</a>
Related
i wrote a function which do count down or up the numbers to another by pressing a button.
look at this :
var timer;
function counterFn(element,oldCount,newCount,speed) {
if(isNaN(speed)) speed=100;
clearInterval(timer);
if(oldCount===newCount) {
element.text(newCount);
return;
}
var counter=oldCount;
timer=setInterval(function() {
if(oldCount<newCount) {
if(counter>newCount)
clearInterval(timer);
counter++;
} else {
if(counter<newCount)
clearInterval(timer);
counter--;
}
if(counter===newCount) {
clearInterval(timer);
}
element.text(counter);
},speed);
}
$('.button').on("click",function() {
counterFn('.endelement',10,100,1);
});
description of the function attributes:
element : the element which will show the result
oldCount : is the start number
newCount : is the end number
speed : is the repeat time of setInterval
now, according to above code, if you press the element with .button class, counterFn function will run. now if you press the button again (before clearing the setinterval by the function), every thing is OK.
this is the working demo : http://jsfiddle.net/hgh2hgh/gpvn9hcq/4/
as you can see, clicking on the button, clear the previous interval and run the new one.
now if the second element call that function like this :
$('.button2').on("click",function() {
counterFn('.endelement2',50,70,2);
});
naturally the second request will stop the timer and run new timer with the new attributes. cause a global variable is defined for just one setInterval.
look at the comments for demolink of this part : [1] in comments
if definition of the variable be inside the function, pressing the button twice, mean running the function for two separate time.
look at the comments for demolink of this part : [2] in comments
OK, now how to run this function correct?
thanks.
Ok coming straight to the point
I have a text box and few other things on a page
if the user is typing in the textbox the page should not refresh otherwise it should refresh after a certain interval
I searched alot and cannot find anything similar
I am new to javascript
Here is a simple example of this. A check runs every 3 seconds. if nothing has been typed in it will refresh, if something has been typed in it will wait 3 seconds before refreshing.
http://jsfiddle.net/9ARrG/
HTML
<input onkeyup="resetTimer = true">
JS
resetTimer = false;
setInterval(function() {
if(!resetTimer) {
location.reload();
}
resetTimer = false;
}, 3000);
Give your input/textarea an id
<input id="textbox" />
// OR
<textarea id="textbox"></textarea>
Then, setup a timer to refresh the page. If there's a change, reset the timer.
var originalTimer = 15000; // here's the original time until page refreshes
var timer = originalTimer; // timer to track whether to refresh page
// now every 1 second, update the timer
setInterval(function() {
timer -= 1000; // timer has gone down 1 sec
// if timer is less than 0, refresh page
if (timer <= 0) window.location.reload();
},1000); // repeat every 1 second (1000 ms)
document.getElementById("textbox").onchange = function() {
// detect textbox changes, reset timer
timer = originalTimer;
}
Use the document.activeElement property to conditionally determine what element has focus.
function refreshPageUnlessFocusedOn (el) {
setInterval(function () {
if(el !== document.activeElement) {
document.location.reload();
}
}, 3000)
}
refreshPageUnlessFocusedOn(document.querySelector('textarea'));
Check out the jsfiddle here for a working sample.
I want that when a user clicks on any external link (identified by either particular id or class) on my site then he should get a popup with a counter of 10 seconds, after 10 seconds the popup should close and the user should be able to access the external URL. How can this be done? I'm able to show a warning like below but I don't know how to add timeout to it, also this is a confirm box, not a popup where I can add some div and more stuff for user to see until the counter stops.
$(document).ready(function(){
var root = new RegExp(location.host);
$('a').each(function(){
if(root.test($(this).attr('href'))){
$(this).addClass('local');
}
else{
// a link that does not contain the current host
var url = $(this).attr('href');
if(url.length > 1)
{
$(this).addClass('external');
}
}
});
$('a.external').live('click', function(e){
e.preventDefault();
var answer = confirm("You are about to leave the website and view the content of an external website. We cannot be held responsible for the content of external websites.");
if (answer){
window.location = $(this).attr('href');
}
});
});
PS: Is there any free plugin for this?
I've put together a little demo to help you out. First thing to be aware of is your going to need to make use of the setTimeout function in JavaScript. Secondly, the confirmation boxes and alert windows will not give you the flexibility you need. So here's my HTML first I show a simple link and then created a popup div that will be hidden from the users view.
<a href='http://www.google.com'>Google</a>
<div id='popUp' style='display:none; border:1px solid black;'>
<span>You will be redirected in</span>
<span class='counter'>10</span>
<span>Seconds</span>
<button class='cancel'>Cancel</button>
</div>
Next I created an object that controls how the popup is displayed, and related events are handled within your popup. This mostly is done to keep my popup code in one place and all events centrally located within the object.
$('a').live('click', function(e){
e.preventDefault();
popUp.start(this);
});
$('.cancel').click(function()
{
popUp.cancel();
});
var popUp = (function()
{
var count = 10; //number of seconds to pause
var cancelled = false;
var start = function(caller)
{
$('#popUp').show();
timer(caller);
};
var timer = function(caller)
{
if(cancelled != true)
{
if(count == 0)
{
finished(caller);
}
else
{
count--;
$('.counter').html(count);
setTimeout(function()
{
timer(caller);
}, 1000);
}
}
};
var cancel = function()
{
cancelled = true;
$('#popUp').hide();
}
var finished = function(caller)
{
alert('Open window to ' + caller.href);
};
return {
start : start,
cancel: cancel
};
}());
If you run, you will see the popup is displayed and the countdown is properly counting down. There's still some tweaks of course that it needs, but you should be able to see the overall idea of whats being accomplished. Hope it helps!
JS Fiddle Sample: http://jsfiddle.net/u39cV/
You cannot using a confirm native dialog box as this kind of dialog, as alert(), is blocking all script execution. You have to use a cutomized dialog box non-blocking.
You can use for example: jquery UI dialog
Even this has modal option, this is not UI blocking.
Consdier using the javascript setTimeout function to execute an action after a given delay
if (answer){
setTimeOut(function(){
//action executed after the delay
window.location = $(this).attr('href');
}, 10000); //delay in ms
}
I have that Javascript counter:
var x=100;
function timerCountdown()
{
document.getElementById('timer1').value=x;
x--;
t=setTimeout("timerCountdown()",1000);
if (x<-1)
{
document.getElementById('timer1').value='Done!';
clearTimeout(t);
}
}
function stopCounter(){
clearTimeout(t);
x=x+1;
}
Then I use:
<body onFocus='timerCountdown()' onBlur='stopCounter()'>
But the problem is, the countdown doesn't start when the page loads. It waits for me to click on another window and to reFocus on the window again.
So I tried this:
<body onLoad='timerCountdown()' onFocus='timerCountdown()' onBlur='stopCounter()'>
But this time, the countdown goes pretty fast. Probably because timerCOuntdown is called twice every second.
Alternatively, I could just use the onFocus and onBlur in the body tag, but I need a function to trigger the Focus upon body load. Is that possible?
Does anyone have a suggestion to solve this problem?
thanks a lot!
The simple answer is because setTimeout is invoked twice, running timerCountdown() once for two times separately, and continually setting two setTimeout IDs.
This would be what you want:
var x = 100;
var t = 0;
function timerCountdown()
{
if (t == 0) t = setInterval(timerCountdown, 1000);
document.getElementById('timer1').value=x;
x--;
if (x < 0)
{
document.getElementById('timer1').value='Done!';
clearTimeout(t);
ticker = 0;
}
}
function stopCounter()
{
clearTimeout(t);
t = 0;
x++;
}
setInterval is much more suited for countdown timers, and things you need to run continually since setTimeout only runs once and you need to keep on calling it.
Edit: This fixes the initial rapid triggering of the timer on Firefox.
Remove the handler from <body onload= and add this to the end of the script block above:
t = setInterval(timerCountdown, 1000);
I'm designing a web site and I would like to be able to call a function 1 second after the last user input. I tried using onKeyUp, but it waited 1 second after the first keystroke.
Does anyone know how would this be possible?
Another similar approach, without globals:
var typewatch = function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
}
}();
...
<input type="text" onKeyUp="typewatch(function(){alert('Time elapsed!');}, 1000 );" />
You can this snippet here.
You can use a keyDown (or keyUp) event that sets a function to run in 1 second and if the user types another key within that second, you can clear the timeout and set a new one.
E.g.
var t;
function keyDown()
{
if ( t )
{
clearTimeout( t );
t = setTimeout( myCallback, 1000 );
}
else
{
t = setTimeout( myCallback, 1000 );
}
}
function myCallback()
{
alert("It's been 1 second since you typed something");
}
Nevermind, I found a way to do it. I call a function on each onkeyup() which increment a counter and then wait 1 second. After the 1 second elapsed, it decrement the counter and check if it's equal to 0.
var keystrokes = 0;
function askAgain()
{
++keystrokes;
setTimeout(reveal, 1000);
}
function reveal()
{
--keystrokes;
if (keystrokes == 0)
alert("Watch out, there is a snake!");
}
Just modify your html input and toss that first line into your existing functions so you're not having to recode anything you have. It will not affect any old code-calling functions either, since if onkeypress is not set then mykeypress will always be < 1.
var mykeypress=0;
var mysleep=1000; //set this higher if your users are slow typers
function mytest(id,text) {
mykeypress--; if(mykeypress > 0) { return; }
//anything you want when user stops typing here
alert("Keypress count at "+mykeypress+" ready to continue
id is "+id+" arguement is "+text);
}
input type="text" name="blah" id="55" onkeypress="mykeypress++"
onkeyup="myid=this.id;setTimeout(function (){mytest(myid,'a test')},mysleep)"
REVERT to old way seamlessly:
input type="text" name="blah" id="55" onkeyup="mytest(this.id,'a test')"
There is some simple plugin I've made that does exacly that. It requires much less code than some proposed solutions and it's very light (~0,6kb)
First you create Bid object than can be bumped anytime. Every bump will delay firing Bid callback for next given ammount of time.
var searchBid = new Bid(function(inputValue){
//your action when user will stop writing for 200ms.
yourSpecialAction(inputValue);
}, 200); //we set delay time of every bump to 200ms
When Bid object is ready, we need to bump it somehow. Let's attach bumping to keyup event.
$("input").keyup(function(){
searchBid.bump( $(this).val() ); //parameters passed to bump will be accessable in Bid callback
});
What happens here is:
Everytime user presses key, bid is 'delayed' (bumped) for next 200ms. If 200ms will pass without beeing 'bumped' again, callback will be fired.
Also, you've got 2 additional functions for stopping bid (if user pressed esc or clicked outside input for example) and for finishing and firing callback immediately (for example when user press enter key):
searchBid.stop();
searchBid.finish(valueToPass);
// Get the input box
let input = document.getElementById('my-input');
// Init a timeout variable to be used below
let timeout = null;
// Listen for keystroke events
input.addEventListener('keyup', function (e) {
// Clear the timeout if it has already been set.
// This will prevent the previous task from executing
// if it has been less than <MILLISECONDS>
clearTimeout(timeout);
// Make a new timeout set to go off in 1000ms (1 second)
timeout = setTimeout(function () {
console.log('Input Value:', input.value);
}, 1000);
});
<!-- a simple input box -->
<input type="text" id="my-input" />
Credits to:
Wait for User to Stop Typing, in JavaScript