jQuery placeholder/hint JavaScript that keeps the hint on focus - javascript

There are hundreds of jQuery placeholder/hint plugin. But none that do what I want it to do
I'm looking for one that will:
Fade the hint when the user focuses on the field, but not clear it until the user starts typing (like the StackOverflow/iOS one)
Will work with the HTML5 placeholder attribute.
Built with jQuery
Cross browser (including IE7/IE8)
Uses unobtrusive JavaScript
Ideally would also Work with password fields

#Roatin Marth is right; if you're going to treat the text as a placeholder, it's supposed to clear. That's the very definition of a placeholder.
Still, I mocked up a proof of concept that you're welcome to use as you like. However, I had to make the placeholder text so light it's barely viewable to keep it from garbling the front text too much (which is why the default behavior is to clear it).
You can see it working at: http://jsfiddle.net/zYQ4Q/4/
// Create placeholder input to serve as background
var $test = $('#test');
var $placeholder = $test.clone().removeAttr('id').removeAttr('placeholder').addClass('placeholder').val($test.attr('placeholder'));
var $container = $('<span class="placeholder-container"></span>');
$container.insertAfter($test).append($test).append($placeholder);
// Basic styling
$container.css({
position: 'relative'
});
$test.css({
position: 'absolute',
left: 0,
top: 0,
zIndex: 10,
backgroundColor: 'transparent',
borderColor: 'transparent'
});
$placeholder.css('color', 'transparent');
// Behavior for focus and blur to achieve the visual effect
$test.focus(function(){
var $input = $(this);
var $placeholder = $('.placeholder', $input.parent());
$placeholder.css('color', '#e0e0e0');
}).blur(function(){
var $input = $(this);
var $placeholder = $('.placeholder', $input.parent());
if ($input.val() == '')
$placeholder.css('color', 'transparent');
}).keyup(function(){
var $input = $(this);
if ($input.val().trim() != '') {
$placeholder.val('');
} else {
$placeholder.val($input.attr('placeholder'));
}
});
UPDATE: Code and jsfiddle have been updated to reflect new changes based on OP's comment. The placeholder now clears after text has been entered into the input.

Update, thanks to chrisdpratt I've actually found a plugin that does what I want it to:
Demo: http://labs.mario.ec/jq-watermark/
Source: https://github.com/marioestrada/jQuery-Watermark

Related

button 'quote' & display into tinymce textarea

I just created a 'quote' button, when we press it, i want it take a text and put it in a textarea.
It works with a basic textarea but I still have a problem,
I use the editor 'Tinymce' .., & I can't put the text in this one .
$(function() {
var $answer = $('#answer');
var $answerTa = $answer.find('textarea');
$('.quote').click(function(e) {
var parent = $(this).parent();
var postContent = parent.find('p').text();
var quote = '[QUOTE]';
quote += postContent+'[/QUOTE]';
var answerTaContent = $answerTa.val();
$answerTa.val(answerTaContent+quote);
$('html, body').animate({
scrollTop: 0},"slow");
});
});
When TinyMCE appears on a page the original textarea is replaced by a series of divs and an iframe. Once TinyMCE appears you cannot use jQuery to interact with the editor - you should use its own APIs. There is an API to insert content at the location of the cursor:
https://www.tiny.cloud/docs/api/tinymce/tinymce.editor/#insertcontent
...or to replace the editor's contents entirely:
https://www.tiny.cloud/docs/api/tinymce/tinymce.editor/#setcontent

Javascript - Submit Text Field, Show Div, Hide All Others

