Recently, I came across a requirement where I needed to create a custom JavaScript function which will change the date formatting on the provided string date parameter.
I tried creating normal JavaScript function in display template and tried calling it from another part of the template but the function was undefined and not found inside the display template. I got a little bit confused as I have created the JavaScript function in the same display template but still not able to find it there while calling. We can have a couple of ways to resolve the issue.
Solution 1
After some Googling, I found the cause of the issue and the solution as well. The possible reason is, the scoping of the display template not allowing us to consider external JavaScript function as a part of the scope to call inside display template.
The solution is to create a new function on Windows scope and the call in the desired place inside display template.
- window.MyTestFunction = function(myParam)
- {
- // your own logic to work on the param 'myParam'
- }
Calling the function,
- <a style="cursor:pointer" onclick='window.MyTestFunction(3)'>Call My custom JS function</a>
Solution 2
- Create a JavaScript file (MySampleJS.js) in the Display Templates/Search folder.
- Add the custom JS function into the MySampleJS.js file.
- Add the following code into the <body> tag below, to include the JS file in display template.
- <script>
- $includeScript(this.url, "~sitecollection/_catalogs/masterpage/Display Templates/Search/ MySampleJS.js");
- </script>

Prajakta PatilPosted Jun 13, 2018, 7:19 AM
Solution 1 worked for me.Thanks for the post
Matthew VennePosted Mar 29, 2018, 2:06 PM
I uploaded the above script into Display Templates/Search folder, called the script as you did in solution 2 and it did not run. My javascript is valid bc if I embed it a CEWP it works, but I need it to run in the display template to work search navigation etc.
Matthew VennePosted Mar 29, 2018, 2:04 PM
<script type="text/javascript">document.onload=function(){ var status_array =document.getElementsByClassName("sefl_status"); var pattern = new RegExp("Effective"); for (var i=0; i < status_array.length; i++) { if (pattern.test(status_array[i].innerHTML)===true) { status_array[i].style.color="green"; } } } console.log("Hi") </script>