I am trying to debug this (incomplete) script, but it is behaving inconsistently. The main problem is when I click off of an item, sometimes the $(editObj).removeAttr('style'); runs and sometimes not. Through the Chrome inspector I can see that the editObj variable in each case is properly defined, but it isn't always getting its inline style attribute removed. Sometimes, and sometimes not. Cannot determine the reason.
I'm a bit out of my element with this code. Maybe something about it is obvious; Regardless I'd appreciate some ideas on why this sort of unpredictable might be occuring!
var editObj = null;
var inputType = 'text';
var input = '#textEdit';
var formId = '#form_undefined'
$(function() {
$("#textEdit").click(function(event) {
event.stopPropagation();
});
$('body').click(function(event) {
if (editObj){
//textedit contents to editobj and
if (inputType == 'text'){
$(editObj).text($("#textEdit").val());
}
$("#textEdit").removeAttr('style').hide();
$(editObj).removeAttr('style');
var previewId = $(editObj).attr('id');
var formId = previewId.replace('bzm', 'form');
$("#" + formId).val($("#textEdit").val());
//ajax modify database
editObj = null;
}
});
$(".editable").not("video, img, textarea")
.click(function(event) {
event.stopPropagation();
loadEditor($(this));
});
});
function loadEditor(element){
$("#textEdit")
.copyCSS(element)
.offset($(element).offset())
.css("display", "block")
.val($(element).text())
.select();
$(element).css("color", "transparent");
editObj = element;
}
I've had trouble in the past with .removeAttr('style'); not actually removing all the inline styles.
Use
$(editObj).attr('style', '');
instead of
$(editObj).removeAttr('style');
I dint see any code that initializes e editobj variable.. May be Im missing Anthony.. Anyways what are the chances of the edit obj being null.. Just put a log statement in the click function to always log ur editobj and see if it is null smtimes
Related
I have a couple of forms on a site. On the first form I used the code below to add a border color if the input field is not blank and remove it if it is blank. This works just fine no issues. But I've found that when I try to use the same method on other forms, to do something else using the same logic, it does not work.
I have read through many forums and what I'm seeing is that the code is only read on page load. But I have forms that run the function after the page is far past loading. Can someone give some light to this? I'm really trying to understand the way this works fully.
Code that works on form:
var checkErrorIn;
jQuery(document).ready(function ($) {
checkErrorIn = setInterval(CheckErrorInput, 0);
});
function CheckErrorInput() {
if (jQuery('body').is('.page-id-6334')) {
// First Name, Last Name validation colors
var pasdFName = jQuery('#first_name').val();
var pasdLName = jQuery('#last_name').val();
if (pasdFName != '') {
jQuery('#first_name').addClass('formConfirm_cc');
} else {
jQuery('#first_name').removeClass('formConfirm_cc');
}
if (pasdLName != '') {
jQuery('#last_name').addClass('formConfirm_cc');
} else {
jQuery('#last_name').removeClass('formConfirm_cc');
}
if (pasdFName != '' & pasdLName == '') {
jQuery('#last_name').addClass('formError_cc');
} else {
jQuery('#last_name').removeClass('formError_cc');
}
if (pasdFName == '' & pasdLName != '') {
jQuery('#first_name').addClass('formError_cc');
} else {
jQuery('#first_name').removeClass('formError_cc');
}
}
}
Code that is not working:
if (jQuery('body').is('.woocommerce-page')) {
var checkActiveName = jQuery('.woo_login_form > form > #username').val();
jQuery('.woo_login_form').on('input', function(){
jQuery('.woo_login_form').addClass('cdc_keep_active');
});
if (checkActiveName =='') {
jQuery('.woo_login_form').removeClass('cdc_keep_active');
}
}
What I am trying to do is fix an issue with a form becoming hidden if not hovered over even when the input has characters. Based on my research I figured I'd do the .on to get the class added when the input got characters. That works but the removal of the characters isn't removing the class. The logic looks right to me. What am I missing?
Thank you in advance for your help and insight.
Update:
Ok so I ended up doing this:
jQuery('.woo_login_form').on('click', function () {
jQuery('.woo_login_form').addClass('cdc_keep_active');
});
jQuery('.custom-login-box > a').on('click', function () {
jQuery('.woo_login_form').toggle();
});
For some reason my class would not add with any of the methods suggested individually so I combined the logic. The first part adds the class that makes the form visible but then the form won't close if clicked out of regardless of the 'removeClass'. So I added a toggle (thank you commenters) method to the "hovered link" to allow users to close the box if not needed.
Would still like to understand why the first method worked in one instance but not the other. Any and all insight appreciated. Thank you.
In your current code example you immediately check for the value of the username field.
var checkActiveName = jQuery('.woo_login_form > form > #username').val();
The thing with this is that checkActiveName will never change, unless it is reassigned elsewhere in the code.
What you need to do is to check the current value after every input of the user. That means moving that line of reading the value of the input inside the input event listener.
if (jQuery('body').is('.woocommerce-page')) {
var $wooLoginForm = jQuery('.woo_login_form');
var $userName = jQuery('#username'); // This ID should only exist once, so no need for complex selectors.
$wooLoginForm.on('input', function() {
var checkActiveName = $userName.val();
if (checkActiveName =='') {
$wooLoginForm.removeClass('cdc_keep_active');
} else {
$wooLoginForm.addClass('cdc_keep_active');
}
});
}
On a sidenote: using setInterval to validate your form is a bad practice. This would basically run infinitely. It doesn't have to. You only have to check if a form is valid after the user enters a value.
Apply the same technique with the event listener like in your second code snippet.
var $document = jQuery(document);
$document.ready(function ($) {
/**
* It might even be better to listen for the input event on the form
* that has to be validated, but I didn't see it in your code.
* Right now it listens for input on the entire page.
*/
$document.on('input', CheckErrorInput);
});
I've got the following bit of code (using JQuery) that I've written for a project. The idea is to have a function that you can attach to an element within an "item" div and it will return the id of that div. In this case, the div id would be item-[some item primary key value]. This function works probably 9/10 times, but every once in a while it will get to the else else case and return false. I've verified through the console that the input for selector is the exact same JQuery $() item in both the success and fail cases.
I'm relatively new to JavaScript, so there may be something obvious I'm missing, but this is some really unusual behavior.
var recursionCounter = 0;
function getElementID(selector, recursionDepth, searchString){
console.log(selector);
var elementID = selector.attr("id");
if(elementID === undefined){
elementID = "";
}
if(elementID.indexOf(searchString) !== -1){
elementID = elementID.split("-")[1];
return elementID;
} else {
if(recursionCounter < recursionDepth){
recursionCounter++;
return getElementID(selector.parent(), recursionDepth, searchString);
} else {
recursionCounter = 0;
alert("The element clicked does not have an associated key.");
return false;
}
}
}
Here is an example of code that calls this function, for some context.
$(document).on("click", ".edit-pencil-item", function(event) {
//Use helper function to get the id of the surrounding div then pass it to the function
var itemID = getElementID($(this), 10, "item-");
jsEditItem(itemID);
return false;
});
Thanks in advance for any help!
If you want to get the encapsulating element of your clicked element, and you know it should have an id starting with "item-" you should be able to do something along the lines of
$(this).closest('[id^="item-"]').attr('id')
Which says find this elements closest parent that has an id starting with "item-" and tell me its id.
As the title says, I have tried THREEx and Stemkovskis standalone KeyboardState.js , and neither of them seems to update properly.
This is my code:
m_vKeyboard = new THREEx.KeyboardState();
// m_vKeyboard.update(); // if using stemkovskis
if (m_vKeyboard.pressed("F")) {
alert("And now it is always true!");
}
you click the F key once, release it; alert window pops up, click OK, it pops up again for all eternity. How come?
Many browsers repeat keydown. Read more here and here (ctrl+f : auto-repeat).
Here's a proposed solution for your specific problem :
A. when keydown store its state as true in some array and make it false on keyup.
wasPressed['F'] = true; //on keydown
wasPressed['F'] = false; //on keyup
B. when checking for next keydown check its state as well.
if (m_vKeyboard.pressed("F") && !wasPressed['F'])
Find full implementation : Here
UPDATE
var wasPressed = {};
if( keyboard.pressed('F') && !wasPressed['f'] ){
alert("F was pressed");
prompt("Enter data : ");
wasPressed['f'] = true;
}
UPDATE 2
keyboard.domElement.addEventListener('keydown', function(event){
wasPressed = {};
})
I'm wondering if it has something to do with alert() being a blocking call. Using the code below gives me your same issue. If I comment out the alert() and un-comment the console.log() it seems to work fine. However, I'm not sure if that helps your issue.
var m_vKeyboard = new THREEx.KeyboardState();
setInterval(function () {
var key = "F";
var pressed = m_vKeyboard.pressed(key);
alert("And now it is always true!");
//console.log("key", key, "pressed", pressed);
}, 100);
Just add this to the beginning of onKeyDown in KeyboardState.js:
if (event.repeat) return;
That's not that great of a title for the question, so if anyone else has a better way to word it after reading it, that'd be appreciated.
Disclosure out of the way, this is homework. The assignment for this week is to refactor our already existing plain JS code to use JQM and I'm having an issue with a conversion I can't quite figure out, here's the code:
function populateItemLinks(key, listItem)
{
var ecLink = $('<a class="padRightRed"></a>');
ecLink.attr("href", "#");
ecLink.attr("key", key);
ecLink.html("Edit Character");
ecLink.on("click", editCharacter);
ecLink.appendTo(listItem);
console.log(ecLink.attr("key"));
ecLink = $('<a class="padLeftRed"></a>');
ecLink.attr("href", "#");
ecLink.attr("key", key);
ecLink.html("Delete Character");
ecLink.on("click", deleteCharacter);
ecLink.appendTo(listItem);
console.log(ecLink.attr("key"));
};
function deleteCharacter()
{
var toDelete = confirm("Do you wish to delete this character?");
if (toDelete)
{
console.log(this.key);
alert("Character was deleted.");
localStorage.removeItem(this.key);
$.mobile.changePage("#home");
}
else
{
alert("Character was not deleted.");
}
}
The issue is the using of the .key attribute as an itentified for the links in the populateItemLinks functions. When it was strait javascript, I could just do linkname.key = key; and then get the key back in the deleteCharacter function with "this.key". Well, now it's always returning undefined and I can't think of any way that wouldn't be convoluted to get the same functionality as the non-JQM version, so any help would be appreciated.
The reason your code is returning undefined is that you're trying to read a property of the DOM element, but you've set an attribute of the DOM element.
The top answers for this question explain the different between the two: .prop() vs .attr()
If you were to set the property of your newly created DOM element like this:
ecLink.prop('key', 12355);
And continued to directly access the DOM element (not via jQuery):
this.key; // 123455
All would of been well. Here is a JSFiddle example showing this in further detail.
Anyway, I've adjusted your code to work with the attribute you're setting:
function deleteCharacter()
{
var toDelete = confirm("Do you wish to delete this character?");
if (toDelete)
{
var key = $(this).attr('key');
alert("Character was deleted.");
localStorage.removeItem(key);
$.mobile.changePage("#home");
}
else
{
alert("Character was not deleted.");
}
}
Having said all this, Data attributes are better suited for storing arbitrary data against a DOM element:
ecLink.data('key', myKey); // set
ecLink.data('key'); // get
What I would do is pass the clicked ecLink as an argument to deleteCharacter() like this:
ecLink.on("click",function() { deleteCharacter($(this)); });
Then you can modify deleteCharacter():
function deleteCharacter(el)
{
var toDelete = confirm("Do you wish to delete this character?");
if (toDelete)
{
var key = el.attr('key'); //get the key attribute
console.log(key);
alert("Character was deleted.");
localStorage.removeItem(key);
$.mobile.changePage("#home");
}
else
{
alert("Character was not deleted.");
}
}
I am using jquery to keep the focus on a text box when you click on a specific div. It works well in Internet Explorer but not in Firefox. Any suggestions?
var clickedDiv = false;
$('input').blur(function() { if (clickedDiv) { $('input').focus(); } });
$('div').mousedown(function() { clickedDiv = true; })
.mouseup(function() { clickedDiv = false });
Point to note: the focus() method on a jquery object does not actually focus it: it just cases the focus handler to be invoked! to actually focus the item, you should do this:
var clickedDiv = false;
$('input').blur( function() {
if(clickeddiv) {
$('input').each(function(){this[0].focus()});
}
}
$('div').mousedown(function() { clickedDiv = true; })
.mouseup(function() { clickedDiv = false });
Note that I've used the focus() method on native DOM objects, not jquery objects.
This is a direct (brute force) change to your exact code. However, if I understand what you are trying to do correctly, you are trying to focus an input box when a particular div is clicked when that input is in focus.
Here's my take on how you would do it:
var inFocus = false;
$('#myinput').focus(function() { inFocus = true; })
.blur(function() { inFocus = false; });
$('#mydiv').mousedown(function() {
if( inFocus )
setTimeout( function(){ $('#myinput')[0].focus(); }, 100 );
}
Point to note: I've given a timeout to focussing the input in question, so that the input can actually go out of focus in the mean time. Otherwise we would be giving it focus just before it is about to lose it. As for the decision of 100 ms, its really a fluke here.
Cheers,
jrh
EDIT in response to #Jim's comment
The first method probably did not work because it was the wrong approach to start with.
As for the second question, we should use .focus() on the native DOM object and not on the jQuery wrapper around it because the native .focus() method causes the object to actually grab focus, while the jquery method just calls the event handler associated with the focus event.
So while the jquery method calls the focus event handler, the native method actually grants focus, hence causing the handler to be invoked. It is just unfortunate nomenclature that the name of this method overlaps.
I resolved it by simply replace on blur event by document.onclick and check clicked element if not input or div
var $con = null; //the input object
var $inp = null; // the div object
function bodyClick(eleId){
if (eleId == null || ($inp!= null && $con != null && eleId != $inp.attr('id') &&
eleId != $con.attr('id'))){
$con.hide();
}
}
function hideCon() {
if(clickedDiv){
$con.hide();
}
}
function getEl(){
var ev = arguments[0] || window.event,
origEl = ev.target || ev.srcElement;
eleId = origEl.id;
bodyClick(eleId);
}
document.onclick = getEl;
hope u find it useful