Make Text Fade Out on Type - javascript

this is for a personal art project. What I basically want to do is create a blank web page where a user can type in text (like a text-editor), but have the text fade out as they type.
By fade out, I don't want the user to have the ability to see the text they had just written. So, I don't want to just transition the font color to match the background color as the user can select the text again.
So far, I've made a textarea that on keyup will store the text input, which will show in a separate div. I've specified in Javascript that when the entered text has reached a certain length: the div will fade out, clear the text, and show up again to show the current text input. The problem is that according to the console, I can't clear the value of the div. Does this make sense?
Here is a fiddle: http://jsfiddle.net/anelec/k40p72xk/5/
HTML:
<textarea type='text' id='myinput'></textarea>
<div><span id="fade"></span></div>
Javascript:
//on keyup store text input into a variable "text"
$( "#myinput" ).keyup(function( event ) {
var text = $("#myinput").val();
console.log("event working");
console.log(text);
//show values of "text" variable in id "fade"
$("#fade").text(this.value);
var fade = $("#myinput").val();
//function to clear text value of id "fade"
function cleartext(){
document.getElementById("#fade").value="";
}
//clear text value of id "fade" after 15 letters
if (fade.length >=15) {
$("#fade").fadeOut(200);
cleartext();
}
//show the incoming text input somehow
if (fade.length <=15) {
$("#fade").fadeIn("fast");
}
});
Please let me know if there is a better way I can approach this.

Try something like this:
// Keep track of how many sets of 15 chars there are
var accum = 0;
// If the length is divisible by 15
if (text.length % 15 == 0) {
$("#fade").fadeOut(200, function() {
accum ++;
// $(this) refers to $("#fade")
$(this).val(''); // set the value to an empty string
});
} else {
$("#fade").fadeIn('fast');
}
// Use the substring method to get every 15 characters to display in #fade
var start = accum * 15,
end = (accum + 1) * 15,
next = text.substring(start, end);
$("#fade").text(next);

This is the closest I've gotten:
Javascript:
$( "#myinput" ).keyup(function( event ) {
var text = $("#myinput").val();
console.log("event working");
console.log(text);
//show values of "text" variable in id "fade"
$("#fade").text(this.value);
var fade = $("#myinput").val();
if (text.length >=5) {
$("#fade").fadeTo(600,0);
$(this).val("");
$("#fade").fadeTo(20,1);
}
});

If I understood you correctly, this should work. You'll want to use the innerHTML instead of value.
Try changing:
function cleartext(){
document.getElementById("#fade").value="";
}
to this:
function cleartext(){
document.getElementById("#fade").innerHTML="";
}
You use value for input fields, and innerHTML for non-input fields.
Option 1:
$( "#myinput" ).keyup(function( event ) {
var text = $("#myinput").val();
console.log("event working");
console.log(text);
$("#fade").text(this.value);
var fade = $("#myinput").val();
function cleartext(){
document.getElementById("fade").innerHTML="";
// you use value this time because it's input field
document.getElementById("myinput").value = "";
}
if (fade.length >=15) {
$("#fade").fadeOut(200);
cleartext();
}
if (fade.length <=15) {
$("#fade").fadeIn("slow");
}
});
Option 2:
THIS EXAMPLE IS FROM ALEX CASSEDY - IF ITS THE BETTER ANSWER, GIVE HIM CREDIT AND NOT MINE, I SIMPLY FIXED ONE THING ON IT SO IT WORKS.
$( "#myinput" ).keyup(function( event ) {
var text = $("#myinput").val();
console.log("event working");
console.log(text);
$("#fade").text(this.value);
var fade = $("#myinput").val();
// Keep track of how many sets of 15 chars there are
var accum = 0;
// If the length is divisible by 15
if (text.length % 15 == 0) {
$("#fade").fadeOut(200, function() {
accum ++;
// $(this) refers to $("#fade")
$(this).val(''); // set the value to an empty string
});
} else {
$("#fade").fadeIn('fast');
}
// Use the substring method to get every 15 characters to display in #fade
var next = text.substring(fade.length - 15);
$("#fade").text(next);
});

Related

While loop to hide div elements

