Sparx401
Sparx401

Reputation: 55

jQuery not working in Chrome 18

Nothing in jQuery appears to be working in Chrome for me. My version is 18.0.1025.151 m. The javascript is in the file test.js:

$('#paragraph').click(function() {
$('#paragraph').hide();
});

And the html is this:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>jQuery Example</title>

    <script src="jquery-1.7.1.min.js"></script>
    <script src="test.js"></script>
</head>
<body>
    <p id="paragraph">This is my paragragh 401!</p>
</body>
</html>

I have triple-checked that the jQuery file is where it's supposed to be. Essentially, the code is supposed to make the paragraph disappear when clicked on. Seems simple enough and syntactically correct. I chose such a simple code because while regular javascript statements and code work fine (such as alert() and whatnot), absolutely nothing in jQuery has worked so far at all.

Here's the strange part though. When using the console in Chrome's developer tools, if I input the exact same jQuery stuff and hit enter, it actually works and functions how it's supposed to.

Does this have anything to do with Chrome's security structure or something?

Edit: Also, I should note that I have not yet uploaded these files on my server yet. This is on localhost (I'm using xammp for what it's worth), so perhaps that may help shed some light on the issue.

Upvotes: 1

Views: 3362

Answers (3)

asawyer
asawyer

Reputation: 17818

It's executing before the DOM is ready. It should look like this:

$(function(){
    $('#paragraph').click(function() {
        $('#paragraph').hide();
    });
});

To address the comment below:

http://api.jquery.com/ready/

The .ready() method is typically used with an anonymous function:

$(document).ready(function() {
  // Handler for .ready() called.
});

Which is equivalent to calling:

$(function() {
 // Handler for .ready() called.
});

Upvotes: 2

elclanrs
elclanrs

Reputation: 94151

You have to wrap it in document ready. That's probably your problem. Also you can use $(this) or cache the selector.

$(function () {
    $('#paragraph').click(function () {
        $(this).hide();
    });
});

Upvotes: 0

meder omuraliev
meder omuraliev

Reputation: 186762

Wrap the code in a document ready, or put test.js before the end body tag.

Upvotes: 3

Related Questions