Skip to main content
Home  › ... 2sxc Apps

turnOn Tutorials

Tutorial Home

Pass function the Module Id as parameter with turnOn

This page creates a unique DOM attribute and sets it on a div. turnOn then passes this attribute to a JavaScript function, which identifies the element with a queryselector and performs DOM manipulations.


In this tutorial you'll learn how to:
  • Create a unique DOM attribute
  • Pass it to a JavaScript function
Look at the text below to see the effect.

turnOn hasn't passed any parameters.

Source Code of this file

Below you'll see the source code of the file. Note that we're just showing the main part, and hiding some parts of the file which are not relevant for understanding the essentials. Click to expand the code

@inherits Custom.Hybrid.Razor14
@using ToSic.Razor.Blade;
<!-- unimportant stuff, hidden -->
Pass function the Module Id as parameter... <!-- unimportant stuff, hidden -->
<br>
@{
  // Use the PageService to activate turnOn
  Kit.Page.Activate("turnOn");

  // Create unique DOM attribute with Module Id
  var uniqueDomAttribute = "turn-on-example-" + CmsContext.Module.Id;
}

@* Inject attribute into DIV, to make it accessible for query *@
<div @uniqueDomAttribute>
  turnOn hasn't passed any parameters.
</div>

@* Passes the parameter domAttribute in a JSON format and executes the window.turnOnTutorial111.init function *@
<turnOn turn-on='{ "run": "window.turnOnTutorial111.init()", "data": { "domAttribute": "@uniqueDomAttribute" } }'></turnOn>

<script src="@App.Path/turn-on/_111-module.js"></script>

<!-- unimportant stuff, hidden -->

Source Code of _111-module.js

Below you'll see the source code of the file. Note that we're just showing the main part, and hiding some parts of the file which are not relevant for understanding the essentials. Click to expand the code

// Use an IFFE to ensure the variables are not exposed globaly
// See https://developer.mozilla.org/en-US/docs/Glossary/IIFE
(() => {
  // Data gets passed as a single object, so we need to deconstruct it.
  function init({domAttribute}) {
    // The element gets found in the DOM by a querySelector with the passed attribute
    const foundElement = document.querySelector(`[${domAttribute}]`)
    // Parameters get displayed in the DOM
    foundElement.innerText = `turnOn has passed the domAttribute: ${domAttribute}`;
  }
  
  const tt = window.turnOnTutorial111 = window.turnOnTutorial111 || {};
  tt.init = tt.init || init;
})();