Setting focus on input with script only - javascript

I am trying to set focus on a text input without explicit mouse events, just javascript based events.
After running my script I would expect the input to be highlighted and the cursor bar to be present.
Clicking on the button which runs the same code will produce the desired result.
The question is how can I do this with pure events?
UPDATE: I am recreating a situation where I am not in control of the HTML being published. Apologies for leaving that part out.
var input = document.querySelector("input");
var btn = document.querySelector("#btn");
btn.addEventListener("click", function(event){
//when triggered by a mouse click on the button, produces desired result
console.log("click");
input.focus();
});
setTimeout(function(e){
var event = new Event("click");
//does not produce desired result
btn.dispatchEvent(event);
//does not produce desired result
btn.click();
}, 1000);
<input type="text">
<button id="btn">button</button>
as per this fiddle

Your code works fine, only not in the jsFiddle or in a Stack Overflow snippet iframe.
The reason is when you click "Run" your actually giving focus to another page (another window element). So after the timeout simulates the click on the button your element is focused alright, but your page is not, so you can't see it.
You can try setting the delay to 5 seconds, then click anywhere on the preview window before the timeout simulates the click, and you will see that your input will have focus exactly like when clicking on the button. You can also access the current focused element with document.activeElement
var input = document.querySelector("input");
var btn = document.querySelector("#btn");
console.log('active element:', document.activeElement);
btn.addEventListener("click", function(event) {
//when triggered by a mouse click on the button, produces desired result
console.log("click");
input.focus();
});
setTimeout(function(e) {
var event = new Event("click");
//does not produce desired result
btn.dispatchEvent(event);
//does not produce desired result
btn.click();
console.log('active element:', document.activeElement);
}, 5000);
<input type="text" />
<button id="btn">
button
</button>

Your code is working fine . It seems like it is not working only at JS Fiddle.
Well you can use "input type="text" autofocus=true .

Without java script we can auto focus the text box using css
https://www.tutorialspoint.com/online_css_editor.php
<head>
<style>
input[type=text]:focus{ outline: 3px solid red; }
</style>
</head>
<input type="text" style="height: 28px; width:350px; " autofocus>

I'm not sure what events you're talking about but you can call scripts on the load of a page in the body onload attribute? This will highlight the input when you load the page for example:
<html>
<body onload='document.querySelector("input").focus()'>
<input type="text" />
</body>
</html>
See this fiddle

Related

Create onchange event with javascript in Firefox

