Blinking text in a button - javascript

I have this function to blink text in a button "AddMoney" :-
function blinker1(){
document.getElementById("AddMoney").value="Add Money";
setTimeout("document.getElementById('AddMoney').value=' '", 500);
xxxx = setTimeout("blinker1()",1500);
}
And I stop it and set the text with this function:-
function cease1() {
clearTimeout(xxxx);
document.getElementById("AddMoney").value="Add Money";
}
It works but now and again there is no text in the button.
Anyone Know why and how to fix.

Now and again there is no text in the button. Anyone Know why?
It happens whenever cease1() is called while setTimeout("document.getElementById('AddMoney').value=' '",500) is still scheduled, which happens on average every third time. In that case, the blinker1() timeout is cancelled and the content is shown, but shortly after it will be hidden again.
… and how to fix?
You'll have to cancel both timeouts:
var timerA, timerB;
function blinker() {
document.getElementById("AddMoney").value = "Add Money";
timerA = setTimeout(function() {
document.getElementById('AddMoney').value = "";
}, 500);
timerB = setTimeout(blinker1, 1500);
}
function cease1() {
clearTimeout(timerA);
clearTimeout(timerB);
document.getElementById("AddMoney").value = "Add Money";
}
Alternatively, use two functions that are mutually scheduling each other so that only one timer is active at a time:
var timer;
function blinkerA() {
document.getElementById("AddMoney").value = "Add Money";
timer = setTimeout(blinkerB, 500);
}
function blinkerB() {
document.getElementById('AddMoney').value = "";
timer = setTimeout(blinkerA, 1000);
}
function cease1() {
clearTimeout(timer);
document.getElementById("AddMoney").value = "Add Money";
}

This version should work a bit better for you. I stuck with vanilla Javascript rather the introducing jQuery:
Fiddle
var blink = window.setInterval(blinker1, 900)
function blinker1() {
var addMoney = document.getElementById("addMoney");
addMoney.innerHTML = " ";
setTimeout(function(){addMoney.innerHTML = "ADD MONEY"}, 300);
}
document.getElementById('stop').addEventListener('click', function(){
clearInterval(blink);
})
Note - it would be better and easier to achieve a blink effect using pure CSS.

