calling two js functions one after another using one button - javascript

Here is my code, not working please help I want to call two js functions using one submit button.I have tried the below code.But it gives error.
function scrollWin() {
// First time click
if (e.name != 'Click') {
e.name = "Click";
function scrollWin() {
window.scrollBy(0, 85);
}
}
// When click it again..
else if (e.name == 'Click') {
e.name = "Unclick";
function myFunction() {
document.getElementById("demo").innerHTML = "<h2> Second Click </h2>";
}
}
}
<input type="button" onclick="scrollWin(); this.style.visibility= 'hidden';
myFunction()" value="Click Me" />
<p id="demo"></p>

You need to define one function which handles this action. It is probably best to store a variable where you can save the state of the clicking. Here is an example:
var clickCount = 0;
function scrollWin(button) {
// first click
if (clickCount === 0) {
window.scrollBy(0, 85);
}
// second or more click
else {
document.getElementById("demo").innerHTML = "<h2> Second Click </h2>";
button.style.display = 'none';
}
clickCount++;
}
<input type="button" onclick="scrollWin(this)" value="Click Me" />
<p id="demo"></p>

You need to get the fundamentals right. A function call will have its own scope and once the scope of a function ends, the variables are destroyed. I think you want to capture a second click for the element.
Don't try declaring a global variable for the same but try to set the elements property on first click which you can access on the second click. read that property on click and then manipulate.
I would suggest you to call the click event as
onclick="click123(this);"
and use this to set the property using setAttribute

I think this accomplishes what you described. You need to pass in the event of the button click and read the button text, but e.name probably wont work you'll need to use innerHTML or textContent. Then you can either perform the operations or call the functions you wish to execute depending on the button text which changes after the 2nd click.
function scrollWin(e) {
//First time click
if(e.textContent != 'Click'){
e.textContent = "Click";
window.scrollBy(0, 85);
}
else if(e.textContent == 'Click'){
e.textContent = "Unclick";
document.getElementById("demo").innerHTML = "<h2> Second Click </h2>";
}//end else
}//end function
<button onclick="scrollWin(this)">Click</button>
<div id="demo"></div>

What I understand you want to perform two operation on same button but in two different condition, if you want to perform keep state and perform action according to that then. Like:
function scrollWin(e) {
var btn = e.target;
var state = btn.dataset.myattr;
if( state == 'state1'){
btn.dataset.myattr = 'state2';
e.name = "Click";
window.scrollBy(0, 85);
}else if (state == 'state2'){
btn.dataset.myattr = 'state1';
e.name = "Unclick";
document.getElementById("demo").innerHTML = "<h2> Second Click </h2>";
}
}
If you want to change the name attribute to something else you can do that and you don't have to change the JS code for that.

Related

I have to double click the follow button to functioning this is due to using click event 2 time

I am working on follow button and with the help of JavaScript I've come up with the following code.
But the problem is I have to double click the follow button to functioning this is due to using click event 2 time. I am open to better methods of solving this too.
var value = null;
const onClick = (event) => {
// event.target.id
value = event.target.id;
console.log(value);
document.getElementById(`${value}`).addEventListener('click',function(){
// console.log(value.id);
if(this.classList.contains('follow')){
this.classList.remove('follow');
this.innerHTML ="Following";
this.style.backgroundColor = 'green' ;
}else{
this.classList.add('follow');
this.style.backgroundColor = 'rgb(27,18,83)' ;
this.innerHTML="Follow";
}
})
}
window.addEventListener('click', onClick);
There is a double click event. You can check the if it satisfies your requirement.
MDN link - https://developer.mozilla.org/en-US/docs/Web/API/Element/dblclick_event
For multiple buttons with the same function, I would give all of them the same class (e.g. "btn"). Then in JS simply get all of the elements with this class, loop over the HTMLCollection which you would get and assign each element an eventlistener. When you want to change something on the button you have to use event.target in the function:
let buttons = document.getElementsByClassName("btn");
for (btn of buttons) {
btn.addEventListener("click", (event) => {
if(event.target.classList.contains('follow')){
event.target.classList.remove('follow');
event.target.innerHTML ="Following";
event.target.style.backgroundColor = 'green' ;
}else{
event.target.classList.add('follow');
event.target.style.backgroundColor = 'rgb(27,18,83)' ;
event.target.innerHTML="Follow";
}
});
}
<button class="btn">1</button>
<button class="btn">2</button>

