PennController for IBEX › Forums › Support › Javascript in HTML Files
- This topic has 3 replies, 2 voices, and was last updated 2 years, 4 months ago by Cascade.
-
AuthorPosts
-
April 19, 2022 at 12:43 pm #8080CascadeParticipant
I’m trying to use HTML files in which javascript within the <head> tag creates line numbers of text appearing in the body (see code below). When I open the HTML file in a web browser, it seems to work fine; however, when I upload it to the experiment on PC Ibex Farm, the javascript doesn’t seem to work. The text of the HTML file is there, but the line numbers are all gone. Is it not possible to use javascript in HTML files for PC Ibex or is there something I need to do in order to enable it?
Best,
Jack<script type="text/javascript"> window.addEventListener('load', function () { var div = document.getElementsByTagName('div')[0]; var lines = div.innerText.split('\n'); div.innerText = ''; for (var l = 0; l < lines.length; l++) { var line = lines[l]; if (line.length == 0) { continue; } var span = document.createElement('span'); next = (l < lines.length - 1) ? lines[l+1] : ''; if (next.length > 0) { span.className = 'line'; } else { span.className = 'line end-of-paragraph'; } span.innerText = line; div.appendChild(span); div.appendChild(document.createTextNode('\n')); } }, false); </script>
April 19, 2022 at 12:48 pm #8081CascadeParticipantIf it helps, I’ve tried using both the Form & Message controller for the HTML item and it doesn’t seem to make a difference.
April 19, 2022 at 6:44 pm #8082JeremyKeymasterHi Jack,
When the content of your HTML file is injected in the experiment, its first
div
element is not the firstdiv
in the document, unlike when you open the file separately in your browserYou could instead mark the elements whose lines you want to number (in particular, the
div
element you target) by giving it a specific class (eg.numberTheLines
):<script type="text/javascript"> window.addEventListener("load", ()=>{ var toNumber = document.querySelectorAll('.numberTheLines'); console.log("toNumber", toNumber); toNumber.forEach( el => { var lines = el.innerText.split('\n'); console.log("lines", lines); el.innerText = ''; for (var l = 0; l < lines.length; l++) { var line = lines[l]; if (line.length == 0) { continue; } var span = document.createElement('span'); next = (l < lines.length - 1) ? lines[l+1] : ''; if (next.length > 0) { span.className = 'line'; } else { span.className = 'line end-of-paragraph'; } span.innerText = line; el.appendChild(span); el.appendChild(document.createTextNode('\n')); } }); }) </script>
Jeremy
April 20, 2022 at 11:41 am #8087CascadeParticipantThanks, Jeremy – that helps a lot!
-
AuthorPosts
- You must be logged in to reply to this topic.