Function activate after two onclicks - javascript

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

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>

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.

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

I need help with these two functions

The first one displays the div, the second one hides the dive up on clicking anywhere else in the document. the problem i have is, when i click the button to show the div, it also counts as a document click so it hides the div. how can i it make not hide the div when i click to show the div
<script type="text/javascript">
function test22(){
var links = document.getElementById('links_safari');
if(links.style.display == "none"){
document.getElementById('links_safari').style.display="";
var content = $('#links_safari').html();
var words = content.split(',');
for (var i = 2; i < words.length; i += 3) {
words[i] += '<br>';
}
content = words.join(' ');
$('#links_safari').html(content);
$('#links_safari').css("margin-top", -322);
$('#links_safari').css("margin-left", 180);
safariPopupStatus++;
}
else{
links.style.display="none";
}
}
</script>
<script type="text/javascript">
$(function (){
$(document).click(
function (e){
var links = document.getElementById('links_safari');
links.style.display="none";
}
)
})
</script>
lets suppose the id of your button is showBtn the code now will be
$(document).click(
function (e){
if($(e.target).attr('id')=='showBtn') return
var links = document.getElementById('links_safari');
if(links.style.display != "none") // why not check here ?
links.style.display="none";
}
)
Have a simple check in your "click" function :
<script type="text/javascript">
$(function (){
$(document).click(
function (e){
var links = document.getElementById('links_safari');
if(links.style.display != "none") // why not check here ?
links.style.display="none";
else
links.style.display="";
}
)
})
</script>
You must stop click event propagation.
Check out http://api.jquery.com/event.stopPropagation/
Create a separate click handler for your button. It should look like:
$("#buttonID").click(function(e) {
test22(); // to show
e.stopPropegation();
});
stopPropegation will keep the event from bubbling up to the document level, preventing the handler from being called there.
You can and also probably should put the show code from test22() into your button handler and have the document handler just handle hiding.

Categories

Resources