How do you declare and call a function with $ in Jquery?

0

I have this problem ..

TypeError: $.slideShow is not a function

I'm trying to call a function with the dollar sign $ , but it does not work. The statement is as follows. in my index.html file ..

<script src="js/script.js"></script>
<script>
    $.slideShow();
</script>

And in my script.js file I have it in the following way ..

$(document).on("ready", function(){
    $.slideShow = function( opcciones ){
     Console.log("Slide");
    }
});

But it tells me that there is no function $.slideShow

my directory is conformed with

Project  -js    -script.js

-index.html

PS: at the moment of removing the function that I created. and just write console.log() in the script of document if it works, the problem arises when calling the function .. I use the Jquery version: jquery-2.1.4.min.js . Thanks ..

    
asked by JuanL 22.04.2018 в 20:55
source

2 answers

2

It is very likely that you are not referencing your file script.js well, if it had the code that you showed and it was well included, the code should work.

$(function() {
  //$.slideShow("opciones"); Error

  /*Este sería el código de 'script.js'*/
  $.slideShow = function(opciones) {
    console.log("Slide");
  }

  /*Aquí no da error*/
  $.slideShow("opciones");

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Something else

Keep in mind that document.ready is obsolete from jQuery 3, you should use function instead.

You had a syntax error in Console.log

    
answered by 22.04.2018 в 21:23
0

The explanation of why this fails is because you have two scripts in your code:

<script src="js/script.js"></script>
<script>
    $.slideShow();
</script>

The script.js is loaded but since it has a $(document).on("ready"... it does not run until jquery and the page has been fully loaded.

The second block $.slideShow(); as it does not have the $(document).on("ready"... is executed instantaneously and therefore that function does not exist.

The solution is simply to add in the second block $(document).on("ready"... or as A. Cedano comments better $(function() { .... });

    
answered by 24.04.2018 в 11:01