Determine current DOM element state in chrome - javascript

How do I determine the state of a textarea element (:focus, :hover, etc.) in Chrome?
For context, I'm trying to create a web application. After submitting the form on a previous page, the textarea of the new page automatically has the cursor, which I do not want to happen. I've tried to use the jQuery code below, which works in Firefox but not in Chrome:
element = $("#elementID");
if (element.is(":focus")) {
element.blur();
}
In Chrome, the code does not execute the element.blur() in the if statement (meaning the if statement fails). I've checked with a debugger and the element is successfully returned by the id in Chrome. So I think the problem is the state check statement.
I assume the problem is the element state and I want to investigate the element state at that time, preferably using Chrome developer tools. Unfortunately, I can't figure out how to check the current state. I can only figure out how to check if the state is equal to a specific state.
I've searched around but I am only finding answers like set :hover state which discuss how to set a specific state using Chrome dev tools and not how to determine the current state when it could be any state.
I realize that I could check for each possible state at that point in the JavaScript, but it seems like I am missing the correct way to check the state.
Here is a JSFiddle of my specific case. However, I'd be interested to also hear the answer to the general question about determining the current state of a textarea.
Thanks for the help!

It's most likely an order of operations issue - the logic is executed before the input's focus can be detected.
I've reproduced the issue here, and fixed it by putting the code into the window .load() event.
var $el = $('textarea');
// will not execute
if ($el.is(':focus')) {
$el.blur();
console.log('outside of window load');
}
// will execute
$(window).load(function() {
if ($el.is(':focus')) {
$el.blur();
console.log('inside window load');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea autofocus></textarea>

Related

CKEditor restore element / undo all changes

Is there a way to restore the original content / undo all changes of an element that had become an Inline-CKEditor?
There does not seem to exist a build-in function for that, see for example this ticket.
Some propose workarounds like a button with onclick javascript event, which reloads a page. Or saving the initial data inside of the editor and use javascript to replace the content with that on an event again. (Here is a thread concerning your request with the mentioned tricks.)
My solution:
After instantiating CKEditor I save the initial content with CKEDITOR.editor1.getData() to a custom variable CKEDITOR.editor1.firstSnapshot. Later when I want to restore it I write it back with CKEDITOR.editor1.setData(CKEDITOR.editor1.firstSnapshot);
At first I wanted to use getSnapshot() but however it always returned true, so that didn't work for me.
I want to share a different approach to problem. I'm using inline CKEditor, and have on blur event (when user unfocus ckeditor) which prompt option for saving content or rollback changes.
For case of rollback - i just put checkDirty() - function which check if instance has changes - in while loop, so undo executes in each true until ckeditor will be restored to initial state.
Code will look like this:
CKEDITOR.instances["editor"].on('blur', function (evt) {
if (confirm("Do you wish to roll back changes ?")) {
while (CKEDITOR.instances["editor"].checkDirty()) {
CKEDITOR.instances["editor"].execCommand('undo');
}
} else {
// do nothing!
}
})

Programmatically change first page jQuery Mobile shows

My goal is to show a different first page depending on whether the user is logged in or not. The login check happens using a synchronous Ajax call, the outcome of which decides whether to show a login dialog or the first user page.
The normal way to do this would be to set $.mobile.autoInitialize = false and then later on initialize programmatically, as described in the answer to this question. For some reason this won't work, instead another page gets loaded every single time.
I decided to give up on this way and try out a different parcour. I now use a placeholder, empty startup page that should be shown for as long as the login check takes. After the login check it should automatically change. This is done by calling a function that performs the ajax call needed for authentication on the pagechange event that introduces this startup page. The function takes care of changing to the outcome page as well.
The trick is that it doesn't quite do that.. Instead it shows the correct page for just a short time, then changes back to the placeholder. Calling preventDefault in pagechange didn't prevent this, as described in the tutorial on dynamic pages. Adding a timer fixed this, leading me to think that the placeholder wasn't quite finished when pageshow got fired (as per this page on page events), or some side-effect of the initial page load still lingered.
I'm really clueless as to how to fix this seemingly trivial, yet burdensome problem. What causes this extra change back to the initial page? Also, if my approach to intercepting the initial page load is wrong, what would be the correct approach instead?
I use jQuery Mobile 1.4.0 and jQuery 1.10.2 (1.8.3 before).
EDIT: Below is the code to my last try before I posted the question here. It does not work: preventDefault does not prevent the transition to the placeholder page.
$(document).on("pagebeforechange", function(e, data) {
if (typeof(data.options.fromPage) === "undefined" && data.toPage[0].id === "startup") {
e.preventDefault();
initLogin();
}
});
function initLogin() {
// ... Login logic
if (!loggedIn) // Pseudo
$('body').pagecontainer("change", "#login", {});
}
If you're using a Multi-page model, you can prevent showing any page on pagebeforechange event. This event fires twice for each page, once for the page which is about to be hidden and once for the page which is about to be shown; however, no changes is commenced in this stage.
It collects data from both pages and pass them to change page function. The collected data is represented as a second argument object, that can be retrieved once the event is triggered.
What you need from this object is two properties, .toPage and .options.fromPage. Based on these properties values, you decide whether to show first page or immediately move to another one.
var logged = false; /* for demo */
$(document).on("pagebeforechange", function (e, data) {
if (!logged && data.toPage[0].id == "homePage" && typeof data.options.fromPage == "undefined") {
/* immediately show login dialig */
$.mobile.pageContainer.pagecontainer("change", "#loginDialog", {
transition: "flip"
});
e.preventDefault(); /* this will stop showing first page */
}
});
data.toPage[0].id value is first page in DOM id.
data.options.fromPage should be undefined as it shouldn't be redirected from another page within the same webapp.
Demo
I'm undergoing the same problem as the one described by #RubenVereecken, that is, a coming back to the initial page once the cange to my second page has completed. In fact, he posed the question "What causes this extra change back to the initial page?" and it hasn't been replied yet.
Unfortunately, I don't know the reason since I haven't found how the page-event order works in JQM-1.4.2 yet, but fortunately, the workaround suggested by #Omar is working for me.
It's not exactly the same code but the general idea works at the time of preventing a coming back to the initial page. My code is as follows:
$(document).on("pagebeforechange", function(event, data) {
if ( typeof (data.toPage) == "string") {
if (data.toPage.indexOf("#") == -1 && typeof (data.options.fromPage[0].id) == string") {
event.preventDefault();
}
}});
The condition data.toPage.indexOf("#") == -1 is because I checked that all the undesired coming-backs to the initial page were happening when the property '.toPage' was set to something like [http://localhost/.../index.html].

Setting viewScope onLoad and onResize

I have used the '#media only screen' in my CSS to determine how and what information should be shown depending on the users screen size. I have a class called panelContainer which is set to display when the screen is greater than 767px, and a class called mobileContainer which displays when the screen is less than that.
I have a couple of custom controls, one that contains the standard form layout and another that contains the mobile device form layout. Originally I placed a div around each with the appropriate styleClass. The problem with it this way was that although only one form is visible, they were both loaded so this caused save issues.
<xp:div id="panelContainer" styleClass="panelContainer">
<xc:content_sCompany></xc:content_sCompany>
</xp:div>
<xp:div id="mobileContainer" styleClass="mobileContainer">
<xc:content_iCompany></xc:content_iCompany>
</xp:div>
I have since added a div to my Xpage with the styleClass of panelContainer, I then added onLoad and onResize events which return the style.display of the div, these should then write the result to a viewScope. But I found it would only write onLoad and although the function was being called onResize it wouldn't change the viewScope variable.
<xp:scriptBlock id="scriptBlock1" type="text/javascript">
<xp:this.value>
<![CDATA[var init = function() {
obj=document.getElementById('formType');
if(getStyleDisplay(obj)=="none"){
formType='#{javascript:viewScope.put("formFormat","mobile");}';
}else{
formType='#{javascript:viewScope.put("formFormat","standard")}';
}
}
dojo.addOnLoad(init);
dojo.connect(window,"onresize",init);
function getStyleDisplay(obj) {
if(obj.currentStyle) { // IE – Opera
return obj.currentStyle.display;
} else { // firefox
return getComputedStyle(obj,'').getPropertyValue('display');
}
}]]>
</xp:this.value>
</xp:scriptBlock>
<div id="formType" class="panelContainer"></div>
.....this viewScope variable is then used in the following way:
<xc:content_Company xp:key="ContentControl">
<xp:this.facets>
<xc:content_sCompany id="content_sCompany"
xp:key="standard">
</xc:content_sCompany>
<xc:content_iCompany id="content_iCompany"
xp:key="mobile">
</xc:content_iCompany>
</xp:this.facets>
</xc:content_Company>
.....extract from content_Company......
<xp:callback facetName="#{viewScope.formFormat}" id="cbkCompanyFormContent">
</xp:callback>
I feel this is the better way to achieve the result I need, as when I have tried it manually it does only load one of the forms and they work as expected.
I cannot see why the viewScope is not being set properly, it is always being set to 'standard', even if I shrink my page before loading the page. I did try writing the value to a Hidden Input, which worked but whenever I tried to access the value using getComponent("hiddenInput1").getValue() it would return null, even though I could see that value had been set when viewing in firebug.
Ok can you check (or tell me if you already have) through some console.log("") 's that the onResize is being called and the correct display is being pulled down etc.
next it may be firing the onResize but are you then partail refreshing the area which is using the viewScope?
Code example of this: (replace controlID with yours)
XSP.partialRefreshGet("controlID", {
onError: function() { console.log('Error'); }
});
I'm a little confused about what the purpose of using onResize is for ? if is to decide what to show whether on mobile or normal screen there are much more efficient ways of doing this.
Using the new redirect control in the latest release of the ExtLib on openNTF. It does exactly what the name suggests and redirects based on certain expressions. leaving you to drop it on a page and say if mobile (or whatever) redirect to this page.
Having a dummy default load page that checks the useragent string to see which page to load (having a separate mobile / fullscreen pages). This is what the teamroom template application that comes with the ExtLib does with its main.xsp and then this is set as the default launch option.
Or if you are trying to do something with whether the phone / tablet is on landscape or portrait you should be using the onOrientationChange event not onResize. check out this example (not the code in the question is what I'm pointing you too, he has a problem getting that to work in a webview):
how to handle javascript onorientationchange event inside uiwebview

How do I discover which function is called when I press a button?

I'm stuck modifying someone else's source code, and unfortunately it's very strongly NOT documented.
I'm trying to figure out which function is called when I press a button as part of an effort to trace the current bug to it's source, and I"m having no luck. From what I can tell, the function is dynamically added to the button after it's generated. As a result, there's no onlick="" for me to examine, and I can't find anything else in my debug panel that helps.
While I prefer Chrome, I'm more than willing to boot up in a different browser if I have to.
In Chrome, type the following in your URL bar after the page has been fully loaded (don't forget to change the button class):
var b = document.getElementsByClassName("ButtonClass"); alert(b[0].onclick);
or you can try (make the appropriate changes for the correct button id):
var b = document.getElementById("ButtonID"); alert(b.onclick);
This should alert the function name/code snippet in a message box.
After having the function name or the code snippet you just gotta perform a seach through the .js files for the snippet/function name.
Hope it helps!
Open page with your browser's JavaScript debugger open
Click "Break all" or equivalent
Click button you wish to investigate (may require some finesse if mouseovering page elements causes events to be fired. If timeouts or intervals occur in the page, they may get in the way, too.)
Inspect the buttons markup and look at its class / id. Use that class or id and search the JavaScript, it's quite likely that the previous developer has done something like
document.getElementById('someId').onclick = someFunction...;
or
document.getElementById('someId').addEventListener("click", doSomething, false);
You can add a trace variable to each function. Use console.log() to view the trace results.
Like so:
function blah(trace) {
console.log('blah called from: '+trace);
}
(to view the results, you have to open the developer console)

How to prevent page's scroll position reset after DOM manipulation?

I've got two JS functions, one that is adding options to a select box
function addOption(selectId, text, value) {
var selectbox = document.getElementById(selectId);
var optNew = document.createElement('option');
optNew.text = text;
optNew.value = value;
try {
selectbox.add(optNew, null); //page position resets after this
}
catch(ex) {
selectbox.add(optNew);
}
}
and another that is doing a document.getElementById(formId).appendChild(newHiddenInput) in a similarly simple function.
They both work, elements are added as expected. However, upon calling either of them, the page resets its scroll position to the top of the page in both IE6 and FF. There is no postback, this is purely clientside manipulation. I've set breakpoints in Firebug, and it occurs immediately after the element.appendChild or select.add gets executed. I know I can use JS to manually set a scroll position, but I didn't think it was necessary when the page isn't being re-rendered.
I'm no expert with JS or the DOM, so I may very well be missing something, but I've looked here and ran through their examples with the Try it Here options and I can't replicate the problem, indicating the codebase I'm working with is the culprit.
Any ideas why the scroll position is being reset? jQuery is available to me as well, if it provides a better alternative.
If the functions are being called from a link you might have an internal anchor in your link:
http://www.website.com/page.html#
This is causing said behavior. The default behavior is that if an anchor does not exist, the page scroll position jumps to the top (scrollTop = 0).
If this happens on every function call regardless of the source, then this can be crossed off the list.
What is activating the event?
If it's an anchor then on the click event you need to "return false;" after the call to your jQuery/Ajax/jScript code.
If it's a button you may need to do the same.
I had this issue yesterday and this was the resolution.
So My link

Categories