I am trying to create searchable content with the help of some JS yet am having trouble hiding the content when there is no input in the search field.
Here is my script:
var $searchContainer = $("#search");
var $contentBoxes = $searchContainer.find(".content");
var $searchInput = $searchContainer.find("#search-input");
var $searchBtn = $searchContainer.find("#search-btn");
$searchBtn.on("click", searchContent);
$searchInput.on("input", searchContent);
while($searchInput == null) {
for($contentBoxes) {
hide();
}
}
function searchContent(){
var userInput;
//Check if call comes from button or input change
if($(this).is(":button")){
userInput = $(this).siblings("input").val();
} else {
userInput = $(this).val();
}
//make the input all lower case to make it compatible for searching
userInput = userInput.toLowerCase();
//Loop through all the content to find matches to the user input
$contentBoxes.each(function(){
var headerText = $(this).find(".title").text();
var contentText = $(this).find(".description").text();
//add the title and content of the contentbox to the searchable content, and make it lower case
var searchableContent = headerText + " " + contentText;
searchableContent = searchableContent.toLowerCase();
//hide content that doesn't match the user input
if(!searchableContent.includes(userInput)){
$(this).hide();
} else {
$(this).show();
}
});
};
I understand a while loop could have a condition where if userInput is equal to null it would loop through each content box and hide the element.
Something like this maybe?
while($searchInput == null) {
$contentBoxes.each(function(){
hide();
}
}
Any help would be greatly appreciated.
You would need to update your userInput variable every cycle of the loop because the userInput value never gets updated. Nonetheless this not a good way to do this because you will block your entire application.
There is no need for a loop, just use an if statement. Also, because this function gets executed when the value of the input is changed, there is no need to use this.
You could put this block of code beneath your $contentBoxes.each function:
$contentBoxes.each(function(){
var headerText = $(this).find(".title").text();
var contentText = $(this).find(".description").text();
//add the title and content of the contentbox to the searchable content, and make it lower case
var searchableContent = headerText + " " + contentText;
searchableContent = searchableContent.toLowerCase();
//hide content that doesn't match the user input
if(!searchableContent.includes(userInput)){
$(this).hide();
} else {
$(this).show();
}
});
if (userInput === null) {
$contentBoxes.each(function(){
$(this).hide();
});
}
I think it will be work like this. You just check if search input !== null and dont hide any content in this case
if($searchInput != null && !searchableContent.includes(userInput)){
$(this).hide();
} else {
$(this).show();
}

Form calculator based on input values

I am working on a Cardio Test calculator which calculates heart attack risk. I want to get score based value for each input. The results logic is already working, I just need to get result score value. See the code below.
<script>
$(document).ready(function() {
$("#female").change(function() {
if ($(this).is(":checked")) {
$("#femaleage").show();
$("#maleage").hide();
}
});
$("#male").change(function() {
if ($(this).is(":checked")) {
$("#maleage").show();
$("#femaleage").hide();
}
});
$( "#cardio__test" ).submit(function( event ) {
event.preventDefault();
if ($("#score").val() <= 3) {
$(".risk__score.low__risk").show();
}
if ($("#score").val() >= 4 && $("#score").val() <= 6) {
$(".risk__score.moderate__risk").show();
}
if ($("#score").val() >= 7) {
$(".risk__score.high__risk").show();
}
if ($("#maleage").val() >= 70) {
$("#score").val() + 8;
}
$(this).hide();
});
});
</script>
Here's a link!
I tested out your codepen and I found out the value of your score is a string type instead of int as I tested using parseInt() and typeof... and the result string value is blank (maybe i changed some code in the codepen during testing) How do you check the value of the score and do you get it as a number? Anyway, to print out the result value you can do it in many ways such as
adding a new div in your results div and print the results inside the div
$(".(new div class name) h3").text($("#score").val());
or simply alert the results
alert($("#score").val());
you can simply use
var scoreValue = $("#score").val();

Having Button not run Function With Empty Input Field

So I have a button that whenever clicked appends whatever the user entered below the input field. I want to make it so when clicked with an empty field nothing appends (essentially the function does not run).
Here is my code:
var ingrCount = 0
$("#addIngrButton").on('click', function() {
var ingredientInput = $("#ingredients").val().trim();
var ingredientSpace = $("<p>");
ingredientSpace.attr("id", "ingredient-" + ingrCount);
ingredientSpace.append(" " + ingredientInput);
var ingrClose = $("<button>");
ingrClose.attr("data-ingr", ingrCount);
ingrClose.addClass("deleteBox");
ingrClose.append("✖︎");
// Append the button to the to do item
ingredientSpace = ingredientSpace.prepend(ingrClose);
// Add the button and ingredient to the div
$("#listOfIngr").append(ingredientSpace);
// Clear the textbox when done
$("#ingredients").val("");
// Add to the ingredient list
ingrCount++;
if (ingredientInput === "") {
}
});
So I wanted to create an if statement saying when the input is blank then the function does not run. I think I may need to move that out of the on click function though. For the if statement I added a disabled attribute and then removed it when the input box contains something. But that turns the button another color and is not the functionality I want. Any ideas I can test out would help. If you need any more information please ask.
If you're testing if ingredientInput is empty, can you just return from within the click event?
$("#addIngrButton").on('click', function() {
var ingredientInput = $("#ingredients").val().trim();
if(ingredientInput === '') { return; }
// rest of code
Simply use :
$("#addIngrButton").on('click', function() {
var ingredientInput = $("#ingredients").val().trim();
if (ingredientInput.length == 0) {
return false;
}
// ..... your code

How to manipulate clipboard data using jquery in chrome, IE 8&9?

This is my jquery code that I am using to truncate the pasted text, so that it doesn't exceed the maxlength of an element. The default behaviour on Chrome is to check this automatically but in IE 8 and 9 it pastes the whole text and doesn't check the maxLength of an element. Please help me to do this. This is my first time asking a question here, so please let me know if I need to provide some more details. Thanks.
<script type="text/javascript">
//var lenGlobal;
var maxLength;
function doKeypress(control) {
maxLength = control.attributes["maxLength"].value;
value = control.value;
if (maxLength && value.length > maxLength - 1) {
event.returnValue = false;
maxLength = parseInt(maxLength);
}
}
//function doBeforePaste(control) {
//maxLength = control.attributes["maxLength"].value;
//if (maxLength) {
// event.returnValue = false;
//var v = control.value;
//lenGlobal = v.length;
// }
// }
$(document).on("focus","input[type=text],textarea",function(e){
var t = e.target;
maxLength = parseInt($(this).attr('maxLength'));
if(!$(t).data("EventListenerSet")){
//get length of field before paste
var keyup = function(){
$(this).data("lastLength",$(this).val().length);
};
$(t).data("lastLength", $(t).val().length);
//catch paste event
var paste = function(){
$(this).data("paste",1);//Opera 11.11+
};
//process modified data, if paste occured
var func = function(){
if($(this).data("paste")){
var dat = this.value.substr($(this).data("lastLength"));
//alert(this.value.substr($(this).data("lastLength")));
// alert(dat.substr(0,4));
$(this).data("paste",0);
//this.value = this.value.substr(0,$(this).data("lastLength"));
$(t).data("lastLength", $(t).val().length);
if (dat == ""){
this.value = $(t).val();
}
else
{
this.value = dat.substr(0,maxLength);
}
}
};
if(window.addEventListener) {
t.addEventListener('keyup', keyup, false);
t.addEventListener('paste', paste, false);
t.addEventListener('input', func, false);
} else{//IE
t.attachEvent('onkeyup', function() {keyup.call(t);});
t.attachEvent('onpaste', function() {paste.call(t);});
t.attachEvent('onpropertychange', function() {func.call(t);});
}
$(t).data("EventListenerSet",1);
}
});
</script>
You could do something like this, mind you this was done in YUI but something simlar can be done for jquery. All you need to do is get the length of the comment that was entered and then truncate the text down the the desired length which in the case of this example is 2000 characters.
comment_text_box.on('valuechange', function(e) {
//Get the comment the user input
var comment_text = e.currentTarget.get('value');
//Get the comment length
var comment_length = comment_text.length;
if(comment_length > 2000){
alert('The comment entered is ' + comment_length + ' characters long and will be truncated to 2000 characters.');
//Truncate the comment
var new_comment = comment_text.substring(0, 2000);
//Set the value of the textarea to truncated comment
e.currentTarget.set('value', new_comment);
}
});
You're putting too much effort into something that is apparently a browser quirk and is mostly beyond your control and could change in the future. In fact, I can't recreate this in IE10 - it behaves just like Chrome for me.
Make sure you are validating the length on the server-side, since it's still possible to get around a field's maxlength when submitting the form input to the server (see this somewhat similar question). That's not to say you shouldn't have some client-side logic to validate the length of the input to enforce the maxlength constraint - I just think you don't need to go to the length you are attempting here to essentially intercept a paste command. Keep it simple - having a basic length validation check in your JavaScript is going to be a lot less messy than what you have here.
Perhaps consider a bit of jQuery like this:
$("#myTextControl").change(function() {
if ($(this).val().length > $(this).attr('maxlength')) {
DisplayLengthError();
}
});
(where DisplayLengthError() is an arbitrary function that triggers some kind of feedback to the user that they have exceeded the maxlength constraint of the field, be it an error label, and alert box, etc.)

Show element if has same html and if not make an alert saying "no results"

Sorry for the horrible title, Am terrible at wording these things.
What I am trying to do is quite simple I think.
I have a set of hidden letters that make up a word.
Below them is a selection of random jumbled up letters.
When people click one of the random jumbled letters I am filtering through the hidden letters and showing the corresponding letter.
What I need to do is, if someone clicks a letter, filter through the hidden letters and either return a "true" and show the letter or return a "false/null" and make an alert();
This is how I am filtering at the moment. I am confused as to where to place an if statement or if that is even the approach I should be taking.
And here is a fiddle (the hidden word is "Seal") - http://jsfiddle.net/GA7WB/
var $buttons = $('#letters span'),
$hidden = $('.letter');
$buttons.click(function(){
_selected = $(this).html();
$hidden.filter(function() {
return $(this).text() == _selected;
}).show();
});
You just need to check the length of the results returned by the filter:
// get matched elements
var matches = $hidden.filter(function() {
return $(this).text() == _selected;
});
// show them, or alert if none
if (matches.length > 0) matches.show();
else alert("There are no " + _selected + "'s");
See Fiddle
Try setting a flag if you find one:
var $buttons = $('#letters span'),
var $hidden = $('.letter');
$buttons.click(function(){
_selected = $(this).html();
var foundOne = false;
$hidden.filter(function() {
var retval = $(this).text() == _selected;
if (retval) foundOne = true;
return retval;
}).show();
if (!foundOne) {
alert("Nope");
}
});
FIDDLE http://jsfiddle.net/GA7WB/4/

Categories

Resources