Mr. Dr. Sushi
Mr. Dr. Sushi

Reputation: 481

SPFx - JavaScript function not firing

I have a slide component assembled on my render() method in my web part, it is displayed fine but the Javascript action "ShowSlide()" necessary to activate the slide is not being fired inside the $().ready()

I've placed the call inside the

public render(): void {  
  this.domElement.innerHTML = `
      <!-- build the slide here -->
      <div>
         <ul>
            .....
            ..... shortened for brevity 
            .....
         </ul>
      </div>
      <!-- CALL THE SLIDE using $().ready() - it doesn't work -->
      <script type="text/javascript">
        $(document).ready( function() 
            ShowSlide();
        });
      </script>
  `;
} 

I've ran out of ideas, I don't know what is preventing the function to be fired, I've added a little button to call this function manually and it works when it is called from pressing the button but not on the expected $().ready()

public render(): void {  
  this.domElement.innerHTML = `
      <!-- manual call for ShowSlide() -- it works when clicked! -->
      <input type="button" value="Start Slide" onClick="ShowSlide()"  />
      <!-- build the slide here -->
      <div>
         <ul>
            .....
            ..... shortened for brevity 
            .....
         </ul>
      </div>
      <!-- CALL THE SLIDE using $().ready() - it doesn't work -->
      <script type="text/javascript">
        $(document).ready( function()
            ShowSlide();
        });
      </script>
  `;
} 

Upvotes: 0

Views: 2772

Answers (1)

Mr. Dr. Sushi
Mr. Dr. Sushi

Reputation: 481

I found the solution for my problem! I learned about adding the script by creating the element inside HEAD, so all I had to do was the following:

  public render(): void {

    this.domElement.innerHTML = this.htmlContents;

    let head: any = document.getElementsByTagName("head")[0] || document.documentElement,
    script = document.createElement("script");
    script.type = "text/javascript";

    try {
        script.appendChild(document.createTextNode(this.htmlScript));
    } 
    catch (e) {
        script.text = this.htmlScript;
    }

    head.insertBefore(script, head.firstChild);
    head.removeChild(script);               
  }

I hope this helps anybody out there facing the same problem, took me 4 straight days researching, googling, reading everything I could, till I found an article on a blog about calling Azure functions inside SPFx, from there I could get the inspiration to connect the points and solve my problem!

Upvotes: 2

Related Questions