JS Fiddle: https://jsfiddle.net/k140nad9/6/
HTML Code below:
<input type="checkbox" id="btnA" onchange="openFunctionA();">
FUNCTION A
</input>
<input type="checkbox" id="btnB" onchange="openFunctionB();">
FUNCTION B
</input>
<div id="map">
MAP
</div>
And this JS Code:
var map = document.getElementById('map')
var btnA = document.getElementById('btnA')
var btnB = document.getElementById('btnB')
function openFunctionA() {
if($('#btnA').is(":checked")){
$('#btnB').attr('disabled', true)
map.addEventListener('click', function(e){
alert("THIS FUNCTION A")
})
} else {
$('#btnB').attr('disabled', false)
}
}
function openFunctionB() {
if($('#btnB').is(":checked")){
$('#btnA').attr('disabled', true)
map.addEventListener('click', function(e){
alert("THIS FUNCTION B")
})
} else {
$('#btnA').attr('disabled', false)
}
}
- Click checkbox Function A to check it, but then dont click div map
- Click again checkbox Function A to uncheck it, then click checkbox Function B
- After poin 2, you will get popup "THIS FUNCTION A" first, instead popup "THIS FUNCTION B"
How to fix this, so when I click checkbox Function B (based on point 3 above), I get popup "THIS FUNCTION B" only.
>Solution :
To do what you require, firstly change the checkboxes to input type="radio". this will give you the functionality of only allowing one of them to be selected at a time for free, without the need of any JS logic.
From there, add the click event handler to the #map element instead of the checkboxes. Then you can simply determine which radio is checked and let your logic flow from there.
Also note that you ideally should not be mixing jQuery and plain JS methods, stick to one or the other. As this is a very simple use case I used plain JS only. In addition the <input /> element does not have a closing </input> tag.
Here’s a working example with the above amendments made:
const map = document.querySelector('#map');
const btnA = document.querySelector('#btnA');
const btnB = document.querySelector('#btnB');
map.addEventListener('click', e => {
if (btnA.checked) {
console.log('Function A');
} else if (btnB.checked) {
console.log('Function B');
}
});
#map {
background-color: grey;
height: 300px;
width: 500px;
}
<label>
<input type="radio" name="foo" id="btnA" />
FUNCTION A
</label>
<label>
<input type="radio" name="foo" id="btnB" />
FUNCTION B
</label>
<div id="map">MAP</div>