Can I check if a JavaScript function is called from a button's onclick attribute?

I have a JavaScript function that can be called either from a button click or from another function.
I am working on a simple game made with vanilla JavaScript and I have a function as below:
function end() {
// End the game
}
which can be called from a button click:
<input type="submit" id="endBtn" value="End Game" onclick="end()">
and can also be called from another JavaScript function:
function play() {
// Game logic
end();
}
The game can be ended by either the user clicking on the button or if certain conditions in the play() function are met.
Is it possible to know if the function is called from a button click?
As by default functions called from events are automatically passed an event value, you can check to see if the event value is not equal to undefined. Code example:
function yourFunction(event = undefined) {
if (event && typeof(event) == "object") {
alert("Called from element")
} else {
alert("Not called from element")
}
}
yourFunction()
<button onclick="yourFunction(event)">Click me!</button>
Yes, it's possible to assess whether it was called from a button click, see below:
btn = document.getElementById("btn");
testDiv = document.getElementById("testDiv");
btn.addEventListener("click", () => {
const payload = "called from button";
randomFn(payload);
});
function randomFn(getInput) {
testDiv.innerHTML = getInput;
}
<button id="btn">Click</button>
<div id="testDiv"></div>
Just let the function accept a string like "calledBy", like:
function myEvent(calledBy){
if(calledBy=="button") //It has been called by the button
else //It has been called by function
}
In your other function you pass "func" as parameter, while in the button you pass "button"
function secondFunction(){
//Do Stuff
myEvent("func");
}
In your button:
...onClick=myEvent('button')...
Hope to be clear, there might be other solutions, but this is the first thing that came in my mind.
One way to get this is by adding another parameter to the function that will allow you to differentiate the source. I.e. if you have a function
function abc(argument1) {
//logic
}
You could add
function abc(argument1, argument2){
if (argument2 === 'button' {
//some logic
}
//logic
}
If you call it from the button, you can call it with onClick: () => abc(argument1, 'button') so you know it came from the button. If called elsewhere, you would change the argument provide from 'button' to whatever you like.
the this in the element onclick will pass the element itself
so you can check if it's an element or not
function test(ele) {
if (ele instanceof Element) {
console.log("this is call by click button");
} else {
console.log("this is call by other way");
}
}
test();
<button onclick="test(this)">ckick me</button>
Actually there may be a workaround. Give your function a string parameter for ex $notifier.
When calling from button click give $notifier parameter as 'button' or whatever meaningful.
So from there by checking the parameter value you can get to know from where the function is fired.
function myFunction(notifier){
if (notifier=='button'){
// triggered from button
}
else if(notifier=='function'){
// triggered from function
}
}
and on button -> onclick="myFunction('button')"
I am not exactly sure what you are trying to do. However, if you truly must log/check if it was a button click or called from another function, you can do something like this:
function triggerFromFunction(d) {
triggerClick(true);
}
function triggerClick(comingFromFunction = false) {
document.getElementById("show").innerHTML = 'Coming from Function = ' + comingFromFunction;
}
<button onclick="triggerClick()">Trigger Click</button>
<button onclick="triggerFromFunction()">Trigger Function</button>
<p id="show"></p>
This solution is based on ES2015. Otherwise you can check if parameter is undefined in an if statement and proceed from there. Checkout:
https://www.w3schools.com/howto/howto_js_default_parameters.asp
All you need to do is look at the function parameters, specifically event.type, which all events will pass, if it has no params it must have been called directly (though you can pass a type if you wanted)
const button = document.getElementById("button");
const result = document.getElementById("result");
button.addEventListener("click", theFunction);
button.addEventListener("mouseover", theFunction);
button.addEventListener("mouseout", theFunction);
function theFunction(e) {
if (e && e.type) result.innerHTML = 'from ' + e.type
else result.innerHTML = 'has no type, perhaps theFunction()'
}
theFunction({type: 'foo'})
<button id="button">Click</button>
<div id="result"></div>

Function activate after two onclicks

Hey I'm using javascript+html only.
Is there any way to activate a function after the button has been clicked two (or more) times? I want the button to do NOTHING at the first click.
For a "doubleclick", when the user quickly presses the mouse button twice (such as opening a program on the desktop), you can use the event listener dblclick in place of the click event.
https://developer.mozilla.org/en-US/docs/Web/Reference/Events/dblclick
For a quick example, have a look at the below code. http://jsfiddle.net/jzQa9/
This code just creates an event listener for the HTMLElement of "item", which is found by using getElementById.
<div id="item" style="width:15px;height:15px;background-color:black;"></div>
<script>
var item = document.getElementById('item');
item.addEventListener('dblclick',function(e) {
var target = e.target || e.srcElement;
target.style.backgroundColor = 'red';
},false);
</script>
As for wanting the user to click an element X times for it to finally perform an action, you can do the following. http://jsfiddle.net/5xbPG/
This below code works by adding a click tracker to the HTMLElement and incrementing the click count every time it's clicked. I opted to save the clicks to the HTMLElement instead of a variable, but either way is fine.
<div id="item" style="width:15px;height:15px;background-color:black;"></div>
<script>
var item = document.getElementById('item');
item.addEventListener('click',function(e) {
var target = e.target || e.srcElement;
var clicks = 0;
if(target.clicks)
clicks = target.clicks;
else
target.clicks = 0;
if(clicks >= 4) {
target.style.backgroundColor = 'red';
}
target.clicks += 1;
},false);
</script>
== UPDATE ==
Since you recently posted a comment that you want two different buttons to be clicked for an action to happen, you would want to do something like this... http://jsfiddle.net/9GJez/
The way this code works is by setting two variables (or more) to track if an element has been clicked. We change these variables when that item has been clicked. For each event listener at the end of changing the boolean values of the click state, we run the function checkClick which will make sure all buttons were clicked. If they were clicked, we then run our code. This code could be cleaned up and made to be more portable and expandable, but this should hopefully get you started.
<input type="button" id="button1">
<input type="button" id="button2">
<div id="result" style="width:15px;height:15px;background-color:black;"></div>
<script>
var result = document.getElementById('result');
var button1 = document.getElementById('button1');
var button2 = document.getElementById('button2');
var button1Clicked = false;
var button2Clicked = false;
button1.addEventListener('click',function(e) {
button1Clicked = true;
checkClick();
},false);
button2.addEventListener('click',function(e) {
button2Clicked = true;
checkClick();
},false);
function checkClick() {
if(button1Clicked && button2Clicked) {
result.style.backgroundColor = 'red';
}
}
</script>
Two ways you can do this, one would be to have a data attribute within the html button that identifies whether the click has been done.
<button id="btn">Click Me!</button>
<script>
var clickedAlready = false;
document.getElementById('btn').onclick = function() {
if (clickedAlready) {
//do something...
}
else
clickedAlready = true;
}
</script>
While global variables aren't the best way to handle it, this gives you an idea. Another option would be to store the value in a hidden input, and modify that value to identify if it's the first click or not.
Maybe something like this?
var numberTimesClicked = 0;
function clickHandler() {
if (numberTimesClicked > 0) {
// do something...
}
numberTimesClicked++;
}
document.getElementById("myBtn").addEventListener("click", clickHandler);

Pure JS "If stament depending the number of click"

I was searching for this problem but I didn't find a solution. I'm trying to create a code where when you click a button do one thing, and when you press the same button later do other thing. I tried to create and "if-else" statement but I can't (don't know) how to count the number of clicks.
The code is:
<button type="submit" id="btnshwmap" onClick="init()" >Show Map</button>
And the if-else :
function init() {
var click =0;
if (click === 0) {
do this
var click = 1;
} else {
do this
}
});//end click
Basically I'm trying to use this example Jquery if its the first time element is being clicked
But the answer are using Jquery I'm trying not use any library.
Thanks a lot!
The problem is that you keep on resetting click=0 every time you call the function.
I would suggest something like this:
function init() {
if( !init.click) {
// first, third, fifth etc.
init.click = 1;
]
else {
// second, fourth...
init.click = 0;
}
}
You just need to have the click counter outside the function, in the global area.
var click =0;
function init() {
if (click == 0) {
//do this once
click = 1;
} else {
//do this every other time
}
});//end click
You could try toggling the value set for the button with the click. Something like:
function init() {
var value = document.getElementById('btnshwmap').value;
if (value === 1) {
do this
document.getElementById('btnshwmap').value = 2;
} else {
do this
document.getElementById('btnshwmap').value = 1;
}
});//end click
Or keep a global variable to track the click status, rather than setting it every time you run the function.

