user1500702
user1500702

Reputation: 1

How to output message when 2 buttons have been pressed consecutively

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"

Upvotes: 0

Views: 765

Answers (3)

user748221
user748221

Reputation:

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

Upvotes: 0

Polyov
Polyov

Reputation: 2311

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

Upvotes: 1

coolguy
coolguy

Reputation: 7954

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

Upvotes: 0

Related Questions