I have a simple form (text field and submit button). I am trying to have the user submit a number, and the resulting number will display one div (from a set of divs).
I tried using this example as a base (when the user clicks a link, it shows a div, but hides others).
My test is below:
var divState = {};
function showhide(oFrm) {
var dividnum = oFrm.Inputed.value;
var prepar = "para";
var divid = prepar + theInput; /* should result in something like "para52" */
divState[divid] = (divState[divid]) ? false : true;
//close others
for (var div in divState){
if (divState[div] && div != divid){
document.getElementById(div).style.display = 'none';
divState[div] = false;
}
}
divid.style.display = (divid.style.display == 'block' ? 'none' : 'block');
}
http://jsfiddle.net/LfzYc/431/
Note: I am NOT proficient in JavaScript at all, which is why I am having difficulty.
Also, I'd like to add a function ... if the number entered is not between 1-4, show a different div, maybe with the id paraEnd.
Please look at the jsFiddle based on your one. I hope I've done what you want. I changed the showhide function and your HTML (fixed div's IDs and added one more div#paraEnd). I'd suggest you refactoring your code.
You should use jQuery to have an easy way to manipulate the DOM.
Using jQuery I made an example for you, just change your JS and paste mine:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
(function ($) {
// get the paragraphs
var paragraphs = $('.paragraph');
// form submit
$('#paragraphform').submit(function (e) {
// prevent the event to flow
e.preventDefault();
// get the input value
var value = $('#Inputed').val() - 1;
// reset all divs removing active css class
paragraphs.removeClass('active');
$('.error').removeClass('active');
// verify if the value doens't exist
if(value < 0 || value > paragraphs.length - 1) {
$('.error').addClass('active');
return;
}
// show the active div
paragraphs.eq(value).addClass('active');
});
})(jQuery);
</script>
Is that what you need?
If you not familiar with jQuery, this is the jquery Learn Center:
https://learn.jquery.com/
And this is a nice tutorial for beginners:
http://www.tutorialspoint.com/jquery/

Is there a method to autofit each textarea to the size of it's data returned from a database query?

I have many different queried field data returning various height and lenghts from a database to multiple variables that are mapped to its own textarea on a web page for display. I need a way to have each textarea auto-fit the data according to its size returned.
Currently I use a javascript function(data-autoresize) for each textarea to allow users to expand the text when the fields are larger than the textarea:
i.e.
$(document).ready(function () {
jQuery.each(jQuery('textarea[data-autoresize]'), function () {
var offset = this.offsetHeight - this.clientHeight;
var resizeTextarea = function (el) {
jQuery(el).css('height', 'auto').css('height', el.scrollHeight + offset);
};
jQuery(this).on('keyup input', function () {
resizeTextarea(this);
}).removeAttr('data-autoresize');
});
});
<textarea title="If needed, hit ENTER to expand this text area." class="textExpand" readOnly="true" data-autoresize rows="10"> **returnDataFieldVar1** <textarea>
This is useful for users to expand manually after data is loaded and too large for the default textarea size of 10 rows. But to make this more efficient and functional, it would be preferred to have each textarea auto-fit to the data that was returned from the query and eliminate users having to manually expand the textareas on the webpage. Any pointers or code examples on how to do this is appreciated!
You looking for something like this?
$(window).on('resize', function(e) {
$('textarea[data-autoresize]').each(function() {
var $textarea = $(this);
$textarea.css('height', 'auto');
$textarea.css('height', $textarea.prop('scrollHeight') + 'px');
});
})
$('textarea[data-autoresize]').each(function() {
$(this).on('keyup input change paste propertychange', function(e) {
var $textarea = $(this);
$textarea.css('height', 'auto');
$textarea.css('height', $textarea.prop('scrollHeight') + 'px');
});
});
https://jsfiddle.net/ff0xjm4q/
On any change set the height to the scrollHeight.
Also handle it on window resize as well since there is no textarea resize event.

ie8 appendchild not working