The text disappears because you only set clearTimeout on xxxx, so the timeout for setTimeout("document.getElementById('AddMoney').value=' '", 500); will always execute. I think this is the reason why there is no text in the button.
My approach would be to set a counter, let say the text need to blink 10 times (based on your code it will take 15sec.) Each time when the text shown the counter will decrease until it reaches 0.
sample code (https://jsfiddle.net/2trodftu/1/)
//counter
var blinkCounter = 10;
// blink method
function blink() {
document.getElementById("AddMoney").value="Add Money";
if (blinkCounter > 0) {
setTimeout("document.getElementById('AddMoney').value=' '", 500);
setTimeout(blink,1500);
}
blinkCounter = blinkCounter - 1;
}
//initializer
blink();
Hope this helps.

Related

Is there a way of making a javascript loop to repeatedly press a button?

I am very new to javascript so bear with me if I make mistakes, I am designing a website that allows the user to change the background with a button press, this all works very well and it's great but I want the images to be able to cycle with a time delay. In essence, I want the user to be able to click a button to change the background but I also want a javascript loop running in the background clicking the same button after a set period of time, is this possible?
The code to change the background is as follows:
$(document).ready(function () {
var i = 0;
$("#n").click(function () {
i++;
if (i > 16) { i = 1; };
$('body').css('background-image', 'url(img/' + i + '.jpg)');
});
$("#p").click(function () {
i--;
if (i <= 0) { i = 16; };
$('body').css('background-image', 'url(img/' + i + '.jpg)');
});
});
And the code for the buttons used is:
<button id="n" class="btn">Nxt</button>
<button id="p" class="btn">Prv</button>
You can use setInterval for looping -
setInterval(() => {
console.log('this will repeat every 500 milliseconds');
}, 500);
My recommendation would be not to simulate a click but just call the same function that the click does.
So let's make a function that can be called:
function increment() {
i++;
if ( i > 16 ){ i = 1; };
$('body').css('background-image', 'url(img/' + i + '.jpg)');
}
Then we can use that for the regular click that you already have:
$("#n").click(increment)
And we can also define a repeating call to this function:
setInterval(increment, 1000)
setInterval is pretty neat for non time sensitive tasks like this. Look at the link provided to see how it works, how to cancel it if you want to stop it...
#Ritesh Ganjewala wrote a nice little snippet in her answer that will show you what setInterval does.
#trincot also has an answer that, while a little more complicated to understand, allows you to have less repeating code by using the same function to increment and decrement your counter. Which is something you should strive for when programming something. This is called the DRY principle.
By design, you can't create user inputs with JavaScript. This makes sense if you think about it, certain browser features like requesting permissions can only be done if the user performs an action. You wouldn't want sites agreeing to grant permissions without your input.
So in your case, the best thing to do would be to have the event listener (for user input) and the setTimeout or requestAnimationFrame (for automatic cycling) call the same function.
document.getElementById('n').addEventListener('click', nextColor);
document.getElementById('p').addEventListener('click', prevColor);
var i = 0;
function nextColor() {
i++;
if ( i > 16 ){ i = 1; };
document.body.style.backgroundImage = `url(img/${i}.jpg)`;
}
function prevColor() {
i--;
if ( i <= 0 ){ i = 16; };
document.body.style.backgroundImage = `url(img/${i}.jpg)`;
}
setInterval(nextColor, 5000);
Don't attempt to send a click event to a button. Instead isolate the function that such a click executes, and then use setTimeout to execute that function. You may also want to reset an ongoing timeout when the user clicks again.
Here is how that could look:
$(document).ready(function(){
var i = 0;
var delay = 1000; // number of milliseconds
var timer = setTimeout(next, delay); // <-- set the time out
function next(step=1) { // optional argument that should be 1 or -1
i = (i + 16 + step) % 16; // Use modulo arithmetic to rotate in the range [0..15]
$('body').css('background-image', 'url(img/' + (i+1) + '.jpg)');
clearTimeout(timer); // interrupt the ongoing time out ...
timer = setTimeout(next, delay); // <-- and start it again
}
$("#n").click(next);
$("#p").click(next.bind(null, -1)); // bind the argument to be -1
});
try this setInterval, this will allow you to run a function with a fixed time delay.
function doThis() {
console.log('2 seconds over ...');
}
var xyz = setInterval(doThis, 2000);
and if you need to stop this,
clearInterval(xyz);
Yes, It is possible...
On click of the button on which you are changing the background color you can also initiate a timeout which will call a function after the specified time period (callback function) which in your case will change the image.and setinterval will do the same repeatedly after a specified interval.
$(document).ready(function(){
var i = 0;
function increment() {
i++;
if ( i > 16 ){ i = 1; };
$('body').css('background-image', 'url(img/' + i + '.jpg)');
}
function decrement() {
i--;
if ( i <= 0 ){ i = 16; };
$('body').css('background-image', 'url(img/' + i + '.jpg)');
}
$("#p").click(function(){
increment();
setInterval(increment, 1000);
}
$("#n").click(function(){
decrement();
setInterval(decrement, 1000);
}
}
Ok so ive figured something out from a couple of people who answered, what ive got now is this:
<script>
setInterval(() => {
$("#n").click();
}, 7000);
</script>
This has the effect of clicking the button i want every 7 seconds and its perfect, thanks for everyones help!

Javascript Text Slideshow Start from Beginning on Hover

I have added a text slideshow to a div that is called by JQuery on hover. How do I get the slideshow to start from the beginning each time the user hovers on the div? Right now it just continues to loop after the first time it is activated.
Thanks in advance!
<script>
$(document).ready(function(){
$('#mercury .infos').hover(
function () {
if($("a.active").is('.mercury')){
$("#descriptionls").fadeIn("2000");
};
var quotes = [
"Who’s the one who’s always there when that keeps happening?",
"Learn to dismantle self-defeating behaviors",
"JOIN THE FLOW TODAY",
];
var i = 0;
setInterval(function() {
$("#lstextslide").html(quotes[i]);
if (i == quotes.length)
i=0;
else
i++;
}, 1 * 4000);
});
});
</script>
You have to cancel the previous interval and call the function that updates the HTML immediately. See http://jsfiddle.net/xozL96fj/
$(document).ready(function(){
var intervalTimer = null;
$('#mercury .infos').hover(
function () {
if($("a.active").is('.mercury')){
$("#descriptionls").fadeIn("2000");
}
if (intervalTimer !== null) {
clearInterval(intervalTimer);
}
var quotes = [
"Who’s the one who’s always there when that keeps happening?",
"Learn to dismantle self-defeating behaviors",
"JOIN THE FLOW TODAY",
];
var i = 0;
function update() {
$("#lstextslide").html(quotes[i]);
i = (i + 1) % quotes.length;
}
// Call it immediately, don't wait until the interval
update();
intervalTimer = setInterval(update, 4000);
});
});
You need to make a check if your slider has already been activated. If you hover over your slider when the slider is already active, you will have to reset $i, and call setInterval() again.

Can't get javascript text effect to work properly with delay

I'm trying to make a random text effect kinda like the one at the end of the movie War Games (Matthew Broderick). The idea is to have individual letters change randomly when ever the user hovers over one of the letters in the word. Eventually after a short time the letter would end up being "decoded" meaning that it would end up on the right letter or number. I have built basic effect but the part I am struggling with is setting the timer. I want to create a small delay between the hover-out event and the actual display of the decoded character. When i add a settimeout however. The script breaks and seems to stack timers. I'm not sure what I'm doing wrong. Below is the code I've got so far.. any help would be great.
function setDecodedChar(object){
var decodedMessage = "HELLO WORLD";
var index = object.attr('class').substring(4);
console.log(index);
object.html(decodedMessage[index]);
}
function changeChar(object){
var randomchar = getrandomChar();
object.html(randomchar);
}
function getrandomChar(){
var char = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
char = possible.charAt(Math.floor(Math.random() * possible.length));
return char;
}
$(function() {
typesetting.letters('.title-text');
var target = $(".title-text").children();
console.log(target);
var timer;
var gate = true;
$(target).hover(function(){
var charChar = $(this);
//on hover-over
if(gate){
gate = false;
timer=setInterval(function(){
changeChar(charChar);
},100);
}
},function(){
//on hover-out
setTimeout(function(){ //<-- breaks here
clearInterval(timer)
setDecodedChar($(this));
},1000);
gate = true;
}
);
});
Here is a jsfiddle of the effect as I currently have it working. http://jsfiddle.net/thesnooker/htsS3/
I really like your idea, and I worked on it. I got it working.
First, here a fiddle : http://jsfiddle.net/htsS3/2/
I must say, i don't know if its the optimal way, but it still working!
The problem with you method is that you have 1 timer for every character, they override themselves, so some letters wont stop.
How i solve it:
I set the timer in the data of every letter like that :
$(this).data('timer', setInterval(function () {
changeChar(charChar);
}, 100));
Not every span have their own timer.
On hover out, i ad to save the $(this) reference into a `var since you lost it in the timeout. I alos saved the timeout into the data so i could stop it when you hover it and it's still changing. Well it look like that now :
var $this = $(this);
$this.data('timeout', setTimeout(function(){
clearInterval($this.data('timer'));
setDecodedChar($this);
},1000))
And finally, on hover, i had to clear timeout and interval:
clearInterval($(this).data('timer'));
clearTimeout($(this).data('timeout'));
Well, I find it hard to explain in my own word, so take a good look at the code and enjoy!
setsetTimeout(function(){ //<-- breaks here
clearInterval(timer)
setDecodedChar($(this));
},1000);
You have an extra 'set'
setTimeout(function(){ //<-- breaks here
clearInterval(timer)
setDecodedChar($(this));
},1000);
So the issue could be related to the timer. It changes every time the setInterval is called. If you were to store the interval on the hover object then clear it by using the stored reference it works.
Cool concept by the way.
$(function () {
var target = $(".text").children();
var timer;
$(target).hover(function () {
var charChar = $(this);
if($(this).data("timer") == void(0)) {
if($(this).data("timeout") != void(0)) {
clearTimeout($(this).data("timeout"));
}
$(this).data("timer", setInterval(function () {
changeChar(charChar);
}, 100));
}
}, function () {
//on hover-out
var timerObject = $(this);
timerObject.data("timeout", setTimeout(function() {
clearInterval(timerObject.data("timer"));
setDecodedChar(timerObject);
timerObject.removeData("timer");
}, 1000));
});

Hide download link for 10 seconds? js

hey, how can I have my download link hidden, and make a count down type thing. Maybe have it count down from 10 and once it's done that have the download link appear, it would be best to do it in js right?
does anyone know how to do this? :D
Thanks
Complete example:
<span id="countdown"></span>
<a id="download_link" href="download.zip" style="display:none;">Download</a>
<noscript>JavaScript needs to be enabled in order to be able to download.</noscript>
<script type="application/javascript">
(function(){
var message = "%d seconds before download link appears";
// seconds before download link becomes visible
var count = 10;
var countdown_element = document.getElementById("countdown");
var download_link = document.getElementById("download_link");
var timer = setInterval(function(){
// if countdown equals 0, the next condition will evaluate to false and the else-construct will be executed
if (count) {
// display text
countdown_element.innerHTML = "You have to wait %d seconds.".replace("%d", count);
// decrease counter
count--;
} else {
// stop timer
clearInterval(timer);
// hide countdown
countdown_element.style.display = "none";
// show download link
download_link.style.display = "";
}
}, 1000);
})();
</script>
You can use setInterval for this. setInterval behaves like a timer, where you can run a certain function periodically. Something like this should do the work(untested):
$(".link").hide();
var iteration = 0;
var timer = setInterval(function() {
if(iteration++ >= 10) {
clearTimeout(timer);
$(".link").show();
$(".counter").hide();
}
$(".counter").text(10 - iteration);
}, 1000);
This will initially hide the download link and run a function every second which counts down from 10. When we reaced ten, we hide the counter and show the link. ClearTimeout is used so that we don't count after we reached ten. Easy as dell.
Edit: As mentioned in the comments, this function is using jQuery to find the elements.
Take a look at the setTimeout function. You can do something like:
function displayLink() {
document.getElementById('link_id').style.display = 'block';
}
setTimeout(displayLink, 10000);
var WAIT_FOR_SECONDS = 10;
var DOWNLOAD_BUTTON_ID = "btnDownload";
if (document.body.addEventListener) {
document.body.addEventListener("load", displayDownloadButton, false);
} else {
document.body.onload = displayDownloadButton;
}
function displayDownloadButton(event) {
setTimeout(function() {
_e(DOWNLOAD_BUTTON_ID).style.display = "";
}, WAIT_FOR_SECONDS*1000);
}
function _e(id) {
return document.getElementById(id);
}

jQuery text() does not work before a setTimeout?

After an Ajax request, I perform the following.
$('#change_ts').text('Defaults Changed!');
//blinking part
var t = setTimeout($('#change_ts').fadeIn('slow'), 500);
clearTimeout(t);
var t = setTimeout($('#change_ts').fadeOut('slow'), 500);
clearTimeout(t);
var t = setTimeout($('#change_ts').fadeIn('slow'), 500);
clearTimeout(t);
var t = setTimeout($('#change_ts').fadeOut('slow'), 500);
clearTimeout(t);
var t = setTimeout($('#change_ts').fadeIn('slow'), 500);
clearTimeout(t);
var t = setTimeout($('#change_ts').fadeOut('slow'), 500);
clearTimeout(t);
var t = setTimeout($('#change_ts').fadeIn('slow'), 500);
clearTimeout(t);
var t = setTimeout($('#change_ts').text('Change Text/Size'), 500);
clearTimeout(t);
It is my make-shift fade in/out blinker. It works well.
However, the first line has no effect when I perform the blinking part. If I remove the blinking the text of the span is changed. But as soon as I uncomment the blinker, it doesn't change the text at all?!
Any ideas why this is?
Thanks all for any help
Update
The set timeout is useless for what I need to do. I have removed it now and I have the following, but I still can not change the text before the fade in/outs?
$('#change_ts').text('Defaults Changed!');
$('#change_ts').fadeIn('slow');
$('#change_ts').fadeOut('slow');
$('#change_ts').fadeIn('slow');
$('#change_ts').fadeOut('slow');
$('#change_ts').fadeIn('slow');
$('#change_ts').fadeOut('slow');
$('#change_ts').fadeIn('slow');
$('#change_ts').text('Change Text/Size');
How about using the jQuery Blink plugin instead. You can see the demo here :)
You should pass a callback function to setTimeout, like this:
var t = setTimeout(function() { $('#change_ts').fadeIn('slow') }, 500);
Right now, you're calling the fade function immediately and sending the return value to setTimeout. You should also change the timeout values to be increasing, like 500, 1000, 1500 etc., otherwise all the fade in/out will occur at the same time. You could use a loop to set-up the values for you. And why are you clearing the timers immediately - they won't have any effect if you do so.
for (var i = 1; i <= 6; i += 2) {
setTimeout(function() { $('#change_ts').fadeIn('slow') }, 500 * i);
setTimeout(function() { $('#change_ts').fadeOut('slow') }, 500 * (i + 1));
}
You can also make a generic blinker like this, which will keep blinking until you clear the timer:
var state = true;
function blink() {
state = !state;
if (state)
$('#change_ts').fadeIn('slow');
else
$('#change_ts').fadeOut('slow');
}
var t = setInterval(blink, 500);
This will keep going until you call clearInterval(t).
Update: The reason the first text call has no effect is because the second text call is executed immediately and the text is overwritten. Note that the fadeIn and fadeOut return immediately, before the animation is completed, so the second text call executes right after that. If you want to wait until the animation is complete, you need to attach a callback to the last fade function, like this:
$('#change_ts').fadeIn('slow', function() {
$('#change_ts').text('Change Text/Size');
});

Categories

Resources