How to output message when 2 buttons have been pressed consecutively - javascript

Hi im new to javascript and messing about with it.
How can i (if possible) show an output when 2 buttons have been pressed one after the other?
Example: click button 1, click button 2, message shows "button 1 and 2 has been clicked"

use an && operator in an if statement.
Javascript:
var button1 = false;
var button2 = false;
var b1_id = document.getElementById('button1');
var b2_id = document.getElementById('button2');
b1_id.addEventListener('click',click1,false);
function click1() {
alert("Button1 clicked");
button1 = true;
check();
}
b2_id.addEventListener('click',click2,false);
function click2() {
alert("Button2 clicked");
if (button1 !== false) button2 = true; //this is to make sure they are clicked consecutivley
check();
}
function check() {
if (button1 === true && button2 === true) {
alert("Button1 and Button2 clicked consecutively");
}
}
HTML:
<input type='button' id='button1' value='button1' />
<input type='button' id='button2' value='button2' />
​jsFiddle

<p id="status"></p>
<button id="btn1" onclick="clickfun(this);">button 1</button>
<button id="btn2" onclick="clickfun(this);">button 2</button>
<script>
clickfun(elm){
var currenthtml = document.getElementById('status').innerHTML;
document.getElementById('status').innerHTML = currenthtml += this.id+' clicked !';
}
</script>

I actually just wrote a library devoted to the mouse object. One thing it does it tracking what buttons are pressed, and follows DOM3 spec mostly.
https://github.com/Benvie/Mouse
Boiled down to minimum, you must continually track the muse to now if the browser does not provide the "buttons" property, which only Firefox 15 does so far. Specially, mousedown to start, then click and contextmenu to end.
The key bits for tracking buttons are
var buttons = 0;
function down(e){ buttons |= 1 << e.button; }
function up(e){ buttons &= ~(1 << e.button); }
window.addEventListener('click', up);
window.addEventListener('contextmenu', up);
window.addEventListener('mousedown', down);

Related

Make div appear when enter is pressed

I have a input where a user can input text and when the user presses enter on their keyboard, it will click the button 'Go!' which should then make the 'Create Div' button appear. And a div is created with the user's inputted text, when they click the 'Create Div' button. But I want this button to be clicked also when the user presses enter. Thus when the user presses 'Enter' the first time, it will click the 'Go!' button which will make the 'Create Div' button appear and then when the user presses 'Enter' the second time ( or preferably when the 'Create Div' button is shown on the screen) then the actual div will be created with the user's inputted text.
I tried doing this in Javascript, by using an IF statement but right now when I press 'Enter' the first time to trigger the 'Go!' button, it automatically triggers the 'Create Div' button and the div appears right after the first 'Enter' is pressed (uncomment the last bit of my JS code to see what I mean) What should I change to get my desired result?
var button = document.getElementById("button");
var createbutton = document.createElement("button");
var creatediv = document.createElement("div");
button.addEventListener('click', function(){
createbutton.innerHTML = "Create Div";
createbutton.style.display = 'inline-block';
document.getElementById("body").appendChild(createbutton);
});
createbutton.addEventListener('click', function(){
createbutton.style.display = 'none';
var input = document.getElementById("input").value;
creatediv.innerHTML = input;
document.getElementById("body").appendChild(creatediv);
});
document.onkeydown = function(event){
if(event.keyCode == 13){
button.click();
}
}
/*if(createbutton.style.display = 'inline-block'){
document.onkeydown = function(event){
if(event.keyCode == 13){
createbutton.click();
}
}
}*/
<body id="body">
<input type="text" id="input" placeholder="Text goes here">
<button id="button">Go!</button>
</body>
You can give your createbuttonand ID and check if the element is inside the DOM
when enter is pressed:
var button = document.getElementById("button");
var createbutton = document.createElement("button");
var creatediv = document.createElement("div");
button.addEventListener('click', function(){
createbutton.innerHTML = "Create Div";
createbutton.style.display = 'inline-block';
createbutton.id = 'createButton';
document.getElementById("body").appendChild(createbutton);
});
createbutton.addEventListener('click', function(){
createbutton.style.display = 'none';
var input = document.getElementById("input").value;
creatediv.innerHTML = input;
document.getElementById("body").appendChild(creatediv);
});
document.onkeydown = function(event){
if(event.keyCode === 13) {
if(document.getElementById('createButton')) {
createbutton.click();
} else {
button.click();
}
}
}
<body id="body">
<input type="text" id="input" placeholder="Text goes here">
<button id="button">Go!</button>
</body>