I've been working on trying to trigger an onchange listener with java script in Mozilla Firefox. I've found a lot on Stack Overflow posted about this, but nothing seems to be working for my unique case.
I've created this HTML with a onchange listener from an onchange event using this helpful post (JavaScript OnChange Listener position in HTML markup). Here's my code:
<HTML>
<head>
<script type="text/javascript">
window.onload= function () {
if(window.addEventListener) {
document.getElementsByClassName('search-box')[0].addEventListener('change', loadXMLDoc, false);
} else if (window.attachEvent){
document.getElementsByClassName('search-box')[0].attachEvent("onchange", loadXMLDoc);
}
function loadXMLDoc(){
alert('It worked');
}
}
function addTextCallListener() {
var searchBox = document.getElementsByClassName("search-box")[0];
searchBox.value = "Hello";
}
</script>
</head>
<BODY>
<input type="text" class="search-box" placeholder="Player Search">
<br \>
<button type="button" onclick="addTextCallListener()">Click Me!</button>
</BODY>
</HTML>
I also saved it as this jsfiddle (for some reason I had to keep it all together for it to work, I couldn't break it up into js and html).
https://jsfiddle.net/josephfedor42/crogL0zd/1/
If you play with this jsfiddle you can see that entering text and pressing enter will trigger the listener and the pop up with the message “It worked” will appear.
But if the button “Click Me!” is pressed it only changes the value of the text box, and the onchange listener is not called.
I realize I could easily add an onchange event to this button. But I want to to trigger the listener by programatically/ superficially using javascript in my addTextCallListener() function.
I've tried the simple stuff, like calling
searchBox.onchange();
searchBox.focus();
searchBox.click();
And a combination of these to add and remove the focus. But it doesn't seem to work. I've found quite a few posts on triggering an onchange event, but nothing that works in Firefox.
Any help would be appreciated.
Thanks for that link of a possible duplicated question. I had checked out that link before.
But I gave it a try again. I saved the jsfiddle from them both and neither one work.
My implementation of Dorian's answer
https://jsfiddle.net/josephfedor42/zaakd3dj/
My implementation of Alsciende's answer
https://jsfiddle.net/josephfedor42/xhs6L6u2/
emphasize mine
According to the mdn page about the change event,
The change event is fired for <input>, <select>, and <textarea>
elements when a change to the element's value is committed by the
user.
and to whatwg specs :
When the input and change events apply (which is the case for all
input controls other than buttons and those with the type attribute in
the Hidden state), the events are fired to indicate that the user has
interacted with the control.
Therefore, setting the value of an input is not an action "committed by the user" nor a sign that "the user has interacted with the control", since it was made by the code.
So, even if the specifications for this event are kind of unclear, the event should not fire when you change its value by code.
Something like this should work:
function addTextCallListener() {
var searchBox = document.getElementsByClassName("search-box")[0];
searchBox.value = "Hello";
//fire the event
if (document.createEvent) {
searchBox.dispatchEvent('change');
} else {
searchBox.fireEvent("onchange");
}
}
Here is the code I needed to add to my function addTextCallListener:
var evObj = document.createEvent('HTMLEvents');
evObj.initEvent( 'change', true, true );
searchBox.dispatchEvent(evObj);
I updated the jsfiddle. The working code is here https://jsfiddle.net/josephfedor42/crogL0zd/7/
Replace onchange with change in this part:
document.getElementsByClassName('search-box')[0].attachEvent("onchange", loadXMLDoc);

Is it okay to add an addEventListener to an entire page

I'm trying to show a textarea element when I click on an input element. The goal is to show the textarea, but when I click anywhere else, the textarea disappears.If I click anywhere on the textarea, it stays visible.
I saw a similar example of one on stackoverflow --> Link to similar question
The method was to add an addEventListener to the html tag by using document.documentElement, so basically the whole page, but I was wondering if there was an alternative? And is it safe to add an addEventListener to an entire page?
The code to addEventListener to entire page:
document.documentElement.addEventListener('click',clickhandler,false);
I'm not trying to be picky either, but I would like to avoid using a timeout on the element
Besides the code above, I first tried using the click event, and everything works fine, but when I click anywhere else the textarea doesn't disappear.
I then tried the focus/blur events, but when the input loses focus, the textarea disappears.
I was thinking of an if conditional for the click function... but I'm not sure how that would work without adding a click event to the entire page...
JSFiddle : http://jsfiddle.net/LghXS/
HTML\
<input type="text" id="email">
<textarea id="suggestion"></textarea>
CSS
textarea{
display:none;
}
JS
var textarea = document.getElementById('suggestion');
var input = document.getElementById('email');
// Using the Click Event
input.addEventListener('click',function(){
var display = textarea.style.display;
if(display === '' || display === 'none'){
textarea.style.display='inline-block';
}else{
textarea.style.display='none';
}
});
// Using the Focus and Blur
/*
input.addEventListener('focus',function(){
textarea.style.display='inline-block';
input.addEventListener('blur',function(){
textarea.style.display='none';
});
});
*/
Sooo, any ideas?

Activating a function by clicking outside the box

Alright so I'm having a bit of trouble with getting a function to work. All I have to do is to make the function activate once i click out from a HTML box.
<hmtl>
<body>
<center>
<script>
function calculateTax() {
var a = document.getElementById('boxone').value;
var b = document.getElementById('boxtwo').value;
var c = a/100*18;
b = c + a;
document.getElementById('boxone').value = a;
document.getElementById('boxtwo').value = b;
}
</script>
<input type="text" id="boxone" value="">
<input type="text" id="boxtwo" value=""><br>
<input type="hidden" onclick="calculateTax()">
</center>
</body>
</html>
Can anyone tell me what I should put instead of onclick and why my formula does not work.Thanks
I made a fiddle for you: http://jsfiddle.net/Dmc9Z/1/
Basically, you can add an onclick event to the body. I also added a button there which can submit it too, depending on what you want.
The reason your code wasn't working was because the input was being processed as a string. When you were 'adding', you were just concatenating values to the string. I added parseInt to fix that for you. I also removed some redundant code.
You want the onBlur event listener.
<input type="text" id="boxone" value="" onBlur="calculateTax()">
onBlur is the event called when an element loses focus - when you click away from an input, for example.
Adding an onClick to the body will work, but isn't the best approach because it will make the function run every time anyone clicks anywhere on your page - not just when they click away from the input.
I would suggest to keep your javascript and html separated. You can add an event listener to the body and make you it only fires when it's not an input field, for example like this:
document.getElementsByTagName("body")[0].addEventListener("click", function(target) {
if (target.nodeName === "INPUT") return false; // if our focus is an input field we don't want to fire the event
calculateTax();
}, false);

jQuery .focusout / .click conflict

I'm working on a project with an autocomplete searchbox. Now I have the issue that I want to pass the value from the found autocompleteresults to the input box, but on the same time, I want the autocompletebox to hide when the inputfield is not more focused.
Now I have a conflict going on with both of them since the click on the autocompletebox is seen as focusout and hide the box even before it can pass the value. Any pointers or workarounds for this kind of issue? Here a jsfiddle to make it more clear to you.
http://jsfiddle.net/KeGvM/
Or here
CSS:
#a_c {display:none;}​
JS:
$('#search_field').focusout(function() {
$('#a_c').hide(); // IF I DELETE THIS IT WORKS
});
$('#search_field').focusin(function() {
$('#a_c').show();
});
$('#a_c a').click(function() {
$('#search_field').val('');
var value = $(this).text();
var input = $('#search_field');
input.val(input.val() + value);
$('#a_c').hide();
return false;
});​
HTML:
<input autocomplete="off" onkeyup="searchFor(this.value);" name="search" id="search_field" class="bold" type="text" placeholder="Search...">
<div id="a_c">hello world</div>​
The way I solved this was using the mousedown event instead of click. The mousedown event is always triggered before the focusout event while click is not.
You can try it out in the little demo below. Focus on the field and then click on the button.
const field = document.getElementById('field');
const btn = document.getElementById('btn');
btn.addEventListener('click', () => console.log('Click'));
btn.addEventListener('mousedown', () => console.log('Mouse down'));
field.addEventListener('focusout', () => console.log('Focus out'));
<input id="field">
<button id="btn">Try it</button>
As you can see the output is in the following order:
Mouse down
Focus out
Click
This is the most stable solution without using any workaround hacks like timeouts. It also does not depend on jQuery. The only thing worth noting that mousedown does not wait for the user to release their mouse button, but in terms of user experience that is not really a concern here.
How about using
:hover
I solved same problem using it.
$('className').on('focusout', function(e) {
if($('.suggestLi' + ':hover').length) {
return;
}
$('.suggestList').empty();
});
My solution in the similar situation was using timeout to temporarily hold off the action taken in blur event handler. Like this:
$('#search_field').focusout(function() {
window.setTimeout(function() { $('#a_c').hide() }, 100);
});

test whether button being clicked before running function on element.blur()

I have a function called showHide() that alternately shows and hides a text input field and a button (button2) when another button (button1) is clicked. The text input field is automatically focused when it opens, and this works great.
The HTML looks roughly thus:
<button1>Show/Hide</button>
<form>
<input class="hidden" type="text" />
<button2 type="submit">Submit</button>
</form>
<script type="text/javascript">
$("button1.someSelectors").click(function() {showHide();});
$("input.someSelectors").blur(function() {showHide();})
</script>
I would like to extend the function such that when the input field loses focus it and button1 disappear, unless it loses focus because button1 is being clicked. As it reads now I'm only testing whether the input field has focus or not. How can I also check whether button2 is being clicked or not?
I tried:
$("input.someSelectors").blur(function() {
if (!$("button2.someSelectors").is(":focus")) {
showHide();
}
});
but it hid the form elements even when I tried clicking button2.
An alternative would be to test whether button2 is being clicked or not in the "hide" part of the function, but when I added
if(!$("button2.someSelectors").click()) {do the hide part of the function}
to showHide(), the form got submitted when I clicked button1 or button2. Here is an example of my problem. Can anyone help?
--Edit:
var showHide=function(item, category) {
if($("input."+item+"."+category).hasClass("hidden")) {
$("input."+item+"."+category).show("fast").focus().removeClass("hidden");
$("button.buy."+item+"."+category).show("fast");
$("button.purchase."+item+"."+category).text("Never mind!");
} else {
$("input."+item).hide("fast").addClass("hidden");
$("button.buy."+item).hide("fast");
$("button.purchase."+item).text("Purchase");
}
}
blur event on textbox is triggered before the click event fires on the button. In order to avoid that you can use mousedown event instead of click event which will be triggered before click event. Try this
$("button1.someSelectors").mousedown(function() {showHide();});
$("input.someSelectors").blur(function() {showHide();})

Categories