3

I'm using SweetAlert.

http://tristanedwards.me/sweetalert

For this I need to initialize the plugin

<script src="lib/sweet-alert.min.js"></script>
<link rel="stylesheet" type="text/css" href="lib/sweet-alert.css">

I need to call the function swal from my file test.js, which is:

var accountnumber_c = $('#accountnumber_c').val();
if($('#accountnumber_c').val()=="")
{
    return;
}
swal('accountnumber_c');

This works in a php file but in test.js it gives "swal function is not defined".

Also how do I initialize the plugin in test.js?

1 Answers1

-1

As you want to refer swwtalert js in another js file you need to use following code to accomplish it:

 var script = document.createElement('script');
    script.src = "/path/to/the/other/file.js";
    document.getElementsByTagName('script')[0].parentNode.appendChild(script);
    //for CSS file
    $('head').append('<link rel="stylesheet" href="your/cssfilelocation/filename.css" type="text/css" />'); 

In case you need to include jquery before sweetalert, use similar code to add jquery before it.

Ashutosh Nigam
  • 868
  • 8
  • 27
  • @FelixKling He is not having any issue in php. his question is on how to reference another js (the js file he mentioned) in his custom js. To my understanding he is planning to move all js in on separate js file and refer that only in php file. His question is "How do I initialize plugin in JS" as he wants to test js as complete unit. – Ashutosh Nigam Dec 12 '14 at 06:31
  • That does not work Uncaught ReferenceError: swal is not defined – asvasdv asdvsadvs Dec 12 '14 at 06:44
  • This is the test.js $(document).ready(function() { $('#accountnumber_c').blur(function(){ var script = document.createElement('script'); script.src = "swal/lib/sweet-alert.min.js"; document.getElementsByTagName('script')[0].parentNode.appendChild(script); swal(accountnumber_c); }); }); – asvasdv asdvsadvs Dec 12 '14 at 06:45
  • @asvasdvasdvsadvs: That can't work because the file is not loaded yet when you call `swal`. – Felix Kling Dec 12 '14 at 06:47
  • 1
    @asvasdvasdvsadvs the inclusion of sweet-alert.min,js should be the first thing in the test.js file. please do console.log(document.getElementsByTagName('script')) to verify if the js file is added. – Ashutosh Nigam Dec 12 '14 at 06:58
  • @asvasdvasdvsadvs do you need jquery also before using sweetalert by any chance? – Ashutosh Nigam Dec 12 '14 at 07:02
  • The problem was I had to load sweet-alert.min.js first. However I am unable to load the css file. – asvasdv asdvsadvs Dec 12 '14 at 07:05
  • 1
    That was my worry that css can create issue. you can load it as follows, as you are using jquery: $('head').append(''); – Ashutosh Nigam Dec 12 '14 at 08:03
  • Yes I was able to insert the style-sheet with the above code. Thank you – asvasdv asdvsadvs Dec 12 '14 at 08:51
  • So can you accept my solution as answer as it solved your query :) – Ashutosh Nigam Dec 12 '14 at 09:04