jQuery Placeholder Animation - javascript

I have an HTML Form that currently has an empty placeholder value.
TypingEffect() randomly selects one of eight examples and then calls type() to type them out as the placeholder. Then, after an interval of 2000, it applies an erasing effect that will erase it.
I think my problem lies within my syntax, more specifically the TypingEffect() function but I can't figure it out.
FIDDLE
HTML:
<form action="" method="get" type="search">
<input type="text" class="textbox" placeholder='' />
</form>
Javascript + jQuery:
$(document).ready(function() {
setInterval ('cursorAnimation', 600);
textbox = $('.textbox');
setInterval ('TypingEffect', 600);
setInterval ('ErasingEffect', 2000);
});
function TypingEffect() {
var tag = Math.floor((Math.random() * 10) + 1);
if (tag = 1) { caption = "Example1" }
if (tag = 2) { caption = "Example2" }
if (tag = 3) { caption = "Example3" }
if (tag = 4) { caption = "Example4" }
if (tag = 5) { caption = "Example5" }
if (tag = 6) { caption = "Example6" }
if (tag = 7) { caption = "Example7" }
if (tag = 8) { caption = "Example8" }
type();
}
function type() {
textbox.attr("placeholder", (caption.substr(0, captionLength++)));
if(captionLength < caption.length+1) {
setTimeout('type()', 50);
} else {
captionLength = 0;
caption = '';
}
}
function ErasingEffect() {
caption = captionEl.html();
captionLength = caption.length;
if (captionLength>0) {
erase();
}
}
function erase() {
textbox.attr("placeholder",(caption.substr(0, captionLength--)));
if(captionLength >= 0) {
setTimeout('erase()', 50);
} else {
captionLength = 0;
caption = '';
}
}

I updated your fiddle to make it work. https://jsfiddle.net/uxftux9w/5/
There were a few issues but I think some were from copying your code into jsfiddle, e.g. cursorAnimation variable and that you have not included jQuery in the fiddle
The main problems were the use of setInterval like Shilly pointed out. Use the function name rather than a string like so setInterval('type()', 50)
setInterval(type, 50)
The other problem was the fact that you were using two setInterval's as follows
setInterval ('TypingEffect', 600);
setInterval ('ErasingEffect', 2000);
These will just repeatedly call the two functions without taking into account the any differences in the length of the caption you are trying to type.
Instead I used setTimeout to delay the initial call to the TypingEffect and ErasingEffect functions, and setInterval to repeatedly call the type/erase functions until the caption is fully typed, or deleted. Here is the code. I added comments so I hope it some sense. There are quite a few ways you could optimise and reduce repetition if you want.
HTML
<form action="search.php" method="get" type="search">
<input type="text" class="textbox" placeholder='' />
</form>
JavaScript
$(document).ready(function() {
var textbox = $('.textbox'),
captionLength = 0,
caption = '',
id = setTimeout(TypingEffect, 600); //call onces and set an Id so it can be cleared
function TypingEffect() {
// console.log('TypingEffect');
var tag = Math.floor((Math.random() * 8) + 1);
if (tag == 1) {
caption = "Example1"
}
if (tag == 2) {
caption = "Example Example 2"
}
if (tag == 3) {
caption = "Example3"
}
if (tag == 4) {
caption = "Example Example 4"
}
if (tag == 5) {
caption = "Example5"
}
if (tag == 6) {
caption = "Example Example Example 6"
}
if (tag == 7) {
caption = "Example7"
}
if (tag == 8) {
caption = "Example Example 8"
}
clearTimeout(id); //clear first clearTimeout(TypingEffect, 600) call
captionLength = 1; //start at 0
id = setInterval(type, 50); //call type every 50ms
}
function type() {
// console.log('type', caption, caption.substring(0, captionLength++));
textbox.attr("placeholder", caption.substring(0, captionLength++));
//when finshed typing clear interval and call erase
if (captionLength === caption.length + 1) {
// console.log('end type');
clearInterval(id); //clear clearInterval(type, 50)
id = setTimeout(ErasingEffect, 1000); //start erase call once after delay
}
}
function ErasingEffect() {
// console.log('ErasingEffect');
clearTimeout(id); //clear clearTimeout(ErasingEffect, 2000); call
captionLength = caption.length; //start at end
id = setInterval(erase, 50); //call erase every 50ms
}
function erase() {
// console.log('erase');
textbox.attr("placeholder", caption.substring(0, captionLength--));
//when finshed erasing clear interval and call type
if (captionLength < 0) {
// console.log('end erase');
clearInterval(id); //clear clearInterval(erase, 50)
id = setTimeout(TypingEffect, 1000); //start over
}
}
});
Update - for those who prefer CSS
Here is a similar effect I discovered by Lea Verou done in pure CSS.