I am developing a website that must run on IE8.
I need to create a bunch of dynamic paragraphs since I am pulling data from a server at runtime.
To do so I am using the following code:
var tempAbstract = layerItems[iter].abstract; // string
var text1 = document.createElement('p'); // paragraph element
text1.textContent = tempAbstract; // assigning string to paragraph
$(text1).css({top: iter*25 + 30, left: 200, position:'absolute'}); // positioning
$(text1).css('color', 'black'); // make text color black
document.getElementById("listLayersWrapper").appendChild(text1); // appending to div
My problem is that the text won't render.
When I count the paragraph divs before and after I add the element, the counter increments as you would expect it should yet the text does not render. Additionally, when I get call position().left and position.top() the element also has the right coordinates.
I am not sure what I am doing wrong and have run out of options.
The issue doesn't appear to be with appendChild, but with textContent. According to the MDN page, textContent is only available in IE9 and up. Older versions of IE do have a non-standard innerText property you can use to achieve the same thing. Here is how you can implement this.
Example:
var tempAbstract = layerItems[iter].abstract;
var text1 = document.createElement('p');
if(text1.textContent !== undefined)
{
text1.textContent = tempAbstract;
}else{
text1.innerText = tempAbstract;
}
$(text1).css({top: iter*25 + 30, left: 200, position:'absolute'});
$(text1).css('color', 'black');
document.getElementById("listLayersWrapper").appendChild(text1);
Alternatively, this could be implemented in jQuery.
Example:
$('<p></p>')
.text(layerItems[iter].abstract)
.css({
top: iter*25 + 30,
left: 200,
position:'absolute',
color: 'black'
})
.appendTo("#listLayersWrapper");

How can I best make an inline span draggable within a paragraph of text?

I have a paragraph of text in which the user may place a "pin" to mark a position. Once a pin has been placed, I would like to allow the user to move its position by dragging it to a new location in the paragraph. This is simple to do with block elements, but I have yet to see a good way to do it with inline elements. How might I accomplish this?
I have already implemented it using window.selection as a way to find the cursor's location in the paragraph, but it is not as smooth as I would like.
As a note, I am using the Rangy library to wrap the native Range and Selection functionality, but it works the same way as the native functions do.
Here is the code:
$(document).on("mousedown", '.pin', function () {
//define what a pin is
var el = document.createElement("span");
el.className = "pin";
el.id = "test";
//make it contain an empty space so we can color it
el.appendChild(document.createTextNode("d"));
$(document).on("mousemove", function () {
//get the current selection
var selection = rangy.getSelection();
//collapse the selection to either the front
//or back, since we do not want the user to see it.
if (selection.isBackwards()) {
selection.collapseToStart();
} else {
selection.collapseToEnd();
}
//remove the old pin
$('.pin').remove();
//place the new pin at the current selection
selection.getAllRanges()[0].insertNode(el);
});
//remove the handler when the user has stopped dragging it
$(document).on("mouseup", function () {
$(document).off("mousemove");
});
});
And here is a working demo: http://jsfiddle.net/j1LLmr5b/22/ .
As you can see, it works(usually), but the user can see the selection being made. Have any ideas on how to move the span without showing the selection highlight? I will also accept an alternate method that does not use the selection at all. The goal is to allow movement of the span as cleanly as possible.
You can do this using ranges instead using code similar to this answer. Unfortunately the code is a bit longer than ideal because IE hasn't yet implemented document.caretPositionFromPoint(). However, the old proprietary TextRange object, still present in IE 11, comes to the rescue.
Here's a demo:
http://jsfiddle.net/j1LLmr5b/26/
Here's the relevant code:
var range, textRange, x = e.clientX, y = e.clientY;
//remove the old pin
$('.pin').remove();
// Try the standards-based way first
if (document.caretPositionFromPoint) {
var pos = document.caretPositionFromPoint(x, y);
range = document.createRange();
range.setStart(pos.offsetNode, pos.offset);
range.collapse();
}
// Next, the WebKit way
else if (document.caretRangeFromPoint) {
range = document.caretRangeFromPoint(x, y);
}
// Finally, the IE way
else if (document.body.createTextRange) {
textRange = document.body.createTextRange();
textRange.moveToPoint(x, y);
var spanId = "temp_" + ("" + Math.random()).slice(2);
textRange.pasteHTML('<span id="' + spanId + '"> </span>');
var span = document.getElementById(spanId);
//place the new pin
span.parentNode.replaceChild(el, span);
}
if (range) {
//place the new pin
range.insertNode(el);
}
Try this my friend
el.appendChild(document.createTextNode("d"));
You have create empty span tag that's why you found empty.
add after
el.id = "test";
this
var value = $('.pin').text();
$(el).text(value);
You can hide selection with css
::selection {color:red;background:yellow;}
::-moz-selection {color:red;background:yellow;}
that's all how i can help for a now

Categories