Pure JS "If stament depending the number of click" - javascript

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.

Related

With javascript, how do you simply express a number of iterations?

For example, say I want a block of code to run after a certain event occurs a certain amount of times (let's suppose a button is pressed in the following example). Would I use something similar to an if statement such as the following:
if( //certain event occurs: document.getElementById('btn').clicked == true 5 times
) {
//block of code to run if button is clicked 5 times: output in p element
}
<button id="btn" type="button">click</button>
<p></p>
If there's a more practical way than an if statement, I'd like know, please, and thanks. However, if an if statement is the way to go (unless of course there's a more practical method), how would you have a block of code run after a certain event occurs per specified increment of times? Utilizing the html elemenets above:
var alpha = 0;
function addition() {
alpha = alpha + 1;
return alpha;
}
document.getElementById('btn').addEventListener('click', 'get_addition');
function get_addition() {
document.getElementsByTagName('P')[0].innerHTML = addition();
if( //document.getElementById('btn').clicked == true per 5 times
) {
//block of code to run per 5 button clicks outputted in p element;
//then return to outputting values in p element rendered by addition() until next 5th iteration;
}
}
You can use data attributes with modulus operator to keep track of the clicks.
function get_addition () {
this.dataset.clicked = this.dataset.clicked || 0
this.dataset.clicked++
if (this.dataset.clicked%5===0) {
this.classList.add("green");
} else {
this.classList.remove("green");
}
}
document.getElementById('btn').addEventListener('click', get_addition);
.green {
background-color: green;
}
<button id="btn">Click</button>
You have a global variable, alpha, which counts how many times the button was clicked. Seems like you can just test whether alpha is a multiple of 5 and execute your special code then (within your get_addition function, after incrementing alpha).
if (alpha % 5 == 0) {
alert("5 clicks");
} else {
// regular code
}
This answer is pretty much the same as #James', but I have provided a self-contained snippet. The idea is the same -- increment a global, and use modulus to check for multiples.
let count = 0;
let btn = document.getElementById("b");
btn.addEventListener("click", function() {
count++;
if (count % 3 == 0) {
alert("You see this once every three clicks");
}
});
<button id="b">Click me 3 times</button>
The best way is to track the number of clicks, increment each time. When you reach 5 you can execute your code & reset the counter.
var counter = 0;
document.getElementById('btn').addEventListener('click', function(){
counter ++;
if(counter == 5)
{
counter = 0;
//this code executed after 5 clicks
}
//this code executed every click
});

calling two js functions one after another using one button

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.

If statement does not work when condition is met

Here is my code:
var count = 2;
var decrementAmount = 1;
function reduceVariable() {
count -= decrementAmount;
}
$("#button").click(function() {
reduceVariable();
});
if (count == 0) {
$("#avrageReactionTime").html("Hello");
};
When i click my button twice the div that has the id avrageReactionTime does not change to have the text hello. Why do i have this problem...
Right now you test once, instead of testing every time the counter changes.
You must put the if inside the event handler :
$("#button").click(function() {
reduceVariable();
if (count==0) {
$("#avrageReactionTime").html("Hello");
}
});
Note that properly indenting your code makes it obvious.

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

IE7 issues with my jQuery [click and change functions]

I have the following snippets of code. Basically what I'm trying to do is in the 1st click function I loop through my cached JSON data and display any values that exist for that id. In the 2nd change function I capturing whenever one of the elements changes values (i.e. yes to no and vice versa).
These elements are all generated dynamically though the JSON data I'm receiving from a webservice. From my understanding that is why I have to use the .live functionality.
In Firefox everything works as expected (of course). However, in IE7 it does not. In IE7, if I select a radio button that displays an alert from the click function then it also adds to the array for the changed function. However, if the radio button does not do anything from the click function then the array is not added to for the change.
As I look at this code I'm thinking that I might be able to combine these 2 functions together however, right now I just want it to work in IE7.
$(document).ready(function () {
//This function is run whenever a 'radio button' is selected.
//It then goes into the CPItemMetaInfoList in the cached JSON data
//($.myglobals) and checks to see if there are currently any
//scripts to display.
$("input:radio").live("click", function () {
var index = parseInt(this.name.split(':')[0]);
for (i = 0; i <= $.myglobals.result.length - 1; i++) {
if ($.myglobals.result[i].CPItemMetaInfoList.length > 0) {
for (j = 0; j <= $.myglobals.result[i].CPItemMetaInfoList.length - 1; j++) {
if (index == $.myglobals.result[i].QuestionId) {
alert($.myglobals.result[i].CPItemMetaInfoList[j].KeyStringValue);
return;
}
}
}
}
});
});
$(document).ready(function () {
var blnCheck = false;
//Checks to see if values have changed.
//If a value has been changed then the isDirty array gets populated.
//This array is used when the questionSubmit button is clickeds
$('input').live('change', function () {
blnCheck = false;
for (i = 0; i <= isDirty.length - 1; i++) {
if (isDirty[i] == $(this).attr("name")) {
blnCheck = true;
break
}
}
if (blnCheck == false) {
isDirty[arrayCount] = $(this).attr("name");
arrayCount += 1;
alert($(this).attr("name"));
}
});
$('textarea').live('change', function () {
blnCheck = false;
for (i = 0; i <= isDirty.length - 1; i++) {
if (isDirty[i] == $(this).attr("id")) {
blnCheck = true;
break
}
}
if (blnCheck == false) {
isDirty[arrayCount] = $(this).attr("id");
arrayCount += 1;
//alert($(this).attr("name"));
}
});
});
UPDATE:
I had to move this chunk of code into the click function:
blnCheck = false;
for (i = 0; i <= isDirty.length - 1; i++) {
if (isDirty[i] == $(this).attr("name")) {
blnCheck = true;
break
}
}
if (blnCheck == false) {
isDirty[arrayCount] = $(this).attr("name");
arrayCount += 1;
alert($(this).attr("name"));
}
Like this:
$(document).ready(function () {
//This function is run whenever a 'radio button' is selected.
//It then goes into the CPItemMetaInfoList in the cached JSON data
//($.myglobals) and checks to see if there are currently any
//scripts to display.
$("input:radio").live("click", function () {
var index = parseInt(this.name.split(':')[0]);
for (i = 0; i <= $.myglobals.result.length - 1; i++) {
if ($.myglobals.result[i].CPItemMetaInfoList.length > 0) {
for (j = 0; j <= $.myglobals.result[i].CPItemMetaInfoList.length - 1; j++) {
if (index == $.myglobals.result[i].QuestionId) {
alert($.myglobals.result[i].CPItemMetaInfoList[j].KeyStringValue);
return;
}
}
}
}
blnCheck = false;
for (i = 0; i <= isDirty.length - 1; i++) {
if (isDirty[i] == $(this).attr("name")) {
blnCheck = true;
break
}
}
if (blnCheck == false) {
isDirty[arrayCount] = $(this).attr("name");
arrayCount += 1;
}
});
});
But...
I had to leave the change function the same. From my testing I found that the .click function worked for IE7 for the radio buttons and checkbox elements, but the .change functionality worked for the textboxes and textareas in IE7 and FF as well as the original functionality of the radio buttons and checkbox elements.
This one got real messy. Thanks to #Patricia for looking at it. Here suggestions did lead me to this solution. I'm going to leave the question unanswered as I wonder if there isn't a cleaner solution to this.
Fact: change event on radio buttons and checkboxes only get fired when the focus is lost (i.e. when the blur event is about to occur). To achieve the "expected" behaviour, you really want to hook on the click event instead.
You basically want to change
$('input').live('change', function() {
// Code.
});
to
$('input:radio').live('click', functionName);
$('input:not(:radio)').live('change', functionName);
function functionName() {
// Code.
}
(I'd however also take checkboxes into account using :checkbox selector for the case that you have any in your form, you'd like to treat them equally as radiobuttons)
I think this is because IE fires the change when focus is lost on checks and radios. so if the alert is popping up, focus is being lost and therefor the change event is firing.
EDIT:
try changing the $('input') selector to $('input:not(:radio)')
so the click will fire for your radios and the change for all your others.
Edit #2:
How bout putting the stuff that happens on change into a separate function. with the index as a parameter. then you can call that function from the change() and the click(). put the call to that function after your done with the click stuff.
You're declaring your blnCheck variable inside one of your document.ready() functions. You don't need two of these either, it could all be in one.
This means that the variable that you're declaring there won't be the one used when your change function is actually called, instead you're going to get some kind of implicit global. Don't know if this is part of it, but might be worth looking at. You should declare this at the top of your JS file instead.

Categories

Resources