Page 1 of 1

How to add JavaScript dynamically from a controller?

Posted: Fri May 28, 2010 10:12 am
by jstuardo
Hello....

I need to add a <script> tag that has a .js source. Also, I need to add a <script> block. And finally, I have to add an onload event to the <BODY> tag. All this, from the contact controller. How can I do it?

The final goal is to add a GoogleMap to the contact page.

Any help will be greatly appreciated.

Jaime

Re: How to add JavaScript dynamically from a controller?

Posted: Fri May 28, 2010 12:39 pm
by Qphoria
You can use:

Code: Select all

$this->document->addScript('catalog/view/javascript/xxxx.js');
in the controller

Body onload is so 1999 :P

There are better ways now
Using jquery (which already comes with opencart) you have

Code: Select all

$(document).ready(function () {
    ....Do js stuff here...
});
or just using normal js you can use:

Code: Select all

window.onload = functionA;

Re: How to add JavaScript dynamically from a controller?

Posted: Sat May 29, 2010 6:25 am
by jstuardo
Thanks a lot.. it worked perfect, but I needed to place the "ready" function inside a .js file because I did not find a way to add a script block inside the page using $this->document.

Cheers
Jaime

Re: How to add JavaScript dynamically from a controller?

Posted: Sat May 29, 2010 11:50 am
by Qphoria
Yes, that is where it is supposed to be placed

Re: How to add JavaScript dynamically from a controller?

Posted: Wed Sep 18, 2019 9:39 pm
by Jansuh
Mabye not really on topic but could you tell me how to run the following from a information page?

Code: Select all

<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "FAQPage",
  "mainEntity": [{
    "@type": "Question",
    "name": "Wat zijn Akoya parels?",
    "acceptedAnswer": {
      "@type": "Answer",
      "text": "Akoya parels zijn ..... enz"
    }
  },{
    "@type": "Question",
    "name": "Waar komen Akoya parels vandaan?",
    "acceptedAnswer": {
      "@type": "Answer",
      "text": "Akoya parels komen voornamelijk uit Japan"
    }
  },{
    "@type": "Question",
    "name": "Hoe worden Akoya parels gekweekt?",
    "acceptedAnswer": {
      "@type": "Answer",
      "text": "Akoya parels worden gekweekt door"
    }
  },{
    "@type": "Question",
    "name": "",
    "acceptedAnswer": {
      "@type": "Answer",
      "text": ""
    }
  }]
}
</script>
Must be simple but i cannot find how to anywhere. Thanks

Re: How to add JavaScript dynamically from a controller?

Posted: Sat Sep 28, 2019 1:48 pm
by cedcommerceteam
Hello Jansuh,

I suggest you to write JS in respective template file & send dynamic data in JS that will be more easier instead of creating a dynamic JS, as you know it is very difficult to handle a JS code.

Thanks.
Kind Regards: