JS onLoad not working in Randomizer | XM Community
Solved

JS onLoad not working in Randomizer

  • 10 January 2020
  • 1 reply
  • 18 views

Hi all,

I wrote a bit of JS and put it in the addOnLoad part, for multiple blocks. It works beautifully. However, I noticed that as soon as I have a Randomizer in my Survey Flow, with say 9 blocks, the onLoad JS only works for the first block.

Since it's randomised, it's clear that it doesn't have anything to do with the block: every time I run it, it (obviously) presents the blocks in random order, and whatever block is presented first, the onLoad JS works, but for the subsequent blocks it doesn't. The JS is identical across blocks. Having a simple `window.alert("hello world");` in onLoad does show, but not my code:

```
/* function to find element based on textContent */
function contains(selector, text) {
var elements = document.querySelectorAll(selector);
return Array.prototype.filter.call(elements, function(element){
return RegExp(text).test(element.textContent);
});
}

/* set "unableToRate" id to unable-to-rate button (also for CSS) */
contains('td', 'Unable to rate')[0].setAttribute("id", "unableToRate");

/* move "unableToRate" button */
document.getElementsByClassName('ChoiceStructure')[0].appendChild ( document.getElementById("unableToRate") );
```

I thought it has something to do with the elements not having been loaded yet, so not being available. But that doesn't explain why it *does* work for the first block.

Anyone any idea what can be happening here? I tried to publish the survey and look at it then, but same problem.

Thanks!
icon

Best answer by MattC 12 January 2020, 15:12

View original

1 reply

Okay so it turns out that onLoad *is* working normally, but that Qualtrics -- when in a Randomizer block -- loads 2 questions: the previous one, in case people want to go back (I assume), and then the current one. So my script was targeting the previous question always (`contains('td', 'Unable to rate')` had a length of 2 instead of 1)

Leave a Reply