Pearu Pearu - 9 months ago 36
Javascript Question

How do I prevent a javascript function from running when a DOM element from an array is already selected?

I have a script that makes gives me a dynamic header depending on which bubble in an array is currently selected. However, when a bubble is already selected and the user clicks on that same bubble, I can't stop the js function from running and it changes the opacity of the header to 0 temporarily. In this case I'd like for the opacity of the header to remain as 1. This seems rather simple but I can't figure it out. The code on CodePen.


<div id="bubbles">
<div onclick="bubbles(0); clearInterval(intrvl);" style="background:#da2225;"></div>
<div onclick="bubbles(1); clearInterval(intrvl);"></div>
<div onclick="bubbles(2); clearInterval(intrvl);"></div>
<div id="bubblecontent">
<h2>Header 1</h2>


function _(x){return document.getElementById(x);}

var ba, bi=0, intrvl;
var bca = [
'<h2>Header 1</h2>',
'<h2>Header 2</h2>',
'<h2>Header 3</h2>',

function bubbles(bi){
_("bubblecontent").style.opacity = 0;
for(var i=0; i < ba.length; i++){
ba[i].style.background = "#ccc";
ba[bi].style.background = "#da2225";
_("bubblecontent").innerHTML = bca[bi];
_("bubblecontent").style.opacity = 1;
}, 300);

window.addEventListener("load", function(){
ba = _("bubbles").children;


In function bubbles, add conditional if the bi is the same as previous one:

var prev = -1;

function bubbles(bi){
   if (bi != prev){
//           put the rest of your bubbles(bi) code put here
   prev = bi;