new function in onclick - javascript

EDIT: Just an example. I need support for if/else
I want to do this:
<button onclick="function() {alert('Hi!');prompt('What can I do for you?', 'make a Sandwich');}">Hello World!</button>
Apparently this doesn't work.
Do you know how I could do this?
How can I "call" a new function?
I cannot simply define it in a <script></script>-node.

You don't need a function to call. You can directly use Javascript code. This is considered bad practice.
<button onclick="alert('Hi!'); prompt('What can I do for you?','make a Sandwich');">
Hello World!
</button>
Demo
You can also use function as event handler as follow:
HTML
<button onclick="fnHandler();">
Hello World!
</button>
Javascript
function fnHandler() {
alert('Hi!');
prompt('What can I do for you?','make a Sandwich');
}
Demo
Using addEventListener you can bind events from javascript instead of inline in the HTML(Recommended):
HTML
<button id="myButton">
Hello World!
</button>
Javascript
document.getElementById('myButton').addEventListener('click', function() {
alert('Hi!');
prompt('What can I do for you?','make a Sandwich');
});
Demo

It is not recommended to write the functions inside the parameter. It is better to write them on a separate function and then link it with one of the methods listened above. You can still do what you said in the example by using the anonimous function like this:
<button onclick='(function(){
alert("hello world");
prompt("I am the Doctor","oh yeah");
})()'></button>

Updated version for general function because add listner adds uniqueness for click
<button onclick="function_name() id="button">Some Text</button>
Now to write the function definition in js
function function_name(){ .... statements; }
A typical example using this with if-else
<script>
document.getElementById('button').onclick = function() {
if (Calc.Input.value == '' || Calc.Input.value == '0') {
window.alert("Please enter a number");
} else {
document.getElementById('button').value=' Justera längd ';
}
return false;
}
</script>

Related

How to add two onclick method in one button? [duplicate]

