BenjaminS
BenjaminS

Reputation: 11

Making JQuery work (linking the .js to the .html)

I am struggling with the most basic of JQuery magic: making it work. I had a much bigger JQuery file with some (previously) functional javascript, but my problem persisted even when I boiled it down to simply a page with a button that once clicked is supposed to fade out. I can only suppose I am referencing wrongly.

This is my html

<!DOCTYPE html>
<html>
  <head>
     <script type="text/javascript" src="script.js"></script>
     <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
  </head>
  <body>
    <button>Make me vanish!</button>
  </body>
</html>

And here is my script.js

$(document).ready(){
$('button').onclick(function(){
    $('button').fadeOut('fast');
});});

This is the link to the test-page itself(not working): http://folk.ntnu.no/benjamas/test.html

Upvotes: 0

Views: 508

Answers (4)

David J Eddy
David J Eddy

Reputation: 2037

1st: Add the jQ library itself:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Then in the code try this:

<input class="button">Make me vanish!</input>

...

$('.button').on('click', function(){
    $('.button').fadeOut('fast');
});

It does not have to be inside the $(document) object iirc; this is a "listener" of sorts.

Upvotes: 1

Oscar Broman
Oscar Broman

Reputation: 1127

Your script has errors, here's a working one:

$(document).ready(function() {
    $('button').click(function() {
        $('button').fadeOut('fast');
    });
});

Upvotes: 2

S&#233;bastien Renauld
S&#233;bastien Renauld

Reputation: 19662

You are missing jQuery itself. That, and you need to reverse the order of your script tags, as your script.js depends on jQuery (it actively uses the $ symbol).

Try this:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<script type="text/javascript" src="script.js"></script>

In addition, your JS itself is dubious - you either use the DOM onclick handler, or you use jQuery's $.click(). Not a mixture of both.

Upvotes: 5

adeneo
adeneo

Reputation: 318232

You'll need to load jQuery before any scripts that uses jQuery :

 <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
 <script type="text/javascript" src="script.js"></script>

And you do know that you're only including jQuery UI, and not the library itself ?

And your JS should look like :

$(function(){
    $('button').on('click', function(){
        $(this).fadeOut('fast');
    });
});

Upvotes: 4

Related Questions