What eventListener Should I use here? - javascript

I am creating this compiler and my problem is that I need to detect the changes in the upper text box and I was able to detect all changes except the change when the user clicks the clear button and the text clears up in the box. Can anyone please suggest what js event listener I can use to detect this?

You can use the simple addEventlistener as follow:
<!DOCTYPE html>
<html>
<body>
<p>This example uses the addEventListener() method to attach a click event to a button.</p>
<button id="myBtn">Try it</button>
<p id="demo">Hello</p>
<script>
document.getElementById("myBtn").addEventListener("click", function() {
document.getElementById("demo").innerHTML = " ";
});
</script>
</body>
</html>
As you can see here, the p tag earlier had a value but after the button is clicked the value into p tag is set to the value assigned in the js. So what you have to do is to make the value inside your text field to null by using the .innerHTML=" "

onclick event will be helpful.
let button = document.getElementById('clear_Code');
let textbox = document.getElementById('textbox');
button.onclick = function() {
textbox.innerText = '';
}

Related

Click two elements at the same time by clicking one button with javascript

Is it possible to click one button and simultaneously click another element. Like I click a button to show an image and simultaneously let something else appear which would also appear when clicking on it
It's totally possible. You have to get the click event of the element, and you can do whatever you want.
Example:
<button id="button">I am a button</button>
<div id="anotherElement"></div>
<script>
const button = document.getElementById('button');
const anotherElement = document.getElementById('anotherElement');
button.addEventListener('click', () => {
// do whatever you want here
anotherElement.click();
});
</script>
As our friend Said says, is possible, just I think if would be better if you name classes instead of ID because is a better practice
<button class="button">Do something here</button>
<button class="button">And here</button>
<script>
const button = document.getElementsByClassName ('button');
button.addEventListener('click', () => {
// do whatever you want here
});
</script>

Setting focus on input with script only

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

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);

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);

The click event from javascript on a button doesn't fire

So, I was going through a tutorial on event handlers. I created a button as instructed and then when I click on it, I wanted an alert to be displayed. Thats it. But it wouldn't work. Here's my html code:
<button id="submit">Submit</button>
And here's my javascript code:
var myButton = document.getElementByID("submit");
myButton.onclick = function(){
alert("YOu clicked on this button");
}
I am using external js file and I've included it in the html from the head of the document.
document.getElementByID("submit"); -- it's Id instead of ID
Edit: I feel very bad for giving this one-liner as an answer, so to add to what others have said about learning how to use the browser's console as a debuggining tool, you should try to find an IDE/text editor with auto-completion to save you such headaches especially when you're just starting out.
You may have an issue where document.getElementById() is happening before the element is created on the page. Try including your JavaScript in an onload event, or include it after the button in your HTML.
As previously stated, use document.getElementById("submit") with lower case Id. Also, you may want to use setAttribute so the alert fires when the button is pressed instead of immediately opening a popup when the alert line is encountered.
<script language="javascript">
var myButton = document.getElementById("submit");
myButton.setAttribute("onclick", "alert('You clicked on this button')");
</script>
change from document.getElementByID to document.getElementById and make sure your script stay below all the elements in the body. Example:
<body>
<button id="submit">Submit</button>
<script type="text/javascript">
var myBtn = document.getElementById("submit");
myBtn.onclick = function()
{
alert("this is a click event button");
};
</script>
</body>
or you can put the script inside the <head></head> by add this event below to your script:
function initialize()
{
// paste your code in here
}
document.addEventListener("DOMContentLoaded",initialize,false);
Hope it work!
it maybe a typo. It is getElementById not ID

Categories