How to put a JavaScript function in an HTML onclick - javascript

Hello I would like to put my JavaScript function in an onclick html because I have several exercises on my page
<button type="button" onclick="formatTime()">Click</button>

Your button should call the javascript function formatTime() onclick, there is nothing wrong with the HTML. Does the Chrome/Firefox Developer Console output any errors on click?
See here for an example.
<button type="button" onclick="foo()">click</button>
<script>
function foo() {
alert('hello world');
}
</script>

Related

Create an HTML button that works as a link with an "onclick"?

I'm new in HTML and I would like some help, I would like to create an HTML button that acts like a link.
So, when you click the button, it redirects to a page locally stored in the same file, which is named "page 2 html",
I have a code line:
<button type="submit">connect</button>
I would like to add a "window.onclick" function to this button which redirect to "page 2 html" and what will be the javascript function that goes with it?
Thanks.
There are a number of ways to do this, If you are stuck to a submit button, you would have to tie it to a form, then make the form's action attribute the link:
<form>
<button type="submit" formaction="https://placekitten.com/">Click Me</button>
</form>
or you could do it as a regular button:
var gimmeCats = () => {
window.location.href = "https://placekitten.com/";
}
<button id="catBtn" onclick="gimmeCats()">Click Me!</button>
Or, if you aren't opposed to bootstrap, there is this:
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
Click Me!!!!!!!!!
Using window.onclick will not do it because you are telling your browser that when you click anywhere in the window it will execute it. So you can use location.replace('') like this:
<input type="submit" onclick="location.replace('page2.html')"/>
Or using a regular button:
<button onclick="location.replace('page2.html')">Page 2</button>
Or by using a function:
<script>
function redirect() {
location.replace('page2.html');
}
</script>
<button onclick="redirect()">Redirect</button>
You could also just use a normal <a> tag:
<button>Redirect</button>

addEventListener function works at the beginning without being fired [duplicate]

This question already has answers here:
Why does click event handler fire immediately upon page load?
(4 answers)
Closed 4 years ago.
So here are my HTML codes:
document.getElementById("sub").addEventListener("click", testing());
function testing() {
document.getElementById("demo").innerHTML ="good";
}
<input type="submit" value="Place Order" id="sub"/>
</fieldset> </form>
<p id="demo"></p>
<script type="text/javascript" src="Q4.js"></script>
In which I declared a button to submit the form.
I added an event to the submit button to run the function testing().
I expected that when the user clicks on the button submit, the page will prompt "good". But, as soon as I load the page, "good" already appeared without clicking in the button.
result page
Why does this happen?
You should remove parentheses to prevent function testing() to be executed. Just put the name of the function.
You can find more details and simple example of listener here.
Here is a working snippet :
/*file javaScript Q4.js*/
document.getElementById("sub").addEventListener("click", testing);
function testing() {
document.getElementById("demo").innerHTML ="good"; }
<input type="submit" value="Place Order" id="sub"/>
</fieldset> </form>
<p id="demo"></p>
<script type="text/javascript" src="Q4.js"></script>
You can also put your function directly into your listener, like this :
document.getElementById("sub").addEventListener("click", function() {
document.getElementById("demo").innerHTML="good";
});
About the bug that "show the good word for a second only" :
Clicking the button causes the form to be submitted, which means the page reloads or the loads the URL in action. That means that all
temporary changes that JavaScript made in the current page load are
gone. Thanks Felix Kling
Change this line :
document.getElementById("sub").addEventListener("click", testing());
to
document.getElementById("sub").addEventListener("click", testing);
addEventListener function accept two parameters
Event name
Callback function
options (optional)
So you had called function inspite of passing function reference there.
Write it down to like below
document.getElementById("sub").addEventListener("click", testing);
OR
document.getElementById("sub").addEventListener("click", function testing() {
document.getElementById("demo").innerHTML ="good";
})
You don't need parenthesis.
document.getElementById("sub").addEventListener("click", testing);

