sgfp
sgfp

Reputation: 13

Make certain bills stand out based on their topic by greying out surrounding bills

So, let's say there are four pieces of legislation coming up involving either education, contraception, or LGBTQ rights. In order to more easily inform people about the content of these bills, I want to highlight them based on their primary topic or issue. Each issue has a button and clicking the Education button should make the bills unrelated to education fade, etc.

One of the bills involves both education and contraception, so it should fade out if all three buttons are clicked or if only the LGBTQ button is clicked.

Here is my code, which works fine for the single-issue bills, but not if the user tries to select multiple issues.

<div class=buttons>
<button id="edu_button" onclick="colorchange('edu_button')" style="background:black; color:white;" issue="education">Education</button>
<button id="ca_button" onclick="colorchange('ca_button')" style="background:black; color:white;" issue="contraception">Contraception</button>
<button id="lgbtq_button" onclick="colorchange('lgbtq_button')" style="background:black; color:white;" issue="lgbtq">LGBTQ</button>
</div>
<br/>
<div class="bill" issue="education">HB 101 (Education bill)</div>
<div class="bill" issue="contraception">HB 102 (Contraception bill)</div>
<div class="bill" issue="lgbtq">HB 103 (LGBTQ bill)</div>
<div class="bill" issue="education contraception">HB 104 (Bill that involves education and contraception)</div>

  function colorchange(id) {

    var background = document.getElementById(id).style.backgroundColor;
    if (background == "black") {
        document.getElementById(id).style.background = "#ec0d7d";
    } else {
        document.getElementById(id).style.background = "black";
    }

}


const buttons = document.querySelectorAll('.buttons');
  const bills = document.querySelectorAll('.bill');

   const hide = function(evt){
    bills.forEach(function(d){
       if(evt.target.getAttribute('issue') != d.getAttribute('issue')) d.classList.toggle('fade');

    });
  }

  buttons.forEach(function(d){ 
    d.onclick = hide; 
  })



.fade{
   opacity: 0.2;
}

http://jsfiddle.net/96ohjm5d/3/

Upvotes: 1

Views: 48

Answers (1)

Brett Donald
Brett Donald

Reputation: 14432

In your hide function, you’re looping through the bills, but for each bill you need to get an array of the issues associated with the bill (try splitting on a space like this: const issueArray = d.getAttribute('issue').split(' ')) and use a nested loop to check each issue against the buttons which are highlighted. Your code only checks the button which was just pushed (evt.target) and ignores whether it was just highlighted or un-highlighted.

Note also that you’re attaching two separate event handlers to each button: colorchange and hide. This works, but you might get less confused if you just used a single event handler for each button to do all the necessary tasks.

Upvotes: 1

Related Questions