Expande button until status change

I use an automation testing tool (selenium)
I try to test a page which has this button:
<button morearea-controllers="my-list" morearea-expanded="false" class="lpw-reach-text-more link">
As a user, when I press show more it shows the "show more content". And when there is no more to show, the morearea-expanded becomes true.
Is there any JavaScript command which could expand the button until the end (until morearea-expanded becomes true)?
Somehting very general I tried as I found it is from the full button list which I found the list and after that the number of button (but this number is not the same in every page I try to test):
document.querySelectorAll('button')
is this:
document.getElementsByTagName('button')[29].click()
You can keep invoking the click event in a while loop until the attribute value is "true". Sample using jQuery (function named automationFunction()):
$(document).ready(function() {
var count = 0,
$button = $("[morearea-controllers='my-list']");
/* bad code alert - just for sample purpose */
$button.click(function() {
if (count == 5) {
return;
} else {
if (count === 4) {
$(this).attr("morearea-expanded", true);
$(this).val("Show Less");
}
$("#container").append((count + 1) + "<br/>");
count++;
}
});
/* automation function */
$("#btn-automate").click(function() {
automationFunction();
});
var automationFunction = function() {
count = 0;
while ($button.attr("morearea-expanded") === "false") {
$button.click();
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
Five items hidden..click on show more to unhide
<div id="container"></div>
</div>
<input type="button" id="btn-show-more" morearea-controllers="my-list" morearea-expanded="false" class="lpw-reach-text-more link" value="Show More"> <br/>
<input type="button" id="btn-automate" value="Invoke automation function">

Disabling a button in vanilla JavaScript and in jQuery

Vanilla JavaScript
In vanilla JavaScript, one can easily enable and disable a button using the following statement:
button.disabled = state;
This works both when humans try to click a button and when buttons are clicked programmatically:
var button = document.getElementById('myButton');
button.addEventListener('click', function() {
alert('world');
});
button.disabled = true;
button.click(); // No output
button.disabled = false;
button.click(); // Output : "Hello" and "world
button.disabled = true;
button.click(); // No output
<input type="button" id="myButton" value="button" onClick="alert('Hello')"/>
This also works when using the MouseEvent interface:
var button = document.getElementById('myButton');
var click = new MouseEvent("click", {
"view": window
});
button.addEventListener('click', function() {
alert('world');
});
button.disabled = true;
button.dispatchEvent(click); // No output
button.disabled = false;
button.dispatchEvent(click); // Output : "Hello" and "world
button.disabled = true;
button.dispatchEvent(click); // No output
<input type="button" id="myButton" value="button" onClick="alert('Hello')"/>
jQuery
I can't seem to be able to do the same with jQuery, though :
var button = $("#myButton");
button.on("click", function() {
alert("world");
});
button.prop("disabled", true);
button.click(); // Output : "world" and "Hello"
button.prop("disabled", false);
button.click(); // Output : "world" and "Hello"
button.prop("disabled", true);
button.click(); // Output : "world" and "Hello"
<script src="https://code.jquery.com/jquery-1.12.2.min.js"></script>
<input type="button" id="myButton" value="button" onClick="alert('Hello')"/>
Both button.prop("disabled", true); and button.attr("disabled", true); simply change the disabled property of the button element, but neither disables the actual click event. This means that events are triggered whenever button.click(); is called, even if the button is disabled!
Additionally, "world" and "Hello" are output in the wrong order.
The simplest code I could come up with to emulate the behavior of the vanilla JavaScript versions, is this :
var button = $("#myButton");
button.on("click", function() {
alert("world");
});
button.disable = (function() {
var onclick = null;
var click = [];
return function(state) {
if(state) {
this.prop('disabled', true);
if(this.prop('onclick') !== null) {
onclick = this.prop('onclick');
this.prop('onclick', null);
}
var listeners = $._data(this.get()[0], "events");
listeners = typeof listeners === 'undefined' ? [] : listeners['click'];
if(listeners && listeners.length > 0) {
for(var i = 0; i < listeners.length; i++) {
click.push(listeners[i].handler);
}
this.off('click');
}
} else {
this.removeProp('disabled');
if(onclick !== null) {
this.prop('onclick', onclick);
onclick = null;
}
if(click.length > 0) {
this.off('click');
for(var i = 0; i < click.length; i++) {
this.on("click", click[i]);
}
click = [];
}
}
}
})();
button.disable(true);
button.click(); // No output
button.disable(false);
button.click(); // Output : "Hello" and "world
button.disable(true);
button.click(); // No output
<script src="https://code.jquery.com/jquery-1.12.2.min.js"></script>
<input type="button" id="myButton" value="button" onClick="alert('Hello')"/>
That is, of course, ridiculously convoluted and "hacky" code to achieve something as simple as disabling a button.
My questions
Why is it that jQuery - unlike vanilla JS - doesn't disable the events when disabling a button?
Is this to be considered a bug or a feature in jQuery?
Is there something I'm overlooking?
Is there a simpler way to get the expected behavior in jQuery?
To achieve expected result, you can utilize .isTrigger within jQuery triggered click handler to determine if event is triggered by javascript, and not user action.
Define attribute event listener as a named function, where this can be passed to check disabled property at if condition if alert() is called, or not called.
Use .attr("disabled", "disabled") to set disabled at element, .removeAttr("disabled") to remove attribute; .attr("onclick", null) to remove event attribute onclick handler; .attr("onclick", "handleClick(true)") to reset event attribute.
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<input type="button" id="myButton" value="button" onclick="handleClick(this)" />
<script>
function handleClick(el) {
if (el.disabled !== "disabled")
alert("Hello")
}
var button = $("#myButton");
button.on("click", function(e) {
console.log(e);
if (e.isTrigger !== 3 && !e.target.disabled)
alert("world");
});
button.attr("disabled", "disabled");
button.attr("onclick", null);
button.click(); // no output
setTimeout(function() {
button.removeAttr("disabled");
button.attr("onclick", "handleClick(button[0])");
button.click(); // Output : "world" and "Hello"
// click button during 9000 between `setTimeout` calls
// to call both jQuery event and event attribute
}, 1000);
setTimeout(function() {
button.attr("disabled", "disabled");
button.attr("onclick", null);
button.click(); // no output
}, 10000);
</script>
If you take a look to jquery-1.12.4.js at these lines:
handlers: function( event, handlers ) {
var i, matches, sel, handleObj,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Support (at least): Chrome, IE9
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
//
// Support: Firefox<=42+
// Avoid non-left-click in FF but don't block IE radio events (#3861, gh-2343)
if ( delegateCount && cur.nodeType &&
( event.type !== "click" || isNaN( event.button ) || event.button < 1 ) ) {
/* jshint eqeqeq: false */
for ( ; cur != this; cur = cur.parentNode || this ) {
/* jshint eqeqeq: true */
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && ( cur.disabled !== true || event.type !== "click" ) ) {
You will you see a different handling of events according to the delegation type:
$(document).on("click", '#btn', function() {
console.log("world");
});
$(function () {
$('#btnToggle').on('click', function(e) {
$('#btn').prop('disabled', !$('#btn').prop('disabled'));
});
$('#btnTestClick').on('click', function(e) {
$('#btn').click();
});
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<button id="btn">Click Me</button>
<button id="btnToggle">Enable/Disable button</button>
<button id="btnTestClick">Test Click</button>
Of course, if you attach the event like in:
$('#btn').on("click", function() {
alert("world");
});
The behaviour is different and seems strange.
Using .prop() is the right way to do it. I think the issue is in the way that you are "testing" it. See this example where the buttons are disabled/enabled correctly using the toggle button regardless of whether the handler is attached via onclick or with jquery.
window.testFunc = function(event) {
if (!$('#myButton2').prop('disabled')) {
alert("hello");
console.log("hello");
}
}
$(document).ready(function() {
var button = $("#myButton2");
button.on("click", function(event) {
if (!$(this).prop('disabled')) {
alert("world");
console.log("world");
}
});
$('#toggleButton').click(function() {
$('#myButton1').prop('disabled', !$('#myButton1').prop('disabled'));
$('#myButton2').prop('disabled', !$('#myButton2').prop('disabled'));
});
$('#tester').click(function() {
$('#myButton1').click();
$('#myButton2').click();
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="myButton1" value="vanilla button (hello)" onclick="window.testFunc(event)"/>
<input type="button" id="myButton2" value="jquery button (world)"/>
<input type="button" id="toggleButton" value="toggle disabled"/>
<input type="button" id="tester" value="test the buttons"/>
The other obvious solution is to just use vanilla javascript. Just because you are using jQuery doesn't mean that everything "must" be done using it. There are some things that are fine to do without jQuery.
EDIT: I edited the snippet showing how you could prevent jquery's .click() from actually triggering the alerts.
You're calling the click function directly 3 times ( button.click() ) which fires regardless of disabled attribute.
The disabled property only responds to click events.
See the updated example:
var button = $("#myButton");
var button2 = $("#myButton2");
button.prop("disabled", false);
button.on("click", function() {
alert("world");
button2.prop("disabled", false);
});
button2.prop("disabled", true);
button2.on("click", function() {
alert("world");
button.prop("disabled", true);
});
<script src="https://code.jquery.com/jquery-1.12.2.min.js"></script>
<input type="button" id="myButton" value="button" onClick="alert('Hello')"/>
<input type="button" id="myButton2" value="button2" />

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

Javascript - how to make true after clicking 2 buttons

I have 3 buttons.
Button #1 and Button #2 and Button #3
After they have clicked #1 and #2, button #3 will activate and they can click on it.
Thank you so much.
This is what I have done so far:
var l50K_WC = false;
var l6OK_WC = false;
function share()
{
alert('yo');
}
function getIt_wc()
{
if(l5OK_WC && l6OK_WC)
window.open('http://websitehere.ca','_self');
if(!l5OK_WC)
alert("Click Button #1)");
else if(!l6OK_WC)
alert("Click Button #2)");
}
This displays the message, but how do I finish the rest where they have to click the 2 buttons before continuing? thanks.
You need to set the values for the both other buttons to true:
var l50K_WC = false;
var l6OK_WC = false;
function click1(){
150K_WC = true;
}
function click2(){
160K_WC = true;
}
function share()
{
alert('yo');
}
function getIt_wc()
{
if(l5OK_WC && l6OK_WC)
window.open('http://websitehere.ca','_self');
if(!l5OK_WC)
alert("Click Button #1)");
else if(!l6OK_WC)
alert("Click Button #2)");
}
And then in the html Code:
<input type="button" value="150KWC" onclick="click1()">
<input type="button" value="160KWC" onclick="click2()">
<input type="button" value="Final Button" onclick="getIt_wc()">
//Javascript
var button1Clicked = false;
var button2Clicked = false;
if (button1Clicked && button2Clicked) {
document.writeln("<button>Button 3</button>");
}
<!--HTML-->
<button onclick="javascript:button1Clicked=true;">Button 1</button>
<button onclick="javascript:button2Clicked=true;">Button 2</button>

Categories

Resources