Related

Propagation issue with jQuery button

I have created a javascript / jquery simple game actioned by two buttons.
Button 1: "Play". The game is played ten times, and increments using a variable that I store in local storage. If the increment matches a random number between one and 10, then console.log("match!"), otherwise console,log("no match");
Button 2: "Restart the game". Once the increment is bigger than 10, then the game starts over by clicking the button.
The problem is, if you look into the console, that the second time you play the game, the game jumps by two increments at a time. The third time, by three increments... Why is that? There is a propagation issue here. How do I solve it?
Jsfiddle is here. Code I paste below, as it's very small:
start_game_over()
function start_game_over(event) {
$("#button1").show();
$("#button2").hide();
localStorage.setItem("progress", 0)
$("#button1").on("click", function() {
if (parseInt(localStorage.getItem("progress")) < 11) {
var random_number = Math.floor(Math.random() * (10 - 0) + 0);
console.log(parseInt(localStorage.getItem("progress")));
if (parseInt(localStorage.getItem("progress")) === random_number) {
console.log("match!")
} else {
console.log("no match")
}
localStorage.setItem("progress", parseInt(localStorage.getItem("progress")) + 1);
} else {
$("#button1").hide();
$("#button2").show();
$("#button2").on("click", function() {
start_game_over();
});
}
})
}
When you start_game_over you assign an event listener to the button click, but you never remove it, so when you call the function again it attaches a new one. restructuring the code a bit to handle the clicks outside of that function would be a good idea.
function start_game_over(event) {
$("#button1").show();
$("#button2").hide();
localStorage.setItem("progress", 0)
}
$("#button1").on("click", function() {
if (parseInt(localStorage.getItem("progress")) < 11) {
var random_number = Math.floor(Math.random() * (10 - 0) + 0);
console.log(parseInt(localStorage.getItem("progress")));
if (parseInt(localStorage.getItem("progress")) === random_number) {
console.log("match!")
} else {
console.log("no match")
}
localStorage.setItem("progress", parseInt(localStorage.getItem("progress")) + 1);
} else {
$("#button1").hide();
$("#button2").show();
}
})
$("#button2").on("click", function() {
start_game_over();
});
You are declaring your event listeners inside a function, so every time the function is called, you are creating a new listener. Put them out of the function and the problem is fixed.
You have to clear your $('#button1') event at the end by using $('#button1').off('click');. This will clear the event listener you create every time in your function.
SE doesn't allow localStorage so run this on JSFiddle or local machine.
start_game_over()
function start_game_over(event) {
$("#button1").show();
$("#button2").hide();
localStorage.setItem("progress", 0)
$("#button1").on("click", function() {
if (parseInt(localStorage.getItem("progress")) < 11) {
var random_number = Math.floor(Math.random() * (10 - 0) + 0);
console.log(parseInt(localStorage.getItem("progress")));
if (parseInt(localStorage.getItem("progress")) === random_number) {
console.log("match!")
} else {
console.log("no match")
}
localStorage.setItem("progress", parseInt(localStorage.getItem("progress")) + 1);
} else {
$("#button1").hide();
$("#button2").show();
$("#button2").on("click", function() {
$("#button1").off("click");
$("#button2").off("click");
start_game_over();
});
}
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button1">Play</button>
<button style="display:none" id="button2">Restart the Game</button>
The problem is that each time you invoke start_game_over you are adding additional click handlers to #button1 and #button2. What you want to do is set up the click handlers once and use a function to reset your game state when #button2 is clicked (or just reset the game state in #button2's callback). For example:
var $button1 = $('#button1');
var $button2 = $('#button2');
var start_game_over = function () {
$button1.show();
$button2.hide();
localStorage.setItem('progress', 0)
};
$button1.on('click', function () {
var progress = parseInt(localStorage.getItem('progress'), 10 /*always include radix!*/);
if (progress < 11) {
//... game logic here
} else {
$button1.hide();
$button2.show();
}
});
$button2.on('click', function () {
start_game_over();
});

Resetting variables is not resetting game?

I am creating a Simon game and it works on round one, but once your each round two it immediately says incorrect.
jsfiddle
I reset all variables between the rounds, but it still seems to save them as it instantly says "Game Over!"
JS:
function makeGuess() {
...
var checkForComplete = setInterval(function () {
if (yourAnswer.length >= round) {
clearInterval(checkForComplete);
yourString = yourAnswer.toString();
correctString = correctAnswer.toString();
if (yourString === correctString) {
alert('Correct');
round++;
yourAnswer = [];
correctAnswer = [];
yourString = "";
correctString = "";
playSimon();
}
else {
alert("Game Over!");
}
}
}, 500)
Here is the playSimon() function:
function playSimon() {
setTimeout(function () {
color = Math.floor(Math.random() * 4);
if (color == 0) {
correctAnswer.push(0);
$('#redButton').addClass('lightOn');
setTimeout(function () {
$('#redButton').removeClass('lightOn');
}, 500);
}
else if (color == 1) {
correctAnswer.push(1);
$('#blueButton').addClass('lightOn');
setTimeout(function () {
$('#blueButton').removeClass('lightOn');
}, 500);
}
else if (color == 2) {
correctAnswer.push(2);
$('#greenButton').addClass('lightOn');
setTimeout(function () {
$('#greenButton').removeClass('lightOn');
}, 500);
}
else if (color == 3) {
correctAnswer.push(3);
$('#yellowButton').addClass('lightOn');
setTimeout(function () {
$('#yellowButton').removeClass('lightOn');
}, 500);
}
i++;
if (i <= round) {
playSimon();
}
else {
makeGuess();
}
}, 700);
}
Why is it alerting Game Over instantly on round 2?
Because you are binding the click events multiple times:
function makeGuess() {
$('#redButton').click(function() {
yourAnswer.push(0);
});
$('#blueButton').click(function() {
yourAnswer.push(1);
});
$('#greenButton').click(function() {
yourAnswer.push(2);
});
$('#yellowButton').click(function() {
yourAnswer.push(3);
});
...
}
Each time makeGuess() is called, the buttons are bound yet another click event listener. First time it's done (first level), there's only 1 event listener so it's working correctly, but from the second level onward each buttons are bound with 2 identical click listener, and when the player click a button, the function is called twice => yourAnswer is pushed twice immediately, which result in an incorrect answer => game over.
A quick fix is to unbind all click events on the 4 buttons before binding them all again, optimally immediately before the next playSimon() is called.
if (yourString === correctString) {
alert('Correct');
round++;
yourAnswer = [];
correctAnswer = [];
yourString = "";
correctString = "";
$('#redButton').unbind( "click" );
$('#blueButton').unbind( "click" );
$('#greenButton').unbind( "click" );
$('#yellowButton').unbind( "click" );
playSimon();
} else {
alert("Game Over!");
}
JsFiddle: https://jsfiddle.net/dfk2am7e/1/
AVAVT is right, however instead of unbinding, rather just bind the event once off.
I have updated your JSFiddle and optimized your code a little bit.
https://jsfiddle.net/dfk2am7e/3/
// Run this when the page has loaded to ensure HTML is there.
$(function(){
$('#redButton').click(function() {
yourAnswer.push(0);
});
$('#blueButton').click(function() {
yourAnswer.push(1);
});
$('#greenButton').click(function() {
yourAnswer.push(2);
});
$('#yellowButton').click(function() {
yourAnswer.push(3);
});
});

JavaScript function dosen't work correct

I have a function that checking board is there a searching element.
First script creating a board with different elements. Element in the square next to board is element that user has to find on the board and click them.
User has to click (as quick as possible) all searching elements. After click on element function checking a board, is there more elements. If yes then nothing happen and user has to click another one. If on board there isn’t searching elements then function display a time and new board create.
But some reason function works correct only first time after page load. Latter function ignore more then one element on board or see element that doesn’t exist on board any more.
Can you tell me what is wrong.
Part of code bellow and there is a link to testing page.
http://doomini2.linuxpl.info/font/
Thank you
function secondStage() {
createBoxes(59);
var usingSet = [];
var i = 0;
var boxList = document.querySelectorAll("#board > div");
createSet(usingSet, 20, shapes);
(function paint() {
if (i <= 59) {
var curentBox = boxList[i];
curentBox.className = usingSet[draw(20)];
curentBox.style.color = colors[draw(colors.length - 5)];
timeStop = setTimeout(paint, 50);
i++;
} else {
var findShape = boxList[draw(59)];
toFind.className = findShape.className;
toFind.style.color = findShape.style.color;
findBoxes(boxList);
clearTimeout(timeStop);
}
})();
}
//function checks boxes to find a proper shape
function findBoxes(boxList) {
startTime = Date.now();
board.addEventListener("mousedown", function (e) {
if ((e.target.className === toFind.className)) {
e.target.className = "correct";
e.target.innerHTML = "OK";
checkBoard();
} else if (e.target.id === "board" || e.target.className === "correct") {
} else {
e.target.className = "false";
e.target.innerHTML = "NO";
}
}, false);
function checkBoard() {
var condition = false;
console.log(condition);
for (var x = 0; x < boxList.length; x++) {
if ((boxList[x].className === toFind.className)) {
condition = true;
console.log(condition);
}
}
if (condition === false) {
var clickTime = Date.now();
var timeResult = parseFloat(((clickTime - startTime) / 1000).toFixed(3));
lastResult.innerHTML = timeResult + "s";
secondResult[secondResult.length] = timeResult;
console.log(secondResult);
displayResult(secondStage);
}
}
}
//function displaig results after every single round
function displayResult(stage) {
cover.className = "";
TweenMax.to("#lastResultDiv", 1, {ease: Back.easeOut, right: (winWidth / 4), });
TweenMax.to("#go", 1, {ease: Back.easeOut, top: (winWidth / 3), onComplete: function () {
goButton.addEventListener("click", function () {
clear();
}, false);
}});
//clear board and return to play
function clear() {
TweenMax.to("#lastResultDiv", 1, {ease: Back.easeIn, right: winWidth, });
TweenMax.to("#go", 1, {ease: Back.easeOut, top: -100, onComplete: function () {
cover.className = "hide";
lastResultDiv.style.right = "-592px";
toFind.className = "";
board.innerHTML = "";
if (firstStageRound === 10) {
secondStage();
} else if (secondStageRound === 5) {
thirdStage();
} else {
stage();
}
}});
}
}
Not Load this File http://cdnjs.cloudflare.com/ajax/libs/gsap/1.17.0/TweenMax.min.js
try to local path

Js and Divs, (even <div> is difference)

I Have find a javascript code that works perfectly for showing a DIV.
but this code works only for showing one div for each page.
i want to include many DIVS for hiding and showing in the same page.
I was try to replace the div id and show/hide span id with a rundom php number for each include, but still is not working.
so how i have to do it?
the JS code:
var done = true,
fading_div = document.getElementById('fading_div'),
fade_in_button = document.getElementById('fade_in'),
fade_out_button = document.getElementById('fade_out');
function function_opacity(opacity_value) {
fading_div.style.opacity = opacity_value / 100;
fading_div.style.filter = 'alpha(opacity=' + opacity_value + ')';
}
function function_fade_out(opacity_value) {
function_opacity(opacity_value);
if (opacity_value == 1) {
fading_div.style.display = 'none';
done = true;
}
}
function function_fade_in(opacity_value) {
function_opacity(opacity_value);
if (opacity_value == 1) {
fading_div.style.display = 'block';
}
if (opacity_value == 100) {
done = true;
}
}
// fade in button
fade_in_button.onclick = function () {
if (done && fading_div.style.opacity !== '1') {
done = false;
for (var i = 1; i <= 100; i++) {
setTimeout((function (x) {
return function () {
function_fade_in(x)
};
})(i), i * 10);
}
}
};
// fade out button
fade_out_button.onclick = function () {
if (done && fading_div.style.opacity !== '0') {
done = false;
for (var i = 1; i <= 100; i++) {
setTimeout((function (x) {
return function () {
function_fade_out(x)
};
})(100 - i), i * 10);
}
}
};
Check out the Fiddle, you can edit code based on your needs ;)
$(function() {
$('.sub-nav li a').each(function() {
$(this).click(function() {
var category = $(this).data('cat');
$('.'+category).addClass('active').siblings('div').removeClass('active');
});
});
});
finaly i found my self:
<a class="showhide">AAA</a>
<div>show me / hide me</div>
<a class="showhide">BBB</a>
<div>show me / hide me</div>
js
$('.showhide').click(function(e) {
$(this).next().slideToggle();
e.preventDefault(); // Stop navigation
});
$('div').hide();
Am just posting this in case someone was trying to answer.

HTML flashing text colors

This is quite an unusual request, but..
Is there anyway to make some text alternate between 2 colors every second?
So it appears as though it's flashing between say... red and grey? I don't mean background color, I mean the actual font color. I'm assuming it would need javascript or something.
Is there any simple way to do that?
(disregarding the fact it could look ugly)
UPDATE
Id like to call to this function several times on my page, each one passing along a different color to alternate with GREY
.
As per your request:
function flashtext(ele,col) {
var tmpColCheck = document.getElementById( ele ).style.color;
if (tmpColCheck === 'silver') {
document.getElementById( ele ).style.color = col;
} else {
document.getElementById( ele ).style.color = 'silver';
}
}
setInterval(function() {
flashtext('flashingtext','red');
flashtext('flashingtext2','blue');
flashtext('flashingtext3','green');
}, 500 ); //set an interval timer up to repeat the function
JSFiddle here: http://jsfiddle.net/neuroflux/rXVUh/14/
Here's an easy way to do it with plain JavaScript:
function flash() {
var text = document.getElementById('foo');
text.style.color = (text.style.color=='red') ? 'green':'red';
}
var clr = setInterval(flash, 1000);
This will alternate the color of the text between red and green every second. jsFiddle example.
Here's another example where you can set the colors of different elements:
function flash(el, c1, c2) {
var text = document.getElementById(el);
text.style.color = (text.style.color == c2) ? c1 : c2;
}
var clr1 = setInterval(function() { flash('foo1', 'gray', 'red') }, 1000);
var clr2 = setInterval(function() { flash('foo2', 'gray', 'blue') }, 1000);
var clr3 = setInterval(function() { flash('foo3', 'gray', 'green') }, 1000);
and the jsFiddle to go with it. You pass the ID of the element you want to flash and the two colors to alternate between.
With JavaScript it is very simple:
function alternateColor(color, textId, myInterval) {
if(!myInterval){
myInterval = 1000;
}
var colors = ['grey', color];
var currentColor = 1;
document.getElementById(textId).style.color = colors[0];
setInterval(function() {
document.getElementById(textId).style.color = colors[currentColor];
if (currentColor < colors.length-1) {
++currentColor;
} else {
currentColor = 0;
}
}, myInterval);
}
alternateColor('red','myText');
Call the function with the first argument being a color, the second being your text's ID, and third being the interval time (optional). Jsfiddle example
Here's some simple easy to understand code.
var count_x = 1,
max_x = 5; // Change this for number of on-off flashes
var flash_color_notify = setInterval(function () {
/* Change the color depending if it's even(= gray) or odd(=red) */
if (count_x % 2 === 0) { // even
$('#element').css('color', 'gray');
} else { // odd
$('#element').css('color', 'red');
}
/* Clear the interval when completed blinking */
if (count_x === max_x * 2) {
clearInterval(flash_color_notify);
} else { count_x += 1; }
}, 500);

Categories