Show button if input is not empty

I am not much of a JavaScript guru, so I would need help with a simple code.
I have a button that clears the value of an input field.
I would like it (the button) to be hidden if input field is empty and vice versa (visible if there is text inside the input field).
The solution can be pure JavaScript or jQuery, it doesn't matter. The simpler, the better.
$("input").keyup(function () {
if ($(this).val()) {
$("button").show();
}
else {
$("button").hide();
}
});
$("button").click(function () {
$("input").val('');
$(this).hide();
});
http://jsfiddle.net/SVxbW/
if(!$('input').val()){
$('#button').hide();
}
else {
$('#button').show();
}
In it's simplest form ;)
to do this without jQuery (essentially the same thing others already did, just pure js). It's pretty simple, but I've also added a few comments.
<body>
<input type="text" id="YourTextBox" value="" />
<input type="button" id="YourButton" value="Click Me" />
<script type="text/javascript">
var textBox = null;
var button = null;
var textBox_Change = function(e) {
// just calls the function that sets the visibility
button_SetVisibility();
};
var button_SetVisibility = function() {
// simply check if the visibility is set to 'visible' AND textbox hasn't been filled
// if it's already visibile and the text is blank, hide it
if((button.style.visibility === 'visible') && (textBox.value === '')) {
button.style.visibility = 'hidden';
} else {
// show it otherwise
button.style.visibility = 'visible';
}
};
var button_Click = function(e) {
// absolutely not required, just to add more to the sample
// this will set the textbox to empty and call the function that sets the visibility
textBox.value = '';
button_SetVisibility();
};
// wrap the calls inside anonymous function
(function() {
// define the references for the textbox and button here
textBox = document.getElementById("YourTextBox");
button = document.getElementById("YourButton");
// some browsers start it off with empty, so we force it to be visible, that's why I'll be using only chrome for now on...
if('' === button.style.visibility) { button.style.visibility = 'visible'; }
// assign the event handlers for the change and click event
textBox.onchange = textBox_Change;
button.onclick = button_Click;
// initialize calling the function to set the button visibility
button_SetVisibility();
})();
</script>
</body>​
Note: I've written and tested this in IE9 and Chrome, make sure you test it in other browsers. Also, I've added this fiddle so you can see it working.
You can use $('selector').hide() to hide an element from view and $('selector').show() to display it again.
Even better, you can use $('selector').toggle() to have it show and hide without any custom logic.
First hide the button on page load:
jQuery(document).ready(function() {
jQuery("#myButton").hide();
});
Then attach an onChange handler, which will hide the button whenever the contents of the text-field are empty. Otherwise, it shows the button:
jQuery("#myText").change(function() {
if(this.value.replace(/\s/g, "") === "") {
jQuery("#myButton").hide();
} else {
jQuery("#myButton").show();
}
});
You will also need to hide the button after clearing the input:
jQuery("#myButton").click(function() {
jQuery("#myInput").val("");
jQuery(this).hide();
});

Categories

Resources