Uncaught ReferenceError: search_for_all is not defined at HTMLAnchorElement.onclick (index.html:49)

I'm basically calling a function called search_for_all() located in a JS file, on an onclick event of the button in my HTML page. But I keep getting the above error.
I'm supposed to print the result of the function in a <p> tag in my HTML file. Following is the code that has the onclick event-
<a id="files" class="btn btn-block btn-lg btn-primary" onclick="search_for_all('https://demo.dataverse.org', 0, 'file')">Files</a>
I'm using document.getElementById("output").innerHTML; inside my JavaScript function to print its result.
Using inline event handlers is bad practice and results in poorly factored, hard-to-manage code. Seriously consider attaching your events with JavaScript, instead, eg: https://developer.mozilla.org/en/DOM/element.addEventListener
If you attach the listener in the same scope that you define the function, it should work properly. For example:
HTML:
<a id="files" class="btn btn-block btn-lg btn-primary">Files</a>
Javascript:
// ... lines of code ...
// declaration of search_for_all function:
function search_for_all(url, param1, param2) {
// ...
}
document.querySelector('#files').addEventListener('click', () => {
search_for_all('https://demo.dataverse.org', 0, 'file');
});

Loading javascript function on button event

I would like to call a Javascript function once the button is displayed on screen. What I am looking for is similar to the 'onclick' attribute:
<input type="button" class="button-class" onclick="function(this)">
However, I would like the function to be called as soon as the button is displayed on screen i.e. it should be instantaneous (button creation=function call). I have already tried 'onload' but this does not seem to work. Is there a way to do this please?
Thank you
Put an script element invoking the function after the button element
<input type="button" class="button-class" onclick="fn(this)" value="button" id="btn">
<script>
function fn(obj){
console.log(obj)
}
fn(document.getElementById("btn"));
</script>
#Questionnaire, you can't do what you want since an action should take place for a button (click event) to execute code.
As a good practice, load your Javascript code after the page is done loading. This is to avoid blocking the rendering of HTML code since
Javascript is synchronous.
...
<script type="text/javascript">
function init() {
// Code for your button function here
}
window.onload = init();
</script>
</html>
The code above is pretty much it.
Just write the function name in onclick property instead of function(this) like the following..
<script>
function myFunc(e){
//do something
}
</script>
<input type="button" class="button-class" onclick="myFunc(this)">
#Bartman pointed out how the .ready() funtion handled it as a document.ready.
So i came up with a small solution to run the waanted funtion once the input button is created. Hotfix but cant imagine another solution
I hope this helps. If not please add a comment so i can edit the answer.
function clickFunc(e) {
alert("click event");
}
function loadFunc() {
alert("load event");
}
$("#button").click(function() {
$("div").append("<input id=\"but\" type=\"button\" class=\"button-class\" onclick=\"clickFunc(this)\">");
$("body").append("<script>loadFunc();<\/script>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="button" type="button">
<div></div>

Google Closure onclick event not working

I have the following button in a HTML file:
<button id="signupbutton" name="signup.submit" type="submit" class="btn">Sign up</button>
I am using pyramid and I include closure base and my script like this:
<script src="${request.static_url('app:javascripts/closure-library/closure/goog/base.js')}"></script>
<script>
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.dom')
goog.require('goog.dom.forms');
</script>
<script src="${request.static_url('app:javascripts/checks.js')}"></script>
In my javascript file checks.js I wrote:
var buton = goog.dom.getElement('signupbutton');
goog.events.listen(
buton,
goog.events.EventType.CLICK,
function(e) {
alert("Here");
});
What I get in the console is a TypeError: src is null events.js:954 (var listenerMap = src[goog.events.LISTENER_MAP_PROP_];) and nothing happens, only the page reloads!
If I create the button using google closure it works! So I can't figure out what the problem is!
its seem because your button is not in the DOM when your javascript is executed.
You should execute your script only after the button's been loaded in the DOM.
TypeError: src is null events.js:954
Example : http://jsfiddle.net/zeroc00l/ZugNX/

Categories