Javascript - Perform a function after first clicking on an item and then clicking on another item

1

I have two lists and I wanted you to do that by clicking first on the first list and then on the second one, perform a function to leave both items green.

<p class="question"><span class="mark-question">1.</span> Relacione as fabricantes aos seus veículos</p>
<ul class="first-column">
    <li data-answer="0,5">Ford</li>
    <li data-answer="2">Fiat</li>
    <li data-answer="3">Renault</li>
    <li data-answer="">Ferrari</li>
    <li data-answer="4" id="honda">Honda</li>
    <li data-answer="1">Chevrolet</li>
</ul>

<ul class="second-column">
    <li>Edge</li>
    <li>Ônix</li>
    <li>Palio</li>
    <li>Sandero</li>
    <li id="civic">Civic</li>
    <li>Fusion</li>
    <li>Fusquinha</li>
</ul>
    
asked by anonymous 10.08.2017 / 21:13

1 answer

1

Creates a clicked variable (for example) to save the element already clicked. Then you can make a simple logic to color when you click and the variable already has an element there.

let clicked = null;
const first = document.querySelector('.first-column');
const second = document.querySelector('.second-column');

first.addEventListener('click', clickChecker);
second.addEventListener('click', clickChecker);

function clickChecker(e) {
  const el = e.target;
  if (!clicked) return clicked = el;
  else style(clicked, el);
  clicked = null;
}

function style(a, b) {
  a.style.backgroundColor = b.style.backgroundColor = '#ccf';
}
<p class="question"><span class="mark-question">1.</span> Relacione as fabricantes aos seus veículos</p>
<ul class="first-column">
  <li data-answer="0,5">Ford</li>
  <li data-answer="2">Fiat</li>
  <li data-answer="3">Renault</li>
  <li data-answer="">Ferrari</li>
  <li data-answer="4" id="honda">Honda</li>
  <li data-answer="1">Chevrolet</li>
</ul>

<ul class="second-column">
  <li>Edge</li>
  <li>Ônix</li>
  <li>Palio</li>
  <li>Sandero</li>
  <li id="civic">Civic</li>
  <li>Fusion</li>
  <li>Fusquinha</li>
</ul>
    
10.08.2017 / 21:19