0

So I have a script like this inside my html:

<script> 
    var slider = new Slider("#pics", {
        tooltip: 'always'
    });
</script>

I was to put this script inside a JavaScript file, so am assuming I am going to turn it into a function

Like this:

function change_pics(){
var slider = new Slider("#pics", {
        tooltip: 'always'
    });
}

is this correct way ?

arjwolf
  • 181
  • 4
  • 16
  • You should not to forget include this js file into page. It can be function or variable, depends where you want to use it – demo Sep 16 '16 at 11:05
  • You don't need to turn that into a function. But, don't forget to add your js file in the html page – Pranesh Ravi Sep 16 '16 at 11:07
  • I'd recommend to follow this pattern. http://imrealashu.in/code/javascript/how-to-write-javascript-library/ – imrealashu Sep 16 '16 at 11:07

2 Answers2

0

You can put the script:

var slider = new Slider("#pics", {
    tooltip: 'always'
});

into a JS file, lets say "slider.js". Then you should import that JS file into your HTML file :

`<script src="PATH_TO_YOUR_JS_FILE"></script>`

You don't have to turn it into a function.

Oğuz Eroğlu
  • 103
  • 1
  • 9
  • I use the script in a input like this: `` This will not work, because I think I need an `onclick` or another property to trigger, no ? – arjwolf Sep 16 '16 at 11:20
  • What do you mean? Can you please be more specific? If you have to attach an onclick event to your button, you can also do this directly into a js file. – Oğuz Eroğlu Sep 16 '16 at 11:29
0

It's a good idea to compartmentalize as you mention, but don't absolutely have to. If you pop just what you have between the <script> tags into change.js without the function declaration, you can literally just put this in your HTML:

<script src="change.js"></script>

...and it will behave like you copy/pasted the contents wherever you put the tags.

Do put the explicit </script> in there, because <script ... /> works only in XHTML files.

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
BJ Black
  • 2,483
  • 9
  • 15
  • I use the script in a input like this: `` This will not work, because I think I need an `onclick` or another property to trigger, no ? – arjwolf Sep 16 '16 at 11:20
  • I think you're using this? http://seiyria.com/bootstrap-slider/. If so, you will need to pull in their css and JavaScript sources first (inside somewhere is traditional). Then if you put your own – BJ Black Sep 16 '16 at 11:28