Setting 'autofocus' attribute with JavaScript not working - javascript

I am writing a small plugin, and the plugin will encapsulate an autofocus setting, but when I add the attribute dynamically with JavaScript, it doesn't autofocus the page, which is weird. Is there anyway around this?
HTML:
<input type="text">
JS:
document.querySelector('input').setAttribute('autofocus', 'autofocus');
Without doing:
document.querySelector('input').setAttribute('autofocus', 'autofocus').focus();
jSFiddle: http://jsfiddle.net/wPUNN/

Try something like this
document.querySelector('input').focus()
Edit
If you want to HTML 5 standard you should make the HTML look something like this
<input type="text" autofocus>
http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#autofocusing-a-form-control:-the-autofocus-attribute

The best approach seems to be this:
document.querySelector('input').autofocus = true;
This post might help explain why to use a reflected property: https://stackoverflow.com/a/18770417/3920924
However it seems you need to apply it near the document load. Otherwise it doesn't seem to fire. I think that's because here (http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#autofocusing-a-form-control:-the-autofocus-attribute:the-dialog-element) it's defined to work as soon as the page is loaded. I haven't seen anything else that says it can be called later in time. Every time I've tried to fire it later with like a setTimeout of 3 seconds it never focuses the field.

Try to add the javascript code soon after the input element, so it will execute before the page load complete. In your case autofocus attribute is set to the element but focusing the element which has autofocus by browser is already done. so you setting the value after browser set the focus. when browser trying to set it no attribute is there. try like following code
<input type="text">
<script>
document.querySelector('input').setAttribute('autofocus', 'autofocus');
</script>
http://jsbin.com/yatugaxe/1/
If you need to do it on button click or something, you need to do it in JavaScript. setting an attribute doesn't mean browser is going to execute it at anytime.

Related

How do I change the title of a web page using javascript?

I know this is a duplicate question, but I've tried a few approaches and I'm not able to get the solution I need.
I need to change the title of a web page, and I thought Javascript would be a good candidate. I've read many disapproving comments already, talking about how changing the title will negatively affect SEO-I'm not worried about that just now.
I'm able to change the title by reassigning a value in an inline script:
<input type="button" value="Click me." onclick="document.title = 'Some new title';" />
But using an inline script in this case is out of the question. I tried loading an embedded script tag above & below the body of the script, no go. This is what I settled on, and it didn't work initially (keep reading):
<script>
document.addEventListener("load", function changeTitle(){
document.title = "FUBAR";
}, true);
</script>
I've tried adding/removing the 'true' value at the end of the parameter list and that doesn't change anything. I avoided naming the function, then named it, and that didn't change anything. What DID work was changing "load" to "click". I need the title to change right after the document is finished loading...is there something else I can use, like "ready", or "onload"? Using "load" yielded no results, but I swear I've seen it used before.
Thanks!
Try using
window.addEventListener rather than document.addEventListener
See
https://developer.mozilla.org/en-US/docs/Web/Events/load
Note: More reliable is to add event listener on
"window.addEventListener".
No need to wait for the load event. Just set the title:
<html>
<head></head>
<body>
<script>document.title = "foobar"</script>
<!-- rest of document -->

Content with queryui checkbox button grows when is replaced with Backbone.js

I have the next code to replace content using Backbone.js
jsfiddle
I don't know why the checkbox button grows when the content is replaced.
Simply, I use the next code to checkbox
$('.checkWeek').button();
I think the reason is because you keep calling the $('.checkWeek').button(); on every click so JQuery does something funny and adds a span within a span which causes the size to grow.
A simple fix is to not call the $('.checkWeek').button(); if the button already exists (or shown)
// if button already exists then dont add it again.
if(!$('label[for=checkWeekM]').hasClass('ui-button'))
$('.checkWeek').button();
Look here: http://jsfiddle.net/Thxtr/3/
At the moment code stores the templates in div tags - every time you call button the template is modified. You can avoid that by using a script tag with type text/template so that it won't be executed as Javascript.
Rigth now:
<div data-template-name="central-home">
<div data-template-name="">
<input type="checkbox" class="checkWeek" id="checkWeekM" />
<label for="checkWeekM">L</label>
</div>
</div>
Change to:
<script data-template-name="central-home">
<div data-template-name="">
<input type="checkbox" class="checkWeek" id="checkWeekM" /><label for="checkWeekM">L</label>
</div>
</script>
With the Javascript unchanged the template will not be found. So you also have to update this line:
content.view = ...$.trim($("[data-template-name='"+ template_name +"'] div").html()...
With the requirement for the template to be inside a div removed:
content.view = ...$.trim($("[data-template-name='"+ template_name +"']").html() ...
Working fiddle
I'm guessing that $('.checkWeek').button() only needs to be called once per .checkweek element, or maybe just once in total.
If so then possible workarounds would be :
to execute $('.checkWeek').button() conditionally (though I'm not sure what the test might be).
to make the $('.checkWeek') selector more selective, ie select only the freshly added element.
if a destroy option exists, to call $('.checkWeek').button('destroy').button() (or similar - you will have to search through the plugin's API documentation).
Without a more complete understanding of the app (and the plugins), I can't tell which of these possibilities is most appropriate.

Removing data attributes from HTML using jQuery

Can't seem to get this one to work...
I have a page that hides certain links. When the DOM is loaded, I'm using jQuery to toggle some of those elements. This is driven by using a data attribute like so:
<div class="d_btn" data-usr='48'>
<div class="hidden_button">
Then, I have the code:
$.each($(".d_btn"), function() {
var btn = $(this).data('usr');
if ( btn == '48' ){
$(this).children('.hidden_button').toggle();
}
The above all works as planned. The problem is that I am trying to remove the data-usr from the class .d_btn once the if statement is evaluated. I've tried the following and nothing works (i.e., after the page is loaded, the source still shows the data-usr attribute:
$(this).removeAttr("data-usr");
$(this).removeData("usr");
I've been working on this for a couple of hours now and...nothing! Help is greatly appreciated!
UPDATE
I've tried the great suggestions of setting the data attribute to an empty string but I'm still not getting the desired result.
To explain a little further, The reason I'm trying to remove the attribute is so when an ajax response adds another item to the page, the previously added items would already have the button either shown or hidden. Upon AJAX response, I'm calling the same function once the DOM is loaded.
Currently, when something is added via AJAX, it toggles all the buttons (showing the ones that were hidden and vice versa.) Ugh...
I'm also fully willing to try alternatives to my approach. Thanks!
UPDATE
Well, the light bulb just flashed and I am able to do what I want to do by just using .show() instead of .toggle()
Anyway, I'd still like to find an answer to this question because the page will be potentially checking hundreds of items whenever something is added - this seems horribly inefficient (even for a computer, hahaha.)
Why don't you set the value to a random value or empty variable instead if removeAttr does not work..
$(this).attr("data-usr" , '');
$(this).prop("data-usr" , '');
Changing the DOM doesn't affect the source. It affects the DOM, which you can view with the Inspector/Developer Tools. Right click => View Source will give you the original source of the page, not the actual current source as modified by JavaScript.
Set it to a blank string:
$(this).attr("data-usr", "");
I second what Kolink said: check the DOM, not the source. (Chrome: Ctrl + Shift + i).
As others have stated. Checking the source will only show the original unedited source for the webpage. What you need to do is check the DOM using developer tools.
I've just checked everything in Chrome's inspector on jsfiddle here and the attribute is definitely being removed as well as the data.

How do I reset the value of a text input when the page reloads?

Firefox (and probably other browsers) want to keep whatever text the user entered in the text input, even after a reload. Just including the default text (that I want the input to revert to) in the html doesn't work:
<input tyep='text' value='default text' />
And neither does trying to use JS
window.onload = function() {document.getElementById("mytextinput").value = 'default text'}
You can use plain old HTML :)
Set autocomplete='off' in the attribute
<input type='text' value='default text' autocomplete='off' />
This works on most modern browsers.
Technically, you don't have to run a function onload to clear it--you could just put the javascript right in the page. For instance:
document.getElementById("mytextinput").value = ''
or with jQuery
$("mytextinput").val('');
Note that it's always a good idea to work with a dom listener to ensure that your javascript fires after the dom has been properly built. So, in the example of jQuery, this would be as easy as
$(document).ready(function() {
$("mytextinput").val('');
});
Try this:
<input type='text' id='mytextinput' value='default text' />
<script>
document.getElementById("mytextinput").value = 'default text';
</script>
This code should run as soon as the textbox has loaded. The onload event can seem inconsistent, I'm not entirely sure how it behaves in multiple browsers on different actions like refreshing.
You can call the script differently, put it in a function, put it somewhere else etc, but it's good to start with a working version.
If this doesn't work on other browsers there isn't much you can do because some browsers will try and be 'helpful' and always autofill for you.
I think you should do a server side coding on page reload. Page reload is generally a postback type idea . The page gets reloaded from server. If you are doing asp.net , in page_load method add your default text. :)

Javascript error: [elementname] has no properties

I'm doing some maintenance coding on a webapp and I am getting a javascript error of the form: "[elementname] has no properties"
Part of the code is being generated on the fly with an AJAX call that changes innerHTML for part of the page, after this is finished I need to copy a piece of data from a hidden input field to a visible input field.
So we have the destination field: <input id="dest" name="dest" value="0">
And the source field: <input id="source" name="source" value="1">
Now when the ajax runs it overwrites the innerHTML of the div that source is in, so the source field now reads: <input id="source" name="source" value="2">
Ok after the javascript line that copies the ajax data to innerHTML the next line is:
document.getElementById('dest').value = document.getElementById('source').value;
I get the following error: Error: document.getElementById("source") has no properties
(I also tried document.formname.source and document.formname.dest and same problem)
What am I missing?
Note1: The page is fully loaded and the element exists. The ajax call only happens after a user action and replaces the html section that the element is in.
Note2: As for not using innerHTML, this is how the codebase was given to me, and in order to remove it I would need to rewrite all the ajax calls, which is not in the scope of the current maintenance cycle.
Note3: the innerHTML is updated with the new data, a whole table with data and formatting is being copied, I am trying to add a boolean to the end of this big chunk, instead of creating a whole new ajax call for one boolean. It looks like that is what I will have to do... as my hack on the end then copy method is not working.
Extra pair of eyes FTW.
Yeah I had a couple guys take a look here at work and they found my simple typing mistake... I swear I had those right to begin with, but hey we live and learn...
Thanks for the help guys.
"[elementname] has no properties" is javascript error speak for "the element you tried to reference doesn't exist or is nil"
This means you've got one or more of a few possible problems:
Your page hasn't rendered yet and you're trying to reference it before it exists
You've got a spelling error
You've named your id the same as a reserved word (submit on a submit button for instance)
What you think you're referencing you're really not (a passed variable that isn't what you think you're passing)
Make sure your code runs AFTER the page fully loads. If your code runs before the element you are looking for is rendered, this type of error will occur.
What your describing is this functionality:
<div id="test2">
<input id="source" value="0" />
</div>
<input id="dest" value="1" />
<script type="text/javascript" charset="utf-8">
//<![CDATA[
function pageLoad()
{
var container = document.getElementById('test2');
container.innerHTML = "<input id='source' value='2' />";
var source = document.getElementById('source');
var dest = document.getElementById('dest');
dest.value = source.value;
}
//]]>
</script>
This works in common browsers (I checked in IE, Firefox and Safari); are you using some other browser or are you sure that it created the elements correct on innerHTML action?
It sounds like the DOM isn't being updated with the new elements to me.
For that matter, why are you rewriting the entire div just to change the source input? Wouldn't it be just as easy to change source's value directly?
This is a stretch, but just may be the trick - I have seen this before and this hack actually worked.
So, you said:
Ok after the javascript line that copies the ajax data to innerHTML the next line is:
document.getElementById('dest').value = document.getElementById('source').value;
Change that line to this:
setTimeout(function() {
document.getElementById("dest").value = document.getElementById("source").value;
}, 10);
You really shouldn't need this, but it is possible that the time between your setting the innerHTML and then trying to access the "source" element is so fast that the browser is unable to find it. I know, sounds completely whack, but I have seen browsers do this in certain instances for some reason that is beyond me.
Generally you shouldn't use innerHTML, but create elements using DOM-methods. I cannot say if this is your problem.

Categories

Resources