Adding an event listener to a widget is giving me an error

Adding an event listener to a widget is giving me an error

  

Could just be making a silly mistake but I've added a listener to an element:

var el = document.getElementById("element");
  el.addEventListener("touchstart", function);

It is giving me this error:

Uncaught TypeError: Cannot read property 'addEventListener' of null

Do I need to wrap the declaration in some sort of if statement so that it waits for the elements to be loaded first?

Hello James,

I can think of two reasons for the error.

1. You are trying to bind the event before the browser rendered the element.

2. You are passing a wrong Id and the element was not found.

In OutSystems, the IDs are dynamically given. So, you need give a name to the element in order to have access to its Id, and pass the id to the script using the form ElementName.Id. or find the element using a different attribute, like a class.

Hope this help you.

Cheers,

Eduardo Jauch

The element identifiers are generated by outsystems.

Can you share the full js code including how you implemented the identifier? Just using "element" won't work. 

Kind regards,

Remco Dekkinga

Remco Dekkinga wrote:

The element identifiers are generated by outsystems.

Can you share the full js code including how you implemented the identifier? Just using "element" won't work. 

Kind regards,

Remco Dekkinga

Sorry for the delay


SyntaxEditor Code Snippet

var $navbar = $('#navbar');

function fixFixedPosition() {
  $navbar.css({
    position: 'absolute',
    top: document.body.scrollTop + 'px'
  });
}

var el = document.getElementById("SchoolNameSelect2.Id");
  el.addEventListener("touchstart", fixFixedPosition);


Solution

Hi James,

You are not using the correct values for the GetElementById('') functions.

  1. First you should create parameters in the javascript block for the WidgetIdentifiers.
  2. Then you need to create input parameters in the client action for all the javascript parameters.
  3. Assign the input parameters to the parameters of the javascript.
  4. When calling the client action, fill the input parameters with the Widget Identifiers.

This should fix your problem.

Kind regards,

Remco Dekkinga

Solution

Great response by Eduardo and Remco.