0

I'm trying to randomly choose one div out of a group and assign a click event to just the selected one. Below is the code I wrote thus far.

<div id="div1"> </div>
<div id="div2"> </div>
<div id="div3"> </div>
<div id="div4"> </div>

<script>

var div1 = document.getElementById("div1");
var div2 = document.getElementById("div2");
var div3 = document.getElementById("div3");
var div4 = document.getElementById("div4");



var randomnumber = Math.floor(Math.random() * (4 - 1 + 1)) + 1;

var bomb = "div" + randomnumber;


alert(bomb);

bomb.onclick = function() { alert("You clicked me...BOOM!")}; // does not work


</script>
William
  • 4,422
  • 17
  • 55
  • 108
  • (4 - 1 + 1) is a bit superfluous - why not just (4)? – JohnLBevan Oct 28 '12 at 14:47
  • This is where I got that from. There is a full explanation in the accepted answer: http://stackoverflow.com/questions/1527803/generating-random-numbers-in-javascript-in-a-specific-range – William Oct 28 '12 at 15:01
  • Ah ok - in the example they're showing a generic way to generate a random number within a range. If you're using fixed values (i.e. these max and mins don't change at runtime) it's best to stick in the actual numbers - I expect you won't get any difference in performance as most compilers would optimise this anyway, but it makes the code a bit cleaner & easier to understand. – JohnLBevan Oct 28 '12 at 15:08

2 Answers2

2

You're setting the onclick property of the string bomb, not the element.

Use

document.getElementById(bomb).onclick = function() { alert("You clicked me...BOOM!")};

You may also use addEventListener if you don't want to replace existing click listeners :

document.getElementById(bomb).addEventListener(function() {
   alert("You clicked me...BOOM!")
});
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • The 'onclick' property shouldn't be used yet that's what the OP uses. Upvoted. – John Dvorak Oct 28 '12 at 14:30
  • I know , but I wasn't sure how to "convert it". I guess I should also ask how to make this an "eventListener" instead per dystroy's comment – William Oct 28 '12 at 14:32
0

If that is your actual script try this:

var bomb = window['div' + randomnumber].onclick = function(){alert('You clicked me... BOOM!');};

If this isn't the actual script, just replace window[ with this[, to reference whatever the current context is.

Of course, @dystroy's approach works just fine, too. I just added this to show you a way to reference a variable, using a string

Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149