Infield label not reappearing on empty field - javascript

I have the following code jquery plugin which was based on one from a while back (demo here: http://jsfiddle.net/3rNpb/) that allows a label to fade in and out based on the user inputting to a field.
The label fades out 50% when a user focuses and then back in if they blur. When they begin typing the label hides completely. And then if the field is empty and they blur again then the label fades back in.
The issue is that when the field is focused and the user deletes the value it does not show the label at 50% again until they blur the field (unfocus).
Can anyone help fix this?
Thanks

In your keydown.infieldlabel event handler, you have this call:
f.hideOnChange(e)
...and your hideOnChange function contains this code:
f.hideOnChange = function (e) {
if ((e.keyCode == 16) || (e.keyCode == 9)) return;
if (f.showing) {
f.$label.hide();
f.showing = false
};
f.$field.unbind('keydown.infieldlabel')
};
It looks to me that the unbind call at the end of your function will cause the keydown event handling to stop; perhaps you have no event handling attached for your backspace or delete key anymore because the event is unbound.

Try this, working fine
<label class="placeholder" for="test">Test Label</label>
<input type="text" id="test" />
(function ($) {
$.InFieldLabels = function (b, c, d) {
var f = this;
f.$label = $(b);
f.label = b;
f.$field = $(c);
f.field = c;
f.$label.data("InFieldLabels", f);
f.showing = true;
f.init = function () {
f.options = $.extend({}, $.InFieldLabels.defaultOptions, d);
if (f.$field.val() != "") {
f.$label.hide();
f.showing = false
};
f.$field.focus(function () {
f.fadeOnFocus()
}).blur(function () {
f.checkForEmpty(true)
}).bind('keydown.infieldlabel', function (e) {
f.hideOnChange(e)
}).change(function (e) {
f.checkForEmpty()
}).bind('onPropertyChange', function () {
f.checkForEmpty()
})
};
f.fadeOnFocus = function () {
if (f.showing) {
f.setOpacity(f.options.fadeOpacity)
}
};
f.setOpacity = function (a) {
f.$label.stop().animate({
opacity: a
}, f.options.fadeDuration);
f.showing = (a > 0.0)
};
f.checkForEmpty = function (a) {
if (f.$field.val() == "") {
f.prepForShow();
f.setOpacity(a ? 1.0 : f.options.fadeOpacity)
} else {
f.setOpacity(0.0)
}
};
f.prepForShow = function (e) {
if (!f.showing) {
f.$label.css({
opacity: 0.0
}).show();
f.$field.bind('keydown.infieldlabel', function (e) {
f.hideOnChange(e)
})
}
};
f.hideOnChange = function (e) {
if ((e.keyCode == 16) || (e.keyCode == 9)) return;
if (f.showing) {
f.$label.hide();
f.showing = false
};
f.$field.unbind('keydown.infieldlabel')
};
f.init()
};
$.InFieldLabels.defaultOptions = {
fadeOpacity: 0.5,
fadeDuration: 300
};
$.fn.inFieldLabels = function (c) {
return this.each(function () {
var a = $(this).attr('for');
if (!a) return;
var b = $("input#" + a + "[type='text']," + "input#" + a + "[type='password']," + "input#" + a + "[type='email']," + "input#" + a + "[type='tel']," + "textarea#" + a);
if (b.length == 0) return;
(new $.InFieldLabels(this, b[0], c))
})
}
})(jQuery);
$("label.placeholder").inFieldLabels();

What you want to do is listen for a keyup event and check to see if your input is empty upon each keyup. If it is, then you fadeIn your label.

Related

Click event works on third or fourth try on button

This is a continuation of This
I used setTimeout() to place cursor on the input fields on pressing the tab, without which the focus goes to a link outside the <div> for some reason I am not aware of.
setTimeout() fixed that issue, but now:
On clicking on submit button the form does nothing but place cursor on the input fields for three or four times then proceeds with submitting.
Here is the submit button functions
$(“#submitbtn”).click(function(e) {
console.log(“click”);
e.preventDefault();
var s = setTimeout(function() {
removeTimeouts();
startValidation();
});
e.stopPropagation();
e.cancelBubble = true;
});
Here is hover function for Submit button
$(“#submitbtn”).mouseover(function(e) {
console.log(“Hover”);
removeTimeouts();
$(“#submitbtn”).focus();
e.preventDefault();
e.stopPropagation();
e.cancelBubble = true;
});
The function removeTimeouts() has all clearTimeout() for all setTimeout() through out the JavaScript file.
But somehow the click function is never works until third or fourth try.
The hover function works on first mouse move though, it prints “Hover” on console, every time the mouse it moves over submit button.
Even after clearing all setTimeout() somehow the focus is moved to input fields instead of proceeding with the console.log() onclick.
Can someone help me understand the issue and help fix the form gets submitted on first click?
Update:
1) This is typed from mobile app, even after re-editing the quote appearing as “” It’s correct in my code just not here.
2) Focus and timeout event is to validate the input fields while moving out of the input field, like if the field is empty, the cursor won’t move to next input field. But just focus is not working, and tab just takes the cursor out of the input fields to a link below it, so time-out helps keeping the cursor the input field.
3) Snippet - This does not replicate the issue as this is by far I can post the code sorry :(
(function ($) {
// Behind the scenes method deals with browser
// idiosyncrasies and such
$.caretTo = function (el, index) {
if (el.createTextRange) {
var range = el.createTextRange();
range.move("character", index);
range.select();
} else if (el.selectionStart != null) {
el.focus();
el.setSelectionRange(index, index);
}
};
// Another behind the scenes that collects the
// current caret position for an element
// TODO: Get working with Opera
$.caretPos = function (el) {
if ("selection" in document) {
var range = el.createTextRange();
try {
range.setEndPoint("EndToStart", document.selection.createRange());
} catch (e) {
// Catch IE failure here, return 0 like
// other browsers
return 0;
}
return range.text.length;
} else if (el.selectionStart != null) {
return el.selectionStart;
}
};
// The following methods are queued under fx for more
// flexibility when combining with $.fn.delay() and
// jQuery effects.
// Set caret to a particular index
$.fn.caret = function (index, offset) {
if (typeof(index) === "undefined") {
return $.caretPos(this.get(0));
}
return this.queue(function (next) {
if (isNaN(index)) {
var i = $(this).val().indexOf(index);
if (offset === true) {
i += index.length;
} else if (typeof(offset) !== "undefined") {
i += offset;
}
$.caretTo(this, i);
} else {
$.caretTo(this, index);
}
next();
});
};
// Set caret to beginning of an element
$.fn.caretToStart = function () {
return this.caret(0);
};
// Set caret to the end of an element
$.fn.caretToEnd = function () {
return this.queue(function (next) {
$.caretTo(this, $(this).val().length);
next();
});
};
}(jQuery));
var allTimeouts = [];
function placeCursor(id) {
id.focus(function(e) {
e.stopPropagation();
//e.cancelBubble();
id.caretToEnd();
});
id.focus();
}
function removeTimeouts(){
for(var i = 0; i < allTimeouts.length; i++) {
clearTimeout(allTimeouts[i]);
}
}
function focusInNumber (id) {
var thisID = id;
var nextID = id + 1;
var preID = id - 1;
//$("#number" + thisID).prop("disabled", false);
var s = setTimeout(function() {
placeCursor($("#number" + thisID));
});
allTimeouts.push(s);
if(preID != 0) {
if($("#number" + preID).val().length <= 0) {
var s = setTimeout(function() {
placeCursor($("#number" + preID));
});
allTimeouts.push(s);
}
}
}
function focusOutNumber (id) {
var thisID = id;
var nextID = id + 1;
var preID = id - 1;
var value = $("#number" + thisID).val();
var regex = new RegExp(/^\d*$/);
var regex1 = new RegExp(/^.*[\+\-\.].*/);
var l = $("#number" + thisID).val().length;
if(!value.match(regex)) {
alert("Just enter numerical digits");
var s = setTimeout(function() {
placeCursor($("#number" + thisID));
},5000);
allTimeouts.push(s);
} else {
if (l<=0) {
alert("This field cannot be empty");
var s = setTimeout(function() {
placeCursor($("#number" + thisID));
},5000);
allTimeouts.push(s);
} else {
if(value.match(regex)) {
var s = setTimeout(function() {
placeCursor($("#number" + nextID));
}, 100);
allTimeouts.push(s);
}
}
}
}
$(document).ready(function(){
$("#number1").focusin(function(){
focusInNumber(1);
});
$("#number1").focusout(function(){
focusOutNumber(1);
});
$("#number2").focusin(function(){
focusInNumber(2);
});
$("#number2").focusout(function(){
focusOutNumber(2);
});
$("#number3").focusin(function(){
focusInNumber(3);
});
$("#number3").focusout(function(){
focusOutNumber(3);
});
$("#number4").focusin(function(){
focusInNumber(4);
});
$("#number4").focusout(function(){
focusOutNumber(4);
});
$("#submitbtn").click(function(e) {
console.log("click");
e.preventDefault();
var s = setTimeout(function() {
removeTimeouts();
alert("startValidation()");
});
e.stopPropagation();
e.cancelBubble = true;
});
$("#submitbtn").mouseover(function(e) {
console.log("Hover");
removeTimeouts();
$("#submitbtn").focus();
e.preventDefault();
e.stopPropagation();
e.cancelBubble = true;
});
});
.SubmitBtn {
width: 100%;
background-color: #cccccc;
}
.Submitbtn:hover {
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" class="reqField" id="number1" placeholder="Enter Number only"></input>
<input type="number" class="reqField" id="number2" placeholder="Enter Number only"></input>
<input type="number" class="reqField" id="number3" placeholder="Enter Number only"></input>
<input type="number" class="reqField" id="number4" placeholder="Enter Number only"></input>
<div id="submitbtn" class="SubmitBtn">Submit</div>
After breaking my head and console.log on all the statement to figure out the flow of code, I was able to find that on $("#submitbtn").click() there is some .focusout() is called.
As these .focusout() were necessary for on the go validation on the <input> fields, i tried to add $.(":focus").blur() and it worked along with adding a return false; on placeCursor() function.
The $.(":focus").blur() removes focus from any currently focused element. And this is a live saver for our logic of code.
So the code looks like
$("#submitbtn").mouseover(function(e) {
console.log("Hover");
$.(":focus").blur();
removeTimeouts();
$("#submitbtn").focus();
e.preventDefault();
e.stopPropagation();
e.cancelBubble = true;
});
....
function placeCursor(id) {
id.focus(function(e) {
e.stopPropagation();
//e.cancelBubble();
id.caretToEnd();
});
id.focus();
return false;
}
Hope this helps someone someday.
Thank you!

Disable browser back and forward

I want to disable browser back and forward,so that i got code like this
(function (global) {
if(typeof (global) === "undefined") {
throw new Error("window is undefined");
}
var _hash = "!";
var noBackPlease = function () {
global.location.href += "#";
// making sure we have the fruit available for juice (^__^)
global.setTimeout(function () {
global.location.href += "!";
}, 50);
};
global.onhashchange = function ($valuable) {
if (global.location.hash !== _hash) {
global.location.hash = _hash;
}
};
global.onload = function () {
noBackPlease();
// disables backspace on page except on input fields and textarea..
document.body.onkeydown = function (e) {
var elm = e.target.nodeName.toLowerCase();
if (e.which === 8 && (elm !== 'input' && elm !== 'textarea')) {
e.preventDefault();
}
// stopping event bubbling up the DOM tree..
e.stopPropagation();
};
}
})(window);
It is working fine, but in url redirection page name along with #! is coming .How to remove this

I want to add a loading png in LiveSearch

I am using a plugin for live search .. everything is working fine .. i just want to add a loading png that appear on start of ajax request and disappear on results ..
please help me to customize the code just to add class where form id="search-kb-form" .. and remove the class when results are completed.
<form id="search-kb-form" class="search-kb-form" method="get" action="<?php echo home_url('/'); ?>" autocomplete="off">
<div class="wrapper-kb-fields">
<input type="text" id="s" name="s" placeholder="Search what you’re looking for" title="* Please enter a search term!">
<input type="submit" class="submit-button-kb" value="">
</div>
<div id="search-error-container"></div>
</form>
This is the plugin code
jQuery.fn.liveSearch = function (conf) {
var config = jQuery.extend({
url: {'jquery-live-search-result': 'search-results.php?q='},
id: 'jquery-live-search',
duration: 400,
typeDelay: 200,
loadingClass: 'loading',
onSlideUp: function () {},
uptadePosition: false,
minLength: 0,
width: null
}, conf);
if (typeof(config.url) == "string") {
config.url = { 'jquery-live-search-result': config.url }
} else if (typeof(config.url) == "object") {
if (typeof(config.url.length) == "number") {
var urls = {}
for (var i = 0; i < config.url.length; i++) {
urls['jquery-live-search-result-' + i] = config.url[i];
}
config.url = urls;
}
}
var searchStatus = {};
var liveSearch = jQuery('#' + config.id);
var loadingRequestCounter = 0;
// Create live-search if it doesn't exist
if (!liveSearch.length) {
liveSearch = jQuery('<div id="' + config.id + '"></div>')
.appendTo(document.body)
.hide()
.slideUp(0);
for (key in config.url) {
liveSearch.append('<div id="' + key + '"></div>');
searchStatus[key] = false;
}
// Close live-search when clicking outside it
jQuery(document.body).click(function(event) {
var clicked = jQuery(event.target);
if (!(clicked.is('#' + config.id) || clicked.parents('#' + config.id).length || clicked.is('input'))) {
liveSearch.slideUp(config.duration, function () {
config.onSlideUp();
});
}
});
}
return this.each(function () {
var input = jQuery(this).attr('autocomplete', 'off');
var liveSearchPaddingBorderHoriz = parseInt(liveSearch.css('paddingLeft'), 10) + parseInt(liveSearch.css('paddingRight'), 10) + parseInt(liveSearch.css('borderLeftWidth'), 10) + parseInt(liveSearch.css('borderRightWidth'), 10);
// Re calculates live search's position
var repositionLiveSearch = function () {
var tmpOffset = input.offset();
var tmpWidth = input.outerWidth();
if (config.width != null) {
tmpWidth = config.width;
}
var inputDim = {
left: tmpOffset.left,
top: tmpOffset.top,
width: tmpWidth,
height: input.outerHeight()
};
inputDim.topPos = inputDim.top + inputDim.height;
inputDim.totalWidth = inputDim.width - liveSearchPaddingBorderHoriz;
liveSearch.css({
position: 'absolute',
left: inputDim.left + 'px',
top: inputDim.topPos + 'px',
width: inputDim.totalWidth + 'px'
});
};
var showOrHideLiveSearch = function () {
if (loadingRequestCounter == 0) {
showStatus = false;
for (key in config.url) {
if( searchStatus[key] == true ) {
showStatus = true;
break;
}
}
if (showStatus == true) {
for (key in config.url) {
if( searchStatus[key] == false ) {
liveSearch.find('#' + key).html('');
}
}
showLiveSearch();
} else {
hideLiveSearch();
}
}
};
// Shows live-search for this input
var showLiveSearch = function () {
// Always reposition the live-search every time it is shown
// in case user has resized browser-window or zoomed in or whatever
repositionLiveSearch();
// We need to bind a resize-event every time live search is shown
// so it resizes based on the correct input element
jQuery(window).unbind('resize', repositionLiveSearch);
jQuery(window).bind('resize', repositionLiveSearch);
liveSearch.slideDown(config.duration)
};
// Hides live-search for this input
var hideLiveSearch = function () {
liveSearch.slideUp(config.duration, function () {
config.onSlideUp();
for (key in config.url) {
liveSearch.find('#' + key).html('');
}
});
};
input
// On focus, if the live-search is empty, perform an new search
// If not, just slide it down. Only do this if there's something in the input
.focus(function () {
if (this.value.length > config.minLength ) {
showOrHideLiveSearch();
}
})
// Auto update live-search onkeyup
.keyup(function () {
// Don't update live-search if it's got the same value as last time
if (this.value != this.lastValue) {
input.addClass(config.loadingClass);
var q = this.value;
// Stop previous ajax-request
if (this.timer) {
clearTimeout(this.timer);
}
if( q.length > config.minLength ) {
// Start a new ajax-request in X ms
this.timer = setTimeout(function () {
for (url_key in config.url) {
loadingRequestCounter += 1;
jQuery.ajax({
key: url_key,
url: config.url[url_key] + q,
success: function(data){
if (data.length) {
searchStatus[this.key] = true;
liveSearch.find("#" + this.key).html(data);
} else {
searchStatus[this.key] = false;
}
loadingRequestCounter -= 1;
showOrHideLiveSearch();
}
});
}
}, config.typeDelay);
}
else {
for (url_key in config.url) {
searchStatus[url_key] = false;
}
hideLiveSearch();
}
this.lastValue = this.value;
}
});
});
};
add a background to the loading class
.loading {
background:url('http://path_to_your_picture');
}

jquery click send function wont work only update the same field

I am trying to make a click send function for my emoticon function but it is not working correctly.
I have created this demo from jsfiddle. In this demo you can se there are four textarea and smiley. When you click smiley then other alert (comments will be come here) changing to (Plese write your comment). What is the problem on there and what is the solution anyone can help me in this regard ?
JS
$('.sendcomment').bind('keydown', function (e) {
if (e.keyCode == 13) {
var ID = $(this).attr("data-msgid");
var comment = $(this).val();
if ($.trim(comment).length == 0) {
$("#commentload" + ID).text("Plese write your comment!");
} else {
$("#commentload" + ID).text(comment);
$("#commentid" + ID).val('').css("height", "35px").focus();
}
}
});
/**/
$(document).ready(function () {
$('body').on("click", '.emo', function () {
var ID = $(this).attr("data-msgid");
var comment = $(this).val();
if ($.trim(comment).length == 0) {
$("#commentload" + ID).text("nothing!");
} else {
$("#commentload" + ID).text(comment);
$("#commentid" + ID).val('').css("height", "35px").focus();
}
});
});
$('body').on('click', '.sm-sticker', function (event) {
event.preventDefault();
var theComment = $(this).parents('.container').find('.sendcomment');
var id = $(this).attr('id');
var sticker = $(this).attr('sticker');
var msg = jQuery.trim(theComment.val());
if (msg == '') {
var sp = '';
} else {
var sp = ' ';
}
theComment.val(jQuery.trim(msg + sp + sticker + sp));
var e = $.Event("keydown");
e.keyCode = 13; // # Some key code value
$('.sendcomment').trigger(e);
});
HTML
At 43 line $('.sendcomment').trigger(e); you trigger keydown event to all textareas. Change it to theComment.trigger(e)

Detect if clicking outside of element (Must support clicking in overlay elements)

Current best solution i have found:
ko.bindingHandlers.clickedIn = (function () {
function getBounds(element) {
var pos = element.offset();
return {
x: pos.left,
x2: pos.left + element.outerWidth(),
y: pos.top,
y2: pos.top + element.outerHeight()
};
}
function hitTest(o, l) {
function getOffset(o) {
for (var r = { l: o.offsetLeft, t: o.offsetTop, r: o.offsetWidth, b: o.offsetHeight };
o = o.offsetParent; r.l += o.offsetLeft, r.t += o.offsetTop);
return r.r += r.l, r.b += r.t, r;
}
for (var b, s, r = [], a = getOffset(o), j = isNaN(l.length), i = (j ? l = [l] : l).length; i;
b = getOffset(l[--i]), (a.l == b.l || (a.l > b.l ? a.l <= b.r : b.l <= a.r))
&& (a.t == b.t || (a.t > b.t ? a.t <= b.b : b.t <= a.b)) && (r[r.length] = l[i]));
return j ? !!r.length : r;
}
return {
init: function (element, valueAccessor) {
var target = valueAccessor();
$(document).click(function (e) {
if (element._clickedInElementShowing === false && target()) {
var $element = $(element);
var bounds = getBounds($element);
var possibleOverlays = $("[style*=z-index],[style*=absolute]").not(":hidden");
$.each(possibleOverlays, function () {
if (hitTest(element, this)) {
var b = getBounds($(this));
bounds.x = Math.min(bounds.x, b.x);
bounds.x2 = Math.max(bounds.x2, b.x2);
bounds.y = Math.min(bounds.y, b.y);
bounds.y2 = Math.max(bounds.y2, b.y2);
}
});
if (e.clientX < bounds.x || e.clientX > bounds.x2 ||
e.clientY < bounds.y || e.clientY > bounds.y2) {
target(false);
}
}
element._clickedInElementShowing = false;
});
$(element).click(function (e) {
e.stopPropagation();
});
},
update: function (element, valueAccessor) {
var showing = ko.utils.unwrapObservable(valueAccessor());
if (showing) {
element._clickedInElementShowing = true;
}
}
};
})();
It works by first query for all elements with either z-index or absolute position that are visible. It then hit tests those elemnts against the elemnet I want to hide if click outside. If its a hit I calculate a new bound retacle which takes into acount the overlay bounds.
Its not rock solid, but works. Please feel free to comment if you see problems with above approuch
Old question
I'm using Knockout but this applies to DOM/Javascript in general
Im trying to find a reliable way if detecting of you click outside of a element. My code looks like this
ko.bindingHandlers.clickedIn = {
init: function (element, valueAccessor) {
var target = valueAccessor();
var clickedIn = false;
ko.utils.registerEventHandler(document, "click", function (e) {
if (!clickedIn && element._clickedInElementShowing === false) {
target(e.target == element);
}
clickedIn = false;
element._clickedInElementShowing = false;
});
ko.utils.registerEventHandler(element, "click", function (e) {
clickedIn = true;
});
},
update: function (element, valueAccessor) {
var showing = ko.utils.unwrapObservable(valueAccessor());
if (showing) {
element._clickedInElementShowing = true;
}
}
};
It works by both listening to click on target element and document. If you click on document but not target element you click outside of it. This works, but, not for overlay items like datepickers etc. This is because these are not inside the target element but in the body. Can I fix this? Are there better way of determine if clicking outside of element?
edit: This kind of works, but only if the overlay is smaller than the element i want to monitor
ko.bindingHandlers.clickedIn = {
init: function (element, valueAccessor) {
var target = valueAccessor();
$(document).click(function (e) {
if (element._clickedInElementShowing === false) {
var $element = $(element);
var pos = $element.offset();
if (e.clientX < pos.left || e.clientX > (pos.left + $element.width()) ||
e.clientY < pos.top || e.clientY > (pos.top + $element.height())) {
target(false);
}
}
element._clickedInElementShowing = false;
});
$(element).click(function (e) {
e.stopPropagation();
});
},
update: function (element, valueAccessor) {
var showing = ko.utils.unwrapObservable(valueAccessor());
if (showing) {
element._clickedInElementShowing = true;
}
}
};
I would like a more rock solid approuch
This is how I usually solve it:
http://jsfiddle.net/jonigiuro/KLxnV/
$('.container').on('click', function(e) {
alert('hide the child');
});
$('.child').on('click', function(e) {
alert('do nothing');
e.stopPropagation(); //THIS IS THE IMPORTANT PART
});
I don't know how your overlay items are generated, but you could always check if the click target is a child of the element you want to constrain your clicks to.

Categories

Resources