Is there any way to use the onclick html attribute to call more than one JavaScript function?
onclick="doSomething();doSomethingElse();"
But really, you're better off not using onclick at all and attaching the event handler to the DOM node through your Javascript code. This is known as unobtrusive javascript.
A link with 1 function defined
Click me To fire some functions
Firing multiple functions from someFunc()
function someFunc() {
showAlert();
validate();
anotherFunction();
YetAnotherFunction();
}
This is the code required if you're using only JavaScript and not jQuery
var el = document.getElementById("id");
el.addEventListener("click", function(){alert("click1 triggered")}, false);
el.addEventListener("click", function(){alert("click2 triggered")}, false);
I would use the element.addEventListener method to link it to a function. From that function you can call multiple functions.
The advantage I see in binding an event to a single function and then calling multiple functions is that you can perform some error checking, have some if else statements so that some functions only get called if certain criteria are met.
Sure, simply bind multiple listeners to it.
Short cutting with jQuery
$("#id").bind("click", function() {
alert("Event 1");
});
$(".foo").bind("click", function() {
alert("Foo class");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo" id="id">Click</div>
ES6 React
<MenuItem
onClick={() => {
this.props.toggleTheme();
this.handleMenuClose();
}}
>
var btn = document.querySelector('#twofuns');
btn.addEventListener('click',method1);
btn.addEventListener('click',method2);
function method2(){
console.log("Method 2");
}
function method1(){
console.log("Method 1");
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Pramod Kharade-Javascript</title>
</head>
<body>
<button id="twofuns">Click Me!</button>
</body>
</html>
You can achieve/call one event with one or more methods.
You can add multiple only by code even if you have the second onclick atribute in the html it gets ignored, and click2 triggered never gets printed, you could add one on action the mousedown but that is just an workaround.
So the best to do is add them by code as in:
var element = document.getElementById("multiple_onclicks");
element.addEventListener("click", function(){console.log("click3 triggered")}, false);
element.addEventListener("click", function(){console.log("click4 triggered")}, false);
<button id="multiple_onclicks" onclick='console.log("click1 triggered");' onclick='console.log("click2 triggered");' onmousedown='console.log("click mousedown triggered");' > Click me</button>
You need to take care as the events can pile up, and if you would add many events you can loose count of the order they are ran.
One addition, for maintainable JavaScript is using a named function.
This is the example of the anonymous function:
var el = document.getElementById('id');
// example using an anonymous function (not recommended):
el.addEventListener('click', function() { alert('hello world'); });
el.addEventListener('click', function() { alert('another event') });
But imagine you have a couple of them attached to that same element and want to remove one of them. It is not possible to remove a single anonymous function from that event listener.
Instead, you can use named functions:
var el = document.getElementById('id');
// create named functions:
function alertFirst() { alert('hello world'); };
function alertSecond() { alert('hello world'); };
// assign functions to the event listeners (recommended):
el.addEventListener('click', alertFirst);
el.addEventListener('click', alertSecond);
// then you could remove either one of the functions using:
el.removeEventListener('click', alertFirst);
This also keeps your code a lot easier to read and maintain. Especially if your function is larger.
React Functional components
<Button
onClick={() => {
cancelAppointment();
handlerModal();
}}
>
Cancel
</Button>
const callDouble = () =>{
increaseHandler();
addToBasket();
}
<button onClick={callDouble} > Click </button>
It's worked for me, you can call multiple functions in a single function. then call that single function.
Here is another answer that attaches the click event to the DOM node in a .js file. It has a function, callAll, that is used to call each function:
const btn = document.querySelector('.btn');
const callAll =
(...fns) =>
(...args) =>
fns.forEach(fn => fn?.(...args));
function logHello() {
console.log('hello');
}
function logBye() {
console.log('bye');
}
btn.addEventListener('click',
callAll(logHello, logBye)
);
<button type="button" class="btn">
Click me
</button>
You can compose all the functions into one and call them.Libraries like Ramdajs has a function to compose multiple functions into one.
Click me To fire some functions
or you can put the composition as a seperate function in js file and call it
const newFunction = R.compose(fn1,fn2,fn3);
Click me To fire some functions
This is alternative of brad anser - you can use comma as follows
onclick="funA(), funB(), ..."
however is better to NOT use this approach - for small projects you can use onclick only in case of one function calling (more: updated unobtrusive javascript).
function funA() {
console.log('A');
}
function funB(clickedElement) {
console.log('B: ' + clickedElement.innerText);
}
function funC(cilckEvent) {
console.log('C: ' + cilckEvent.timeStamp);
}
div {cursor:pointer}
<div onclick="funA(), funB(this), funC(event)">Click me</div>

My function is being run before a button is clicked [duplicate]

This question already has answers here:
Why is the method executed immediately when I use setTimeout?
(8 answers)
Closed 4 years ago.
In the code below, why does the header text change on page load, and not only after the button is clicked?
<h1 id="header">This is a header</h1>
<button id="btn1">Change text</button>
<script>
function change_text(target_id, target_text) {
document.getElementById(target_id).textContent = target_text;
}
button1 = document.getElementById("btn1")
button1.onclick = change_text("header", "something")
</script>
If you wanted to reuse that function and keep the onclick out of the markup, you could do this:
<h1 id="header">This is a header</h1>
<button id="btn1">Change text</button>
<script>
function change_text(target_id, target_text) {
document.getElementById(target_id).textContent = target_text;
}
button1 = document.getElementById("btn1")
button1.onclick = function () {
change_text("header", "something");
}
</script>
This uses something called an anonymous function.
Learn more here: JavaScript Functions
The issue is this line:
button1.onclick = change_text("header", "something")
The JS engine will do the following in this order:
Call change_text with the arguments "header" and "something"
Assign the result of change_text (in this case, undefined) to button1.onclick
Jane Doe's answer should work. If you want to keep your current code structure, then you could use the following:
button1.onclick = function(){
change_text("header", "something");
};
This creates an anonymous function and assigns it to onclick. When onclick is triggered, it will execute the function which calls change_text.
Can you try:
<h1 id="header">This is a header</h1>
<button onclick="change_text('header', 'something')" id="btn1">Change text</button>
<script>
function change_text(target_id, target_text) {
document.getElementById(target_id).textContent = target_text;
}
</script>
I am pretty confident that will work as intended for you..
The reason is simple: you have already called change_text("header", "something") in your code. You are basically doing the same thing as:
let res = change_text("header", "something") // already called, res is undefined
button1.onclick = res
If you are actually passing an event handler, it should looks like button1.onclick = change_text, with change_text() taking an event as param instead. OR as seen in the other answer, <button onclick="change_text('header', 'something')" id="btn1">Change text</button> (this creates an anonymous function that would be called on click event)

Is there something like a clicked===true conditional statment in javascript?

using javascript, is there a condition something like this
if (clicked===true && var===3) {
function executes here
}
if there isn't, how can you get the same effect?
For mouse and UI handling the Javascript model is based on events. In other words what you do is
element.onclick = function() {
// what to do when that element is clicked
};
for example:
<!DOCTYPE html>
<html>
<body>
<div id="thediv">Click me</div>
<script>
document.getElementById("thediv").onclick = function() {
alert("Awww... why did you do that?");
};
</script>
</body>
</html>
you have to bind an eventhandler to the element. you can do this inline with an onclick eventhandler. Also you can't use the name var because it is a reserved word in javascript.
html
<a id="mylink" href="#" onclick="handleMyClick();">Click me</a>
javascript
var myvar=3;
handleMyClick(){
if(myvar==3){
alert("you clicked the link and myvar is 3");
}
}

Why does the onclick fire next function not assigned to it?

Why clicking the button fires the alert? It is assigned to the paragraph, not button.
HTML:
<button onclick="foo()">Click me</button>
<p id="hidden" style="display:none"> I was hidden </p>
Javascript:
function foo(){
document.getElementById("hidden").style.display = "block";
document.getElementById("hidden").onclick = innnerClick();
}
function innnerClick(){
alert("Ouch! That hurt!")
}
Because of this line:
// ----------------------------------------------------vv
document.getElementById("hidden").onclick = innnerClick();
Here you call the innnerClick function immediately.
Just remove () after to pass the reference to a function instead of calling it, i.e.
document.getElementById("hidden").onclick = innnerClick;
Since, you need to add the reference of the function like this:
function foo(){
document.getElementById("hidden").style.display = "block";
document.getElementById("hidden").onclick = innnerClick;
}
not directly calling it.
Fiddle Demo
In jQuery, we can reproduce the same issue like:
$('button').click(function () {
$('#hidden').show();
$('#hidden').click(innnerClick()); <-- see the function with () here
});
Fiddle Demo
The issue is same here, we just need to pass the function reference to click handler here like:-
$('#hidden').click(innnerClick);
Fiddle Demo

javascript onclick change onclick to new function

I need to be able to change the onclick event of an id so that once it has been clicked once it executes a function which changes the onclick event
Here is my code:
Javascript:
function showSearchBar()
{
document.getElementById('search_form').style.display="inline";
document.getElementById('searchForm_arrow').onclick='hideSearchBar()';
}
function hideSearchBar()
{
document.getElementById('search_form').style.display="none";
document.getElementById('searchForm_arrow').onclick='showSearchBar()';
}
and here is the HTML:
<!-- Search bar -->
<div class='search_bar'>
<img id='searchForm_arrow' src="images/icon_arrow_right.png" alt=">" title="Expand" width="10px" height="10px" onclick='showSearchBar()' />
<form id='search_form' method='POST' action='search.php'>
<input type="text" name='search_query' placeholder="Search" required>
<input type='image' src='images/icon_search.png' style='width:20px; height:20px;' alt='S' >
</form>
</div>
Thanks
Change your code in two places to reference the new functions directly, like:
document.getElementById('searchForm_arrow').onclick=hideSearchBar;
Can you try this,
function showSearchBar()
{
if(document.getElementById('search_form').style.display=='none'){
document.getElementById('search_form').style.display="inline";
}else{
document.getElementById('search_form').style.display="none";
}
}
You were nearly right. You are settingthe onclick to a string rather than a function. Try:
in showSearchBar()
document.getElementById('searchForm_arrow').onclick=hideSearchBar;
in hideSearchBar()
document.getElementById('searchForm_arrow').onclick=showSearchBar;
You do not need to create two function.
Just create one function and using if condition you can show and hide the form tag..
function showSearchBar()
{
if(document.getElementById('search_form').style.display=='none'){
document.getElementById('search_form').style.display=''; // no need to set inline
}else{
document.getElementById('search_form').style.display='none';
}
}
function searchBar(){
var x = document.getElementById('search_form').style.display;
x = (x == 'inline') ? 'none' : 'inline';
}
You can wrap up both functions into one by adding a check to the current condition of the element and applying your style based on that condition. Doesn't actually change the function but doesn't need to as there is now only one functon performing both actions.
With javascript you can check and perform opration
function SearchBarevent()
{
if(document.getElementById('search_form').style.display=='none'){
document.getElementById('search_form').style.display="inline";
}else{
document.getElementById('search_form').style.display="none";
}
}
or if you may go for jquery there is better solution toogle
Like:
$("#button_id").click(function(){
$( "#search_form" ).toggle( showOrHide );
});
Fiddle is example
Here is an option that uses jQuery:
$('#searchForm_arrow').click(function() {
$('#search_form').slideToggle();
});
http://jsfiddle.net/PuTq9/

Categories