layerburn layerburn -4 years ago 149
jQuery Question

jQuery - How to use a single function to set global variables to true by detecting div id clicked?

I'm trying to use a single function to detect which div was clicked and then set the corresponding variable to true. So if I clicked ID "click1", then I would like to set VAR "click1_view" to true.

I'm having trouble getting the variable within the function to evaluate, what am I missing? I'm fairly new to jQuery. In action script it would have simply been eval(thisViewed) = true; but that does not work here. Any guidance would be greatly appreciated.

<div class="circle" id="click1">1</div>
<div class="circle" id="click2">2</div>
<div class="circle" id="click3">3</div>
<div class="circle" id="click4">4</div>
<div class="circle" id="click5">5</div>

<script>
var click1_view = false;
var click2_view = false;
var click3_view = false;
var click4_view = false;
var click5_view = false;

function showContent(){
var thisBtn = $(this).attr('id');
var thisViewed = thisBtn + "_view";

thisViewed = true;

console.log(click1_view);
}

$('#click1').click(showContent);
$('#click2').click(showContent);
$('#click3').click(showContent);
$('#click4').click(showContent);
$('#click5').click(showContent);
</script>

Answer Source

Use a object to persist which element is viewed and Bracket notation to set the set property using variable.

Additionally as you have added a common class to element use it to attach event handlers

var obj = {
  click1_view: false,
  click2_view: false,
  click3_view: false,
  click4_view: false,
  click5_view: false
}

function showContent() {
  var thisBtn = $(this).attr('id');
  var thisViewed = thisBtn + "_view";
  //Use bracket notation to set the property value
  obj[thisViewed] = true;
  console.clear();
  console.log(obj);
}

$('.circle').click(showContent);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="circle" id="click1">1</div>
<div class="circle" id="click2">2</div>
<div class="circle" id="click3">3</div>
<div class="circle" id="click4">4</div>
<div class="circle" id="click5">5</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download