I am trying to toggle a div so it shows and hides when a user enters text into textarea.
i am using the below code and its not working for me, can anyone please show me why? thanks
html:
<head>
<script>
$(document).ready(function() {
$("#cname").keyup(function() {
if ($("#cname").val() > 8) {
$('#cname2').toggle("slow");
}
});
});
</script>
</head>
<form>
<input type="text" id="cname" name="cname" class="field">
<div id="cname2"></div>
</form>
css:
#cname2{
width:30px;
height:30px;
position:absolute;
margin-top:-13px;
margin-left:400px;
background-image: url('tick.png');
background-repeat:no-repeat;
background-position:right;
display:none;
}
so apparently my above code doesnt work in IE 9, but i should be able to achieve what i am trying to do by using this code, but can someone please show me where i place my div ID/how i adapt it to work for me?
var activeElement = null;
var activeElementValue = null;
// On focus, start watching the element
document.addEventListener("focusin", function(e) {
var target = e.srcElement;
if (target.nodeName !== "INPUT") return;
// Store a reference to the focused element and its current value
activeElement = target;
activeElementValue = target.value;
// Listen to the propertychange event
activeElement.attachEvent("onpropertychange", handlePropertyChange);
// Override .value to track changes from JavaScript
var valueProp = Object.getOwnPropertyDescriptor(
HTMLInputElement.prototype, 'value');
Object.defineProperty(activeElement, {
get: function() { return valueProp.get.call(this); },
set: function(val) {
activeElementValue = val;
valueProp.set.call(this, val);
}
});
});
// And on blur, stop watching
document.addEventListener("focusout", function(e) {
if (!activeElement) return;
// Stop listening to propertychange and restore the original .value prop
activeElement.detachEvent("onpropertychange", handlePropertyChange);
delete activeElement.value;
activeElement = null;
activeElementValue = null;
});
function handlePropertyChange(e) {
if (e.propertyName === "value" &&
activeElementValue !== activeElement.value) {
activeElementValue = activeElement.value;
// Fire textchange event on activeElement
}
};
$(document).ready(function() {
$("#cname").keyup(function() {
if ($("#cname").val().length > 8) {
$('#cname2').show();
} else {
$('#cname2').hide();
}
});
});
One possible approach (demo):
$(document).ready(function() {
$("#cname").on('input', function() {
$('#cname2')[this.value.length > 8 ? 'hide' : 'show']('slow');
});
});
Here I assumed that in cname2 container there's some warning message, that has to be shown if length of text input is 8 or less characters. Note also that I've used oninput handler, not keyup: as it allows me to process mouse-driven cut-and-paste as well as direct input. The only drawback is that IE8 doesn't support this event (and IE9 support for it is rather buggy, as handler is not fired when character is removed from text input).
Use this Javascript function
var z = document.getElementById('cname');
z.onkeyup = function(){
document.getElementById('cname2').innerHTML = z.value;
}
Your HTML:
<input type='text' name='cname' class='field' id='cname'>
<div class='cname2' id='cname2'></div>
Checkout here: http://jsfiddle.net/iamsajeev/Q9LPv/
$(document).ready(function() {
$("#cname").keyup(function() {
if ($("#cname").val() > 8) {
$('#cname2').fadeIn("slow");
}
else
{
$('#cname2').fadeOut("slow");
}
});
});
http://jsfiddle.net/5EjP7/2/
I hope that helps
Try the following script:
$(document).ready(function() {
$("#cname").keyup(function() {
if ($("#cname").val().length > 8) {
$('#cname2').toggle("slow");
}
});
});
Related
I need to delete all children of a div after clicking enter.
There is a div and event listener below.
<div id = "area" contenteditable="true"></div>
document.onreadystatechange = function(){
if(document.readyState == 'complete'){
document.getElementById("area").addEventListener("keypress" , public_mode);
}
function public_mode(){
var key = window.event.keyCode;
if (key == 13) {
sendMessage();
}
}
function sendMessage(){
var area = document.getElementById("area");
while (area.firstChild) {
area.removeChild(area.firstChild);
}
}
As you can see the contenteditable elements is added an element in according with clicking enter - it depends on browser what element will be added.In my case I use chrome and here are inserted div.
So, the result after clicking enter on the area but without removing
<div id = "area" contenteditable = "true">
Sckoriy
<div></div>
</div>
and , with removing
<div id = "area" contenteditable = "true">
<div></div>
<div></div>
</div>
But , the needed result is
<div id = "area" contenteditable = "true">
//Empty
</div>
The code mostly works, however there were two main issues.
keyCode is deprecated. you should be using key which turns the syntax of searching for a key into looking for a string. This means instead of 13 you just check to see if key is Enter.
Secondly you need to pass the event to your public_mode function so that you can read the key that has been pressed when the event occurs. You also need to use preventDefault to prevent it from adding a new line after removing everything from the original contentEditable area when it does detect Enter
document.onreadystatechange = function() {
if (document.readyState == 'complete') {
document.getElementById("area").addEventListener("keypress", public_mode);
}
function public_mode(event) {
var key = event.key;
if (key === "Enter") {
event.preventDefault();
sendMessage();
}
}
function sendMessage() {
var area = document.getElementById("area");
while (area.firstChild) area.removeChild(area.firstChild);
}
}
#area {
min-width: 100vw;
border: 1px solid black;
}
<div id="area" contenteditable="true"></div>
You could just set the innerHTML proprety to an empty string;
area.innerHTML = '';
target the dom by id
var s = document.getElementById("area");
save the number of childrens
var num = s.children.length;
and remove the num of childs of element
for(var i=0;i<num;i++){
s.children[0].remove()
}
and inner for some thext
s.innerHTML = "";
Pass the key event as an argument to your function.
Also, if you do not want the newline entered in your div, you can prevent the event from continuing with event.preventDefault().
document.onreadystatechange = function() {
if (document.readyState == 'complete') {
const area = document.getElementById('area')
area.addEventListener('keypress', public_mode);
area.focus();
}
}
function public_mode(event) {
if (window.event.keyCode == 13) {
sendMessage();
event.preventDefault();
}
}
function sendMessage() {
const area = document.getElementById('area');
while (area.firstChild) {
area.removeChild(area.firstChild);
}
}
<div id="area" contenteditable="true">Press Enter to erase me!</div>
I have an input[type=text] area and i'll paste/type a URL in it.
If pasted/typed url contains http, i want to hide $('#button') element.
If its not, keep showing the button also.
Thanks for any help.
Here is my demo code so far:
$('#pasteUrl').on('input', function () {
var str = $('#pasteUrl').val();
if (str.indexOf("http") !== -1) {
$('#button').hide();
}
});
Edit: Added "propertychange" to events as suggested by OP in the comments.
$('#pasteUrl').on('input propertychange', function (ev) {
var str = $(ev.currentTarget).val();
if (str.indexOf("http") != -1) {
$('#button').hide();
} else {
$('#button').show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="pasteUrl" />
<button id="button">Go</button>
This is likely what you want - using toggle:
$('#pasteUrl').on('input propertychange', function() {
var str = $(this).val();
$('#button').toggle(str.indexOf("http") == -1);
});
Say I want to activate myFunction only if the user has pressed the paragraph with a key and clicks on it. In the case below, the function will get triggered if any of the events is true.
<p id="p1" onClick="myFunction()" onKeyDown="myFunction()">
Text awaiting to be colored in red</p>
<script>
function myFunction(){
document.getElementById("p1").style.color = "red";
}
</script>
You need one extra variable isKeyDown, and isKeyDown should be set to true on keydown, and set to false on keyup.
And than in click callback check is isKeyDown true, call myFunction.
An example of how you could do it. This works with Enter and normally clicking it. Really you don't need to make p focus but I thought it was neat, even though you can still handle the key events from the document and since the click only registers on p there's nothing to worry about.
var p = document.getElementById('p1');
p.addEventListener('mousedown', function(e) {
p.clicked = true;
checkEvents(p);
});
p.addEventListener('mouseup', function(e) {
p.clicked = false;
});
p.addEventListener('keydown', function(e) {
if (e.keyCode === 13) {
p.enterDown = true;
}
});
p.addEventListener('keyup', function(e) {
checkEvents(p);
if (e.keyCode === 13) {
p.enterDown = false;
}
});
function checkEvents(el){
if(el.enterDown && el.clicked){
el.style.backgroundColor = 'red';
}
}
p:focus {
outline: none;
}
<p id="p1" tabindex='0'>
Text awaiting to be colored in red</p>
You'll need to breakdown into two methods. First is keystrokes->click and then click->keystrokes. I'm not sure if this is achievable on pure/vanilla javascaript. But on jquery it goes something like:
$('#p1' ).keydown(function() {
if($('#p1').click()) {
document.getElementById("p1").style.color = "red";
}
});
$('#p1')click(function () {
if($('#p1').keydown()) {
document.getElementById("p1").style.color = "red";
}
});
I'm able to replace/remove a certain value of an input when a label is clicked, here is my code:
$("#labelid").on("click",function() {
if($("#inputid").val('sometexthere'));
{
$("#inputid").val('');
}
});
The code deletes the value sometexthere each time the label is clicked. I want to limit this to only once, so if the label is clicked for the first time it deletes the value and if it clicked for the second time, it does nothing (leave value as it is).
How can I do this?
Answers would be greatly appreciated.
Use .one() method.
Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
$("#labelid").one("click",function() {
if($("#inputid").val() === 'sometexthere') // remove the ;
{
$("#inputid").val('');
}
});
The val('...')in if($("#inputid").val('sometexthere')) is assigning the value, and not comparing - $("#inputid").val() === '...' .
Note : As j08691 suggests here if its just related to initial text/placeholder use <input placeholder="sometexthere"/>
var click = false;
$("#labelid").on("click",function() {
if(!click){
if($("#inputid").val('sometexthere'));
{
$("#inputid").val('');
}
click = true;
}
});
this will work :)
In your code $("#inputid").val('sometexthere') is always true because what is happening there is setting a value to the field. The val method returns jQuery object so it is basically truthy.
One of the solutions indeed is the .one method which assigns the event listener only once. However, you may need to do other things on the click event. So I'll go with a flag:
var flag = true;
$("#labelid").on("click",function() {
var input = $("#inputid");
var current = input.val();
if(current === 'sometexthere' && flag) {
flag = false;
input.val('');
}
});
And by the way, consider the usage of the placeholder attribute.
In case you've been persuaded by the argument to use a placeholder instead here's an example implementation that includes a fallback for browsers that don't natively support HTML5 Placeholders (ahem <=IE9)...
$(function() {
//test if placeholder is natively supported:
function hasPlaceholder() {
var test = document.createElement('input');
return ('placeholder' in test);
}
//if placeholder is not natively supported initialise this method to replicate the behaviour
if(!hasPlaceholder){
$('[placeholder]').focus(function() {
var $this = $(this);
if ($this.val() == $this.attr('placeholder')) {
$this.val('')
.removeClass('placeholder');
}
}).blur(function() {
var $this = $(this);
if ($this.val() == '' || $this.val() == $this.attr('placeholder')) {
$this.addClass('placeholder')
.val($this.attr('placeholder'));
}
}).blur();
//on submit, make sure we remove any fo placeholder values
$('[placeholder]').parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var $this = $(this);
if ($this.val() == $this.attr('placeholder')) {
$this.val('');
}
})
});
}
});
/* You can style placeholders... */
input.placeholder {color:#66aaee;}
::-webkit-input-placeholder {color: #66aaee;}
:-moz-placeholder {color: #66aaee;}
::-moz-placeholder {color: #66aaee;}
:-ms-input-placeholder {color: #66aaee;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Label: <input name="inputname" id="inputid" placeholder="this is the placeholder" /></label>
You could use jQuery.off() after the link is clicked the first time. I think the placeholder is a nice idea, but I don't know if it accomplishes what you want, and if you need backwards compatibility you would need a shim to handle the placeholder property. I agree with the accepted answer if the detachment of the event handler is unconditional.
If detachment of the event handler is conditional, I think this is cleaner:
$("#labelid").on("click",function() {
var $input = $("#inputid");
if($input.val().length > 0) {
$input.val('');
$(this).off("click");
}
});
I am using the below placeholder code for IE8, however about 70% of the time when you move your mouse around in the dropdown login field it loses focus (the whole dropdown login field vanishes); through debugging - when I remove this code the problem goes away - I have found the cause of the problem is this code:
Edit: I have found it isn't caused by any particular placeholder code, but it IS caused by some part of the process as I have tried 3 separate placeholder plugins and it happens on all 3 of them; take them away and no problems.
$(document).ready(function() {
if ( !("placeholder" in document.createElement("input")) ) {
$("input[placeholder], textarea[placeholder]").each(function() {
var val = $(this).attr("placeholder");
if ( this.value == "" ) {
this.value = val;
}
$(this).focus(function() {
if ( this.value == val ) {
this.value = "";
}
}).blur(function() {
if ( $.trim(this.value) == "" ) {
this.value = val;
}
})
});
// Clear default placeholder values on form submit
$('form').submit(function() {
$(this).find("input[placeholder], textarea[placeholder]").each(function() {
if ( this.value == $(this).attr("placeholder") ) {
this.value = "";
}
});
});
}
});
You can view an example here: http://condorstudios.com/stuff/temp/so/header-sample.php
Edit: Not sure if it will help as jsfiddle doesn't work on IE8 and I can't test if the fiddle behaves badly in IE8 too, but here is the fiddle: http://jsfiddle.net/m8arw/7/
Any way to fix this?
Have you tried switching your event to show/hide dropdown to 'mouseenter' and 'mouseleave'?
It's a lot more reliable on old IE than 'focus' and 'blur' event. Also, bind the event directly on the 'dropdown' div is more preferable than on the 'input' element.
In short, please try change this part of your code like this.
$(function() {
var dropdown = $('div.login div.dropdown')
.on('mouseenter', function() {
dropdown.css('display', 'block');
})
.on('mouseleave', function() {
dropdown.removeAttr('style');
});
});
demo: http://so.devilmaycode.it/placeholder-code-used-for-ie8-causing-dropdown-login-field-to-lose-focus
$(function(){
$('#main_header .login li').hover(function(){
$(this).find('.dropdown').show();
},function(){
$(this).find('.dropdown').hide();
});
});
NOTE: i have also cleaned up and fixed some coding horror in your js code...
I use this code to implement placeholder on all browsers (it uses Modernizr to detect it):
Demo: http://jsfiddle.net/S3zQ9/
var placeholder_OnBlur = function () {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
};
var placeholder_OnFocus = function () {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
};
var placeholder_OnSubmit = function () {
$(this).find('[placeholder]').each(function () {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
});
};
var placeholder_OnLoad = function () {
if (!!$(this).attr('placeholder')) {
$(this).on('focus', placeholder_OnFocus);
$(this).on('blur', placeholder_OnBlur);
$(this).parents('form').on('submit', placeholder_OnSubmit);
$(this).blur();
}
};
if (!Modernizr.input.placeholder) {
$('[placeholder]').each(placeholder_OnLoad);
}
Don't have IE8 to test